Okay, this is a significant jump in complexity from the basic game! Creating an AI that plays Snake using Deep Q-Learning (DQN) involves:
- Refactoring the Game: Making the game environment suitable for an AI agent to interact with.
- Defining State and Action Space: How the AI perceives the game (state) and what moves it can make (actions).
- Reward System: How the AI knows if it's doing well or poorly.
- Deep Q-Learning (DQN) Architecture:
- A neural network (using PyTorch).
- An experience replay buffer.
- An epsilon-greedy policy for exploration.
- A target network.
- Training Loop: Interacting with the game, collecting experiences, and updating the neural network.
I'll use PyTorch for the Deep Q-Learning part, as it's often a bit more concise for these kinds of implementations. Genetic algorithms could be used to evolve a neural network's weights or simple policies, but for sequential decision-making like this, DQN is a more standard and often more effective approach.
Understanding the AI Concepts
- Reinforcement Learning (RL): A paradigm where an agent learns to make decisions by taking actions in an environment to maximize a cumulative reward.
- Deep Q-Learning (DQN): A specific RL algorithm that uses a neural network (the "Deep" part) to approximate the optimal Q-function. The Q-function estimates the expected future reward for taking a particular action in a given state.
- State: The current observation of the environment (e.g., snake's position, apple's position, dangers).
- Action: The moves the agent can make (e.g., turn left, turn right, go straight).
- Reward: A numerical value indicating the immediate feedback for an action (e.g.,
+10 for eating an apple, -10 for crashing, -0.1 for each step).
- Experience Replay: Storing past
(state, action, reward, next_state, done) tuples and sampling from them randomly for training. This helps stabilize training and breaks correlations between consecutive experiences.
- Target Network: A second, periodically updated neural network used to calculate the target Q-values. This stabilizes the training by providing a fixed target for a period.
- Epsilon-Greedy Policy: During training, the agent will sometimes take a random action (
epsilon probability) to explore the environment, and sometimes take the action recommended by the network (1 - epsilon probability) to exploit its learned knowledge. epsilon usually decays over time.
- Gamma (Discount Factor): A value between 0 and 1 that discounts future rewards. A higher
gamma means the agent cares more about long-term rewards.
Step-by-Step Code Implementation
First, let's modify your SnakeGame class to be more AI-friendly (e.g., providing a state, taking an action, returning reward). Then, we'll build the PyTorch DQN agent.
1. Update snake_game.py (Save as snake_game_env.py or similar)
This version will have a SnakeGameEnv class that acts as the environment for our AI. It will provide methods like reset(), get_state(), and perform_action().
# snake_game_env.py
import pygame
import sys
import random
from collections import namedtuple
# Game Constants
WIDTH, HEIGHT = 800, 600
BLOCK_SIZE = 20
# FPS is for display, AI training will run much faster logic
FPS_DISPLAY = 60 # Set to 0 for fastest training, or a value like 60 to visualize during training
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Direction enum for clarity
Point = namedtuple('Point', 'x, y')
# Directions
RIGHT = 1
LEFT = -1
UP = 2
DOWN = -2
class SnakeGameEnv:
def __init__(self, w=WIDTH, h=HEIGHT):
pygame.init()
self.w = w
self.h = h
self.display = pygame.display.set_mode((self.w, self.h))
pygame.display.set_caption('Snake AI Game')
self.clock = pygame.time.Clock()
self.font = pygame.font.Font(None, 36) # Default font
self.reset()
def reset(self):
self.direction = RIGHT # Start moving right
self.head = Point(self.w / 2, self.h / 2) # Start in the middle
self.snake = [self.head,
Point(self.head.x - BLOCK_SIZE, self.head.y),
Point(self.head.x - (2 * BLOCK_SIZE), self.head.y)]
self.score = 0
self.apple = None
self._place_apple()
self.frame_iteration = 0
return self.get_state() # Return initial state
def _place_apple(self):
x = random.randint(0, (self.w - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
y = random.randint(0, (self.h - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
self.apple = Point(x, y)
if self.apple in self.snake: # Ensure apple doesn't spawn on snake
self._place_apple()
def play_step(self, action):
self.frame_iteration += 1
reward = 0
game_over = False
# 1. Collect user input (for human play/exit)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 2. Move
self._move(action) # Update the head
self.snake.append(self.head)
# 3. Check if game over
if self._is_collision() or self.frame_iteration > 100 * len(self.snake): # Punish infinite loops
game_over = True
reward = -10 # Crash penalty
return reward, game_over, self.score
# 4. Place new apple or just move
if self.head == self.apple:
self.score += 1
reward = 10 # Apple reward
self._place_apple()
else:
self.snake.pop(0) # Remove tail if no apple eaten
reward = -0.1 # Small penalty for each step to encourage finding food
# 5. Update UI and clock
self._update_ui()
self.clock.tick(FPS_DISPLAY) # Control display speed
return reward, game_over, self.score
def _is_collision(self, pt=None):
if pt is None:
pt = self.head
# Hits boundary
if pt.x > self.w - BLOCK_SIZE or pt.x < 0 or pt.y > self.h - BLOCK_SIZE or pt.y < 0:
return True
# Hits itself
if pt in self.snake[1:]: # Don't check against the head itself
return True
return False
def _move(self, action):
# [straight, right, left]
clockwise = [RIGHT, DOWN, LEFT, UP]
idx = clockwise.index(self.direction)
if action[0] == 1: # Straight
new_direction = clockwise[idx]
elif action[1] == 1: # Right turn
new_direction = clockwise[(idx + 1) % 4]
else: # Left turn
new_direction = clockwise[(idx - 1 + 4) % 4]
self.direction = new_direction
x = self.head.x
y = self.head.y
if self.direction == RIGHT:
x += BLOCK_SIZE
elif self.direction == LEFT:
x -= BLOCK_SIZE
elif self.direction == DOWN:
y += BLOCK_SIZE
elif self.direction == UP:
y -= BLOCK_SIZE
self.head = Point(x, y)
def _update_ui(self):
self.display.fill(BLACK)
for pt in self.snake:
pygame.draw.rect(self.display, GREEN, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(self.display, BLUE, pygame.Rect(self.snake[0].x, self.snake[0].y, BLOCK_SIZE, BLOCK_SIZE)) # Tail tip
pygame.draw.rect(self.display, RED, pygame.Rect(self.apple.x, self.apple.y, BLOCK_SIZE, BLOCK_SIZE))
text = self.font.render("Score: " + str(self.score), True, WHITE)
self.display.blit(text, [0, 0])
pygame.display.flip()
def get_state(self):
head = self.head
# Define points around the head for collision checking
point_l = Point(head.x - BLOCK_SIZE, head.y)
point_r = Point(head.x + BLOCK_SIZE, head.y)
point_u = Point(head.x, head.y - BLOCK_SIZE)
point_d = Point(head.x, head.y + BLOCK_SIZE)
dir_l = self.direction == LEFT
dir_r = self.direction == RIGHT
dir_u = self.direction == UP
dir_d = self.direction == DOWN
# State representation for the AI
state = [
# Danger straight
(dir_r and self._is_collision(point_r)) or
(dir_l and self._is_collision(point_l)) or
(dir_u and self._is_collision(point_u)) or
(dir_d and self._is_collision(point_d)),
# Danger right (turn right from current direction)
(dir_u and self._is_collision(point_r)) or
(dir_d and self._is_collision(point_l)) or
(dir_l and self._is_collision(point_u)) or
(dir_r and self._is_collision(point_d)),
# Danger left (turn left from current direction)
(dir_d and self._is_collision(point_r)) or
(dir_u and self._is_collision(point_l)) or
(dir_r and self._is_collision(point_u)) or
(dir_l and self._is_collision(point_d)),
# Move direction
dir_l,
dir_r,
dir_u,
dir_d,
# Food location
self.apple.x < head.x, # food left
self.apple.x > head.x, # food right
self.apple.y < head.y, # food up
self.apple.y > head.y # food down
]
return [int(x) for x in state] # Convert booleans to integers (0 or 1)
2. Create the DQN Agent (agent.py)
This file will contain the PyTorch neural network, the Q-learning trainer, and the agent logic.
# agent.py
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import numpy as np
from collections import deque
import random
# For saving model
import os
MAX_MEMORY = 100_000 # Max experiences to store in replay buffer
BATCH_SIZE = 1000 # Number of samples to train on at once
LR = 0.001 # Learning rate
GAMMA = 0.9 # Discount factor for future rewards
class Linear_QNet(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.linear1 = nn.Linear(input_size, hidden_size)
self.linear2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
x = F.relu(self.linear1(x))
x = self.linear2(x)
return x
class QTrainer:
def __init__(self, model, lr, gamma):
self.lr = lr
self.gamma = gamma
self.model = model
self.optimizer = optim.Adam(model.parameters(), lr=self.lr)
self.criterion = nn.MSELoss() # Mean Squared Error Loss
def train_step(self, state, action, reward, next_state, done):
state = torch.tensor(state, dtype=torch.float)
next_state = torch.tensor(next_state, dtype=torch.float)
action = torch.tensor(action, dtype=torch.long)
reward = torch.tensor(reward, dtype=torch.float)
# Handle batch training
if len(state.shape) == 1:
# Add a batch dimension if it's a single sample
state = torch.unsqueeze(state, 0)
next_state = torch.unsqueeze(next_state, 0)
action = torch.unsqueeze(action, 0)
reward = torch.unsqueeze(reward, 0)
done = (done, ) # Make it a tuple
# 1. Predict Q values with current state
pred = self.model(state)
# 2. Calculate target Q values (Bellman equation)
# Q_new = r + gamma * max(Q(s')) if not done
# Q_new = r if done
target = pred.clone() # Start with current predictions
for idx in range(len(done)):
Q_new = reward[idx]
if not done[idx]:
Q_new = reward[idx] + self.gamma * torch.max(self.model(next_state[idx]))
target[idx][torch.argmax(action[idx]).item()] = Q_new # Update the Q value for the chosen action
self.optimizer.zero_grad() # Clear gradients
loss = self.criterion(target, pred) # Calculate loss
loss.backward() # Backpropagate
self.optimizer.step() # Update weights
class Agent:
def __init__(self):
self.n_games = 0
self.epsilon = 0 # Randomness
self.gamma = GAMMA
self.memory = deque(maxlen=MAX_MEMORY) # popleft() when maxlen reached
self.model = Linear_QNet(11, 256, 3) # Input: 11 (state size), Hidden: 256, Output: 3 (actions)
self.trainer = QTrainer(self.model, lr=LR, gamma=self.gamma)
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def train_long_memory(self):
if len(self.memory) > BATCH_SIZE:
mini_sample = random.sample(self.memory, BATCH_SIZE) # List of tuples
else:
mini_sample = self.memory
# Unzip the batch
states, actions, rewards, next_states, dones = zip(*mini_sample)
self.trainer.train_step(states, actions, rewards, next_states, dones)
def train_short_memory(self, state, action, reward, next_state, done):
self.trainer.train_step(state, action, reward, next_state, done)
def get_action(self, state):
# Random moves: tradeoff exploration / exploitation
# As games increase, epsilon decreases -> less random moves
self.epsilon = 80 - self.n_games # Start high, decay
final_move = [0,0,0] # [straight, right, left]
if random.randint(0, 200) < self.epsilon: # Epsilon-greedy
move = random.randint(0, 2)
final_move[move] = 1
else:
state0 = torch.tensor(state, dtype=torch.float)
prediction = self.model(state0) # Get Q-values for each action
move = torch.argmax(prediction).item() # Choose action with highest Q-value
final_move[move] = 1
return final_move
def save_model(self, file_name='model.pth'):
model_folder = './model'
if not os.path.exists(model_folder):
os.makedirs(model_folder)
file_name = os.path.join(model_folder, file_name)
torch.save(self.model.state_dict(), file_name)
print(f"Model saved to {file_name}")
def load_model(self, file_name='model.pth'):
model_path = os.path.join('./model', file_name)
if os.path.exists(model_path):
self.model.load_state_dict(torch.load(model_path))
self.model.eval() # Set model to evaluation mode
print(f"Model loaded from {model_path}")
else:
print(f"No model found at {model_path}. Starting fresh.")
3. Main Training Script (main.py)
This script orchestrates the training process.
# main.py
import pygame
from snake_game_env import SnakeGameEnv, FPS_DISPLAY # Import the modified game env
from agent import Agent
import matplotlib.pyplot as plt
from IPython import display # for plotting in notebooks, remove if not in notebook
import time
def plot_scores(scores, mean_scores):
display.clear_output(wait=True) # For notebooks
display.display(plt.gcf()) # For notebooks
plt.clf() # Clear current figure
plt.title('Training Progress')
plt.xlabel('Number of Games')
plt.ylabel('Score')
plt.plot(scores, label='Score')
plt.plot(mean_scores, label='Mean Score')
plt.ylim(ymin=0)
plt.text(len(scores)-1, scores[-1], str(scores[-1]))
plt.text(len(mean_scores)-1, mean_scores[-1], str(round(mean_scores[-1], 2)))
plt.legend()
plt.grid(True)
plt.show(block=False) # Non-blocking plot
plt.pause(.1) # Pause for plot to update
def train():
plot_scores_list = []
plot_mean_scores = []
total_score = 0
record_score = 0
env = SnakeGameEnv() # Our game environment
agent = Agent() # Our DQN agent
# Optional: Load a pre-trained model if available
# agent.load_model()
while True:
# Get old state
state_old = env.get_state()
# Get move from agent
final_move = agent.get_action(state_old)
# Perform move and get new state
reward, done, score = env.play_step(final_move)
state_new = env.get_state()
# Train short memory (one step)
agent.train_short_memory(state_old, final_move, reward, state_new, done)
# Remember for long memory (experience replay)
agent.remember(state_old, final_move, reward, state_new, done)
if done:
# Train long memory (batch from replay buffer)
env.reset() # Reset game
agent.n_games += 1
agent.train_long_memory()
if score > record_score:
record_score = score
agent.save_model() # Save best model
print(f'Game: {agent.n_games}, Score: {score}, Record: {record_score}')
plot_scores_list.append(score)
total_score += score
mean_score = total_score / agent.n_games
plot_mean_scores.append(mean_score)
plot_scores(plot_scores_list, plot_mean_scores)
if __name__ == '__main__':
train()
How to Run
- Save the files:
- Save the first code block as
snake_game_env.py.
- Save the second code block as
agent.py.
- Save the third code block as
main.py.
- Install Libraries:
pip install pygame torch numpy matplotlib
(Note: torch installation might vary based on your OS and CUDA requirements. Refer to PyTorch website for specific instructions).
- Run the training:
python main.py
Explanation and Notes:
- State Representation:
- The
get_state() method now returns an 11-element binary list.
- The first 3 elements (
danger_straight, danger_right, danger_left) indicate immediate collision threats relative to the snake's current heading.
- The next 4 elements (
dir_l, dir_r, dir_u, dir_d) indicate the snake's current absolute direction.
- The last 4 elements (
food_left, food_right, food_up, food_down) indicate the apple's position relative to the snake's head.
- This compressed state is much easier for a neural network to learn from than raw pixel data.
- Action Space:
- The AI outputs one of three relative actions:
[1,0,0] (straight), [0,1,0] (turn right), [0,0,1] (turn left).
_move() in SnakeGameEnv translates these relative actions into absolute directions. This makes the learning problem easier as the AI doesn't need to relearn "up" when its "right" is now "up".
- Reward Function:
+10: Eating an apple.
-10: Crashing (wall or self).
-0.1: Taking a step (encourages efficiency, prevents pointless wandering).
- Added a
frame_iteration check in play_step to give a negative reward and end the game if the snake moves too many steps without eating (punishes infinite loops).
Agent Class:
Linear_QNet: A simple feedforward neural network. ReLU activation is used in the hidden layer.
QTrainer: Handles the optimization process (loss calculation, backpropagation, weight updates).
remember(): Stores the experiences in the deque memory.
train_long_memory(): Samples a BATCH_SIZE of experiences from memory and trains the network. This is crucial for stable DQN training.
train_short_memory(): Trains on the immediate last step.
get_action(): Implements the epsilon-greedy policy. epsilon decreases as the number of games (n_games) increases, making the agent explore less and exploit its learned knowledge more over time.
Potential Improvements & Further AI Algorithms:
- Double DQN / Dueling DQN / Prioritized Experience Replay: More advanced DQN techniques to further stabilize and improve training.
- Hyperparameter Tuning: Experiment with
LR, GAMMA, BATCH_SIZE, MAX_MEMORY, epsilon decay schedule, and hidden_size for better performance.
- Convolutional Neural Networks (CNNs): If you wanted to feed raw pixel data to the AI, you would need CNNs, but this is much more complex for this game.
- Proximal Policy Optimization (PPO) / A2C: Other powerful RL algorithms for continuous control or more complex environments, but they have different setup requirements than Q-learning.
- Genetic Algorithms (GA):
- While not used here for the primary learning, GAs could be used in a few ways:
- Hyperparameter Optimization: A GA could search for the best
LR, GAMMA, etc., for your DQN.
- Direct Policy Evolution: For simpler snake policies (e.g., small neural networks with few weights), you could evolve the weights directly using a GA. Each "individual" in the GA would be a set of neural network weights. You would evaluate their fitness by letting them play a few games of Snake. This bypasses backpropagation and reward functions directly. However, for deep networks, this becomes computationally very expensive.
- Neuroevolution: A hybrid approach where GAs evolve the architecture of the neural network, and then RL (like DQN) trains the weights, or vice-versa.
This DQN setup is a good starting point for an autonomous Snake player and showcases the power of reinforcement learning. Training might take some time, but you should eventually see the snake learn to find apples and avoid obstacles!