AI & research

Autonomous Snake Game Agent

Applied Deep Q-Learning with Python and Pygame to train an agent that improves through reinforcement learning, achieving high scores autonomously.

Reinforcement Learning & Pathfinding

This project reimagines the classic Snake Game by teaching an agent to autonomously navigate, collect food, and avoid collisions using a suite of Reinforcement Learning algorithms and Graph Theory fallbacks.

Training Algorithms

  • Deep Q-Networks (DQN): Implemented to generalize across the massive state space, significantly boosting convergence over baseline Q-Learning.
  • Double DQN: Addressed Q-value overestimation, becoming the most stable and performant driving model.

Fallback Strategies

To prevent the agent from trapping itself in late-game scenarios, I integrated hard-coded safety mechanisms:

  • Hamiltonian Cycle: Generated using Prim's algorithm to guarantee survival indefinitely.
  • BFS (Breadth-First Search): Used as a deterministic mid-game trajectory shortcut.

Training Results

Model / strategyHighest scoreHighest mean scoreNotes
Baseline DQN59N/AFirst DQN training run
DQN + reward shaping671900Improved with reward shaping
Best current DQN521500Most consistent DQN so far
CNN 5×5321000Grid input, 5×5 filters
CNN 7×716600Grid input, 7×7 filters
Hamiltonian cycle∞N/ASurvives indefinitely once the path is set
BFS150N/AReliable but not optimal
Double DQN, 400×400 grid541700The only fully working learned model

Tabular Q-learning ran for 16+ hours and struggled to generalise, often looping near the food to exploit the reward shaping. The small 400×400 grid (20×20 cells) is where Double DQN with the safety fallbacks works best; larger boards are the open problem.

What's Next

Tune the Double DQN hyperparameters further, try Rainbow DQN, feed the grid to a convolutional network, and refine reward shaping to stop the looping behaviour.

Figures

A random Hamiltonian cycle generated with Prim's algorithm: following it, the snake can never trap itself.
A random Hamiltonian cycle generated with Prim's algorithm: following it, the snake can never trap itself.

Stack

  • Deep Q-Learning
  • Pygame
  • RL
  • Python