A complete Deep Reinforcement Learning project that trains an AI agent to play the classic Snake game using a Deep Q-Network (DQN) implemented from scratch with PyTorch.
- Overview
- Reinforcement Learning Background
- DQN Algorithm
- Project Architecture
- Setup & Installation
- Training
- Evaluation
- Hyperparameters
- Project Structure
- Screenshots
- Future Improvements
This project implements a Deep Q-Network (DQN) agent that learns to play Snake through reinforcement learning. The agent receives a compact 11-dimensional binary state representation, takes actions relative to its current direction, and learns an optimal policy through experience replay and target network stabilization.
Key Features:
- โ Complete DQN implementation from scratch (no RL libraries)
- โ Real-time Pygame visualization during training
- โ Demo/watch mode for trained agents
- โ Comprehensive metrics tracking and plotting
- โ Model checkpointing and best model saving
- โ DQN vs Random agent comparison
- โ Adjustable training speed (FPS control)
- โ Clean modular architecture
Reinforcement Learning (RL) is a paradigm where an agent learns to make decisions by interacting with an environment. At each time step:
- The agent observes the current state
s - Selects an action
abased on its policy - Receives a reward
rand transitions to a new states' - The goal is to maximize the cumulative discounted reward
The agent learns from trial and error, discovering which actions lead to higher long-term rewards through the Bellman equation.
The Deep Q-Network combines Q-learning with deep neural networks:
| Component | Description |
|---|---|
| Online Q-Network | Neural network that predicts Q-values for each action |
| Target Q-Network | Stabilized copy of the online network for computing targets |
| Experience Replay | Buffer of past transitions, randomly sampled for training |
| Epsilon-Greedy | Exploration strategy that decays over time |
Q(s, a) = r + ฮณ ร max_a'[Q_target(s', a')]
Where:
Q(s, a)is the estimated value of taking actionain statesris the immediate rewardฮณ(gamma) is the discount factor for future rewardsQ_targetuses the target network for stable targets
[danger_straight, danger_left, danger_right,
food_left, food_right, food_up, food_down,
moving_left, moving_right, moving_up, moving_down]
| Action | Description |
|---|---|
| 0 | Move Straight |
| 1 | Turn Left |
| 2 | Turn Right |
Input State (11) โ FC(256) โ ReLU โ FC(128) โ ReLU โ FC(64) โ ReLU โ Q-values (3)
The architecture separates concerns into distinct modules:
- Game Logic (
snake_game.py) โ Environment dynamics - RL Logic (
agent.py,model.py,replay_buffer.py) โ DQN algorithm - Rendering (
renderer.py) โ Pygame visualization - Training/Evaluation (
train.py,evaluate.py) โ Orchestration
- Python 3.8 or higher
- pip package manager
# Clone or navigate to the project directory
cd "RL Project"
# Install dependencies
pip install -r requirements.txtpython train.py# Train for 1000 episodes
python train.py --episodes 1000
# Train without rendering (faster)
python train.py --no-render --episodes 1000
# Set custom training FPS
python train.py --fps 300
# Resume from checkpoint
python train.py --resume checkpoints/checkpoint_ep500.pth| Key | Action |
|---|---|
ESC |
Quit training |
SPACE |
Pause/Resume |
โ |
Increase FPS |
โ |
Decrease FPS |
python evaluate.pypython evaluate.py --compare --episodes 100python evaluate.py --benchmark --episodes 200python evaluate.py --model checkpoints/checkpoint_ep500.pth --fps 20| Parameter | Value | Description |
|---|---|---|
gamma |
0.99 | Discount factor |
learning_rate |
0.001 | Adam optimizer LR |
batch_size |
64 | Minibatch size |
replay_buffer_size |
100,000 | Max replay memory |
epsilon_start |
1.0 | Initial exploration |
epsilon_min |
0.01 | Min exploration |
epsilon_decay |
0.995 | Decay per episode |
target_update_freq |
1,000 | Target sync interval |
hidden_layers |
(256, 128, 64) | Network architecture |
| Event | Reward |
|---|---|
| Eat food | +10.0 |
| Collision (game over) | -10.0 |
| Each step | -0.1 |
| Move closer to food | +0.5 |
| Move away from food | -0.5 |
| Looping movement | -1.0 |
RL Project/
โ
โโโ config.py # All hyperparameters and configuration
โโโ snake_game.py # Snake game environment (RL interface)
โโโ model.py # Q-Network architecture (PyTorch)
โโโ replay_buffer.py # Experience replay buffer
โโโ agent.py # DQN agent (training + inference)
โโโ renderer.py # Pygame visualization (HUD, snake, food)
โโโ utils.py # Metrics tracking, plotting, random agent
โโโ train.py # Training loop with live visualization
โโโ evaluate.py # Demo mode, comparison, benchmarking
โโโ requirements.txt # Python dependencies
โโโ README.md # This file
โ
โโโ assets/ # (Optional) game assets
โโโ checkpoints/ # Saved model checkpoints
โโโ plots/ # Training result plots
โโโ report/
โโโ report.md # Detailed technical report
Training plots and game screenshots are automatically saved to the
plots/directory after training completes.
- Training Results:
plots/training_results.pngโ Scores, epsilon decay, loss, survival time - Agent Comparison:
plots/agent_comparison.pngโ DQN vs Random agent
- Double DQN: Reduce Q-value overestimation
- Dueling DQN: Separate state-value and advantage streams
- Prioritized Experience Replay: Sample important transitions more often
- CNN-based State: Use raw pixel input instead of hand-crafted features
- Curriculum Learning: Gradually increase grid size
- Multi-agent: Multiple snakes competing
- Noisy Networks: Parameter-space exploration instead of epsilon-greedy
- Human Play Mode: Allow human to play and compare with AI
This project is developed for educational and academic purposes.
Built with PyTorch, Pygame, and a passion for Reinforcement Learning ๐ฎ๐ค