---
title: "AI snake"
year: "2019"
motto: "AI Snake Game"
description: "Snakes that learn to survive using genetic algorithms. It's an extension of the developed JavaScript snake game."
stack: ["javascript"]
website: "https://lab.rolandoandrade.me/ia-snake/"
url: "https://rolandoandrade.me/projects/ai-snake/"
author: "Rolando Andrade"
---

# AI snake

> AI Snake Game

Snakes that learn to survive using genetic algorithms. It's an extension of the developed JavaScript snake game.

Year: 2019. Stack: javascript. Website: https://lab.rolandoandrade.me/ia-snake/

Repositories:

- [github](https://github.com/RolandoAndrade/ia-snake)
- [gitlab](https://gitlab.com/RolandoAndrade/ia-snake)

Open the page and 80 snakes start playing at once. Within seconds, most of them crash into a wall or into their own bodies. Nobody told them how to play. Each one moves with a random brain.

Playing snake is easy for people. We look ahead, spot the food, and avoid the walls and our own tail. Teaching a computer to do that without writing the rules is a different problem.

I wanted to see if snakes could learn to survive on their own. I wrote no pathfinding code and no fixed strategies. The snakes had only evolution. The best ones survive and pass on their traits. The rest die.

This project was my experiment with genetic algorithms and neural networks. I built it in plain JavaScript, and it runs in the browser.

## Random brains, then better ones

Each of the 80 snakes has its own brain. The brain is a small neural network that decides whether to turn left, go straight or turn right. A neural network is a set of connected math functions. Its behavior depends on numbers called weights.

At first, the snakes move at random. Some survive longer than others. Maybe they got lucky. Maybe their random weights happened to help them avoid obstacles.

When every snake has died, the next generation starts. The survivors pass their weights to their children. Some weights get mixed between two parents. Some get changed at random. Over many generations, the snakes get better at staying alive.

## What a snake can see

Each network has four layers. The input layer takes 22 values that describe the snake's situation. The output layer gives three values: turn left, go straight or turn right.

The 22 inputs tell the snake everything it knows:

- Eight directions showing where the food is (up, down, left, right, and four diagonals)
- Eight directions showing if obstacles are in the way
- Two values indicating if the snake is moving toward the food
- Four distances to each wall

Between input and output there are two hidden layers, with 18 and 10 neurons. The hidden layers use the sigmoid activation. The output layer uses ReLU. An activation is the function each neuron applies to its result. The snake picks the output with the highest value.

## Survival of the fittest snake

When a generation ends, the algorithm sorts the 80 snakes by fitness score. Fitness is a number that says how well a snake did.

A few things change the score. Moving toward food adds points. Moving away takes points off. Eating food gives a big bonus. Hitting a wall or yourself gives a penalty. A timer also kills snakes that wander too long without eating.

The top 15% of snakes survive to the next generation and become parents. The algorithm makes children by combining the weights of two parents. This step is called crossover. Each weight has a 50% chance of coming from either parent.

After crossover, there is a 30% chance of mutation. Mutation adds small random changes to all the weights in the network. This adds variety. It helps the population escape local optima, which are strategies that look best only because nothing nearby is better.

![Each generation plays, gets scored, keeps the top 15%, and breeds the next 80 snakes](https://storage.rolandoandrade.me/blog/ai-snake-generation-loop.webp)

## No libraries, just canvas

The whole project runs in the browser on an HTML canvas. It uses no libraries and no frameworks.

The code is split into several modules:

- **Shapes** draws rectangles and circles on the canvas.
- **Brain** is the neural network, with its layers, weights and forward propagation.
- **Snake** handles movement and collision detection.
- **Generations** does selection, crossover and mutation.
- **Game** runs the main loop and manages the boards.

Each snake lives on its own 80x80 pixel board. The main view shows 10 columns and 8 rows of these small boards. That is how you can watch 80 snakes evolve at once.

## A brain from scratch

I built the neural network from scratch, without TensorFlow or any other library. It is only matrix multiplication and activation functions.

A layer stores its weights in a 2D array and its biases in a 1D array. Forward propagation is how the network turns inputs into outputs. It multiplies the input by the weights, adds the biases and applies the activation function.

The sigmoid function squeezes any value into the range between 0 and 1. That gives the hidden layers smooth changes. The ReLU function returns the input if it is positive and zero if not. That is enough for the output layer, which only needs to pick the highest value.

## Watching them learn

In the first generation, the snakes move at random and crash almost at once. By generation 10, some snakes avoid walls every time.

By generation 50, new behaviors appear. Snakes circle near the edges. They follow food more reliably. Some learn to move in loops until food appears nearby.

The learning is not perfect. Sometimes a good strategy spreads through the population and then disappears through mutation. Sometimes the snakes get stuck in a local optimum. They find an average strategy and never discover a better one.

## Rewarding the right thing

The fitness function took several tries. My first version only rewarded eating food. Snakes wandered at random until they found food by accident. No learning happened.

Rewarding movement toward food changed everything. Snakes that got closer scored higher, even if they died before eating. That gave the genetic algorithm a clear direction to follow.

The mutation rate needed tuning too. When it was too low, the population settled on average solutions. When it was too high, good strategies were destroyed before they could spread.

## Evolution has no foresight

Genetic algorithms are simple to build and hard to tune. A small change in the fitness function or the mutation rate leads to very different results.

Neural networks do not need to be deep to solve simple problems. A network with 22 inputs, two hidden layers and 3 outputs was enough to play basic snake.

Running 80 simulations side by side made evolution visible. You could watch better strategies appear and spread through the population.

The snakes never learned to plan ahead. They only react to what they see right now. Sometimes that is enough. Sometimes they trap themselves in a corner.

[Book a call with Rolando](https://rolandoandrade.me/pricing/)
