Creating a Snake AI using Deep Q-Learning (DQN) or Genetic Algorithms (GA) is a fun and educational challenge. Below, I’ll guide you through building a Snake game-playing AI using Deep Q-Learning with PyTorch .
🐍 Snake Game + AI Using Deep Q-Network (DQN) with PyTorch
This example will:
Use a simple convolutional neural network (CNN) to observe the game state.
Train an agent using Deep Q-Learning (DQN) .
Save and load trained models.
🔧 Requirements
Install these if not already installed:
bash Copy code
pip install pygame torch numpy matplotlib collections
📁 Folder Structure
code Copy code
snake_ai/
│
├── snake_game.py # The environment
├── dqn_agent.py # DQN Agent
├── train.py # Training loop
└── model.pth # Saved model (after training)
1️⃣ snake_game.py – Snake Environment for AI
python Copy code
# snake_game.py
import pygame
import random
pygame.init()
BLOCK_SIZE = 20
WIDTH, HEIGHT = 400, 400
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
ACTIONS = [0, 1, 2, 3] # Up, Down, Left, Right
class SnakeGameAI:
def __init__(self):
self.display = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake AI")
self.clock = pygame.time.Clock()
self.reset()
def reset(self):
self.snake = [(100, 100), (80, 100), (60, 100)]
self.direction = 'RIGHT'
self.score = 0
self.frame_iteration = 0
self.apple = self._place_food()
self.game_over = False
return self.get_state()
def _place_food(self):
while True:
x = random.randint(0, (WIDTH - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
y = random.randint(0, (HEIGHT - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
if (x, y) not in self.snake:
return (x, y)
def play_step(self, action):
self.frame_iteration += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
self._move(action)
self.snake.append(self.head)
reward = 0
if self._is_collision():
reward = -10
self.game_over = True
return self.get_state(), reward, self.game_over
if self.head == self.apple:
self.score += 1
reward = 10
self.apple = self._place_food()
else:
self.snake.pop(0)
self._update_ui()
self.clock.tick(50)
return self.get_state(), reward, self.game_over
def _is_collision(self, pt=None):
if pt is None:
pt = self.head
x, y = pt
if x < 0 or y < 0 or x >= WIDTH or y >= HEIGHT:
return True
if pt in self.snake[:-1]:
return True
return False
def _update_ui(self):
self.display.fill(BLACK)
for pos in self.snake:
pygame.draw.rect(self.display, GREEN, (*pos, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(self.display, RED, (*self.apple, BLOCK_SIZE, BLOCK_SIZE))
pygame.display.flip()
def _move(self, action):
directions = ['UP', 'RIGHT', 'DOWN', 'LEFT']
idx = directions.index(self.direction)
if action[1]: # right turn
new_idx = (idx + 1) % 4
elif action[2]: # left turn
new_idx = (idx - 1) % 4
else: # go straight
new_idx = idx
self.direction = directions[new_idx]
x, y = self.snake[-1]
if self.direction == 'UP':
y -= BLOCK_SIZE
elif self.direction == 'DOWN':
y += BLOCK_SIZE
elif self.direction == 'LEFT':
x -= BLOCK_SIZE
elif self.direction == 'RIGHT':
x += BLOCK_SIZE
self.head = (x, y)
def get_state(self):
head = self.head
point_l = (head[0] - BLOCK_SIZE, head[1])
point_r = (head[0] + BLOCK_SIZE, head[1])
point_u = (head[0], head[1] - BLOCK_SIZE)
point_d = (head[0], head[1] + BLOCK_SIZE)
dir_l = self.direction == 'LEFT'
dir_r = self.direction == 'RIGHT'
dir_u = self.direction == 'UP'
dir_d = self.direction == 'DOWN'
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
(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
(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,
# Apple location
self.apple[0] < head[0], # apple left
self.apple[0] > head[0], # apple right
self.apple[1] < head[1], # apple up
self.apple[1] > head[1] # apple down
]
return tuple(state)
2️⃣ dqn_agent.py – Deep Q-Network Agent
3️⃣ train.py – Training Loop
python Copy code
# train.py
import torch
import pygame
from snake_game import SnakeGameAI
from dqn_agent import DQNAgent
import matplotlib.pyplot as plt
import numpy as np
def train():
plot_scores = []
plot_mean_scores = []
total_score = 0
record = 0
game = SnakeGameAI()
agent = DQNAgent()
while True:
state_old = game.get_state()
action_index = agent.act(state_old)
action = [0, 0, 0]
action[action_index] = 1 # Convert to [left, straight, right]
state_new, reward, game_over = game.play_step(action)
agent.remember(state_old, action_index, reward, state_new, game_over)
if game_over:
game.reset()
agent.n_games += 1
print(f"Game {agent.n_games}, Score: {game.score}, Record: {record}")
if game.score > record:
record = game.score
agent.save()
plot_scores.append(game.score)
total_score += game.score
mean_score = total_score / agent.n_games
plot_mean_scores.append(mean_score)
plot(plot_scores, plot_mean_scores)
agent.replay()
def plot(scores, mean_scores):
plt.clf()
plt.title('Training...')
plt.xlabel('Number of Games')
plt.ylabel('Score')
plt.plot(scores)
plt.plot(mean_scores)
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.pause(0.001)
if __name__ == '__main__':
train()
🧠 Notes on AI Strategy
The AI receives a 11-dimensional state vector describing:
Collision danger in front, left, right
Current direction
Relative position of the apple
It learns to map this to one of three actions: [left, straight, right].
Uses experience replay , epsilon-greedy exploration , and target networks for stability.
🚀 To Run the AI
bash Copy code
python train.py
After some episodes, you'll see the AI improve!
🧬 Optional: Add Genetic Algorithm (GA)
If you want to use Genetic Algorithms instead of DQN:
Replace the DQN with a feedforward neural net that uses weights evolved via GA.
Define a fitness function based on score/time survived.
Evolve generations using selection, crossover, mutation.
Let me know if you'd like that version too!
✅ Summary
✅ You now have:
A working Snake game controlled by AI
A PyTorch-based DQN agent
Experience replay and target networks
Saving/loading functionality
Real-time training visualization
Would you like the Genetic Algorithm version next? Or maybe deploy this to WebAssembly or Unity ? Let me know!