Artificial Intelligence (CMP2020), University of Lincoln · March 2024 · Project page: AI Snake

The brief
Take a simple Snake game in NetLogo and make the snakes play themselves using the search algorithms from the module. Each snake has to plan a path to the food and follow it without hitting walls, the other snake or itself.
Five ways to find an apple
I implemented all five, and you can give each snake a different one and watch them race:
- Depth-first search: dives down one route as far as it can before backtracking. It finds a path, but often a ridiculous winding one
- Breadth-first search: expands outwards evenly in every direction, so it always finds the shortest path, but it checks a lot of squares to get there
- Uniform-cost search: orders its search by the cost of the path so far, always extending the cheapest route first
- Greedy best-first search: only looks at how close a square is to the nearest apple (using Manhattan distance, since snakes can’t move diagonally). It’s fast and heads straight for the food, but it can walk itself into trouble
- A*: combines both, the cost so far plus the distance to the nearest apple, so it finds short paths without exploring everything
Watching them side by side makes the differences obvious in a way a textbook doesn’t. Depth-first snakes wander, breadth-first ones are thorough, and A* just goes.
Making them better at the game
- Avoiding the other snake: a switch makes each snake re-plan its route whenever the next step would collide with the other player, since the other snake may have moved into its path since it planned. How well it works depends on the algorithm
- A debug view: a switch shows the squares each search visited and the path it chose, which was great for checking the algorithms were doing what I expected
- High-score mode: instead of stopping at a target length, the snake keeps going as long as it can survive
My extension: Snake in 3D
The part I’m proudest of is the extra: I rebuilt the whole project in 3D. The snakes now search a cube instead of a grid, with six neighbours per square (up and down as well as the four sides), and every algorithm still works.
NetLogo can’t switch between 2D and 3D in one project, so it had to become a second file running in NetLogo 3D. I checked with my lecturers first that submitting two versions was OK. I removed the human-controlled snake from the 3D version, because steering a snake through a 3D cube with a keyboard isn’t a fair ask of anyone.

The 3D version
The feedback called it a brilliant 3D version, and mentioned that it crashed the marker’s PC (not the code’s fault, luckily). Searching a 3D volume is a lot more work than a flat grid.
Since then
I’ve put the 2D version on this site so you can pick an algorithm for each snake and watch them race in your browser. The 3D version needs desktop NetLogo 3D, so it lives on its own branch of the repo.