This project trains a Deep Q-Network (DQN) to play the classic Snake game using Reinforcement Learning (RL). The agent learns by interacting with the environment and optimizing its movements to maximize the score, as defined in the reward function.
├── snake-reinforcement-learning
│ ├── models
│ │ ├── dqn_agent.py # Deep Q-Network agent implementation
│ ├── snake_game
│ │ ├── __init__.py
│ │ ├── snake_game.py # Game environment (Pygame-based)
│ ├── train.py # Training script for RL agent
│ ├── evaluate.py # Evaluate the trained model
│ ├── dqn_snake.pth # Saved trained model (generated after training)
│ ├── requirements.txt # Required dependencies
│ ├── .gitignore # Files to ignore in Git
│ ├── README.md # Project documentation (this file)
git clone https://github.com/SergioV3005/snake-reinforcement-learning.git
cd snake-reinforcement-learningpython -m venv venv
# Activate it:
# Windows:
venv\Scripts\activate
# Mac/Linux:
source venv/bin/activatepip install -r requirements.txtTrain the agent using Deep Q-Learning:
python train.pyThis script trains the agent for multiple episodes and saves the learned model as dqn_snake.pth.
After training, you can test the agent’s performance:
python evaluate.pyThis will run the trained model inside the Snake game environment and let the AI play.
- Algorithm: Deep Q-Learning (DQN)
- Frameworks: PyTorch, NumPy, Pygame
- State Representation: Distance to walls, food direction, collision risks
- Rewards System:
+10: Eating food-10: Hitting a wall or itself-0.1: Staying idle (encourages movement)
This project is open-source and available under the MIT License.
Feel free to contribute! Open an issue or submit a pull request if you have ideas for improvements.