Training an AI to Play Snake Using a Genetic Algorithm

GeneticAlgorithm AI MachineLearning Python GameDev

🎮 Introduction

With the rapid progress of AI, mainstream attention has shifted to large language models and neural networks — leaving some older but still powerful methods in the shadows. One such method is the Genetic Algorithm (GA) — a fascinating AI technique inspired by biological evolution and survival of the fittest.

To rediscover its potential, I applied a genetic algorithm to a niche but well-defined task: training an AI to play the classic Snake game. This project aimed to optimize snake performance, increase survival time, and visualize the learning process of a GA in a self-contained environment.


🧠 Why Genetic Algorithms?

Unlike traditional models that generalize across tasks, genetic algorithms are tailored for specific environments. They work by evolving a population of candidate solutions (or “snakes”) over generations, gradually improving their performance through selection, crossover, and mutation.

Snake is the perfect game for this: it has a finite action space (Up, Down, Left, Right), a clear objective (eat food and survive), and a well-defined environment. It’s also easy to visualize, making it an ideal playground for evolutionary AI.


🕹 Game Overview

The Snake Gen project, developed in Python 3.11.7 using Pygame, supports three main modes:

  • 🧑‍💻 Manual Mode: Play Snake yourself with arrow keys.
Manual play GIF
  • 🤖 AI Training Mode: Train an AI snake using genetic evolution.
Train AI GIF
  • 🧠 Pre-Trained AI Mode: Watch distinct AI personalities in action (Hunter, Explorer, Strategist, Risk Taker, and AI Mastery).
Pre-trained GIF

The interface includes real-time metrics, colorful graphics, and interactive menus.


🔬 Inside the AI Brain

The snake’s AI is powered by a set of 9 weighted parameters representing its “genome”:

  • 1- Food Bonus
  • 2- Toward Food Reward
  • 3- Away From Food Penalty
  • 4- Loop Penalty
  • 5- Survival Bonus
  • 6- Wall Penalty
  • 7- Exploration Bonus
  • 8- Momentum Bonus
  • 9- Dead-End Penalty

Each AI candidate starts with random weights, normalized for stability:

self.brain = np.random.uniform(-1.5, 1.5, 9)
self.brain /= np.linalg.norm(self.brain)

These weights are used in a fitness function to guide decision-making during gameplay.


🧬 The Genetic Algorithm in Action

🔁 Evolution Steps:

  • Tournament Selection: Randomly selects a group of snakes and picks the one with the highest fitness.
  • Crossover: Combines two parents’ weights at a random cut point.
  • Mutation: Applies slight random changes to weights to maintain diversity.

Fitness is evaluated with this formula:

Fitness = (Score × Length × 5) + (Survival Time × 10) - (Moves Made / (Score + 1))

📈 Training Results

The game was trained for 100 generations with 50 candidates per generation. The evolution was clearly visible:

Generation Avg. Length Best Length
1 6 12
10 34 72
50 44 106
100 63 143

With each generation, the snakes got better at avoiding walls, finding food, and surviving longer.


🧪 Technical Challenges & Limitations

While effective in defined environments, genetic algorithms are not general-purpose solvers. Their success depends heavily on:

  • Carefully chosen state space parameters
  • Well-tuned fitness functions
  • A simple, structured environment

Transferring trained models to new games or settings is impractical without redesigning the entire setup. However, this specialization is also a strength: it allows for deep optimization in tasks like Snake.


🤖 Ethical Considerations

AI in games often sparks controversy — are bots ruining the experience or creating new forms of expression?

  • 🎮 Bad Use: Cheating in online games with unfair advantages.
  • 🎮 Good Use: Tool-assisted speedruns (TAS) that push games to their limits.

Like high-frequency trading in finance, intelligent systems need ethics and boundaries. In this project, the goal was exploration and learning — not competition.


Try It Yourself

Clone the repo and start evolving your own snakes:

git clone https://github.com/burakkagann/Snake_Gen
cd Snake_Gen
pip install -r requirements.txt
python Snake-Gen-v11.5.py

References

  • 1- Alam, Tanweer, et al. “Genetic Algorithm: Reviews, Implementations, and Applications.” International Journal of Engineering Pedagogy, 2020. arXiv, https://doi.org/10.48550/arXiv.2007.12673
  • 2- Bialas, Piotr. pp. 42–46, Implementation of Artificial Intelligence in Snake Game Using Genetic Algorithm and Neural Networks.