Building an snake game where the agent learns from the enivornment
🎯 Overview
This project implements a Reinforcement Learning (RL) agent trained using Deep Q-Learning (DQN) to play the classic Snake game. The game environment is built with Pygame, and the training logic is implemented using PyTorch.
The agent learns optimal gameplay strategies by interacting with the environment — receiving rewards for good actions (like eating food) and penalties for bad ones (like hitting walls or itself).
✅ Custom Snake Game Environment built with Pygame
🤖 Deep Q-Network (DQN) agent implemented using PyTorch
🧩 Experience Replay and Epsilon-Greedy Exploration
📈 Dynamic training visualization (score, game count, loss, etc.)
💾 Model saving and loading for training continuity
Snake-DQN/
│ ├── game.py # Pygame environment for Snake
├── model.py # PyTorch neural network model (DQN)
├── agent.py # Reinforcement learning agent logic
├── helper.py # Helper functions (plotting, etc.) │ ├── models/ # Saved trained models
├── results/ # Training logs and performance plots
│ └── README.md # Project documentation
- Environment (Pygame)
The Snake moves in a grid.
The agent observes the game state (snake position, direction, food location, etc.).
It receives a reward after each action:
+10 for eating food
-10 for dying
Small negative reward for each step to encourage faster food collection
- Deep Q-Learning (DQN)
The neural network predicts Q-values for each possible action ([straight, left, right]).
The agent selects actions using an epsilon-greedy policy.
Experience Replay Buffer stores past experiences (state, action, reward, next_state, done) to break correlation in training.
Target network stabilizes training by periodically syncing weights.
pygame.reinforcement.learning.-.Made.with.Clipchamp.mp4
Install the required libraries:
pip install pygame torch numpy matplotlib
- Train the Agent
Run the training script:
python agent.py