Visualizations
311 / 500

311 · Algorithms

Perfect Snake

A snake AI that can never crash, cutting safe shortcuts until it fills every cell.

Each game starts by building a random Hamiltonian cycle, a closed tour through every cell: a randomized Prim's spanning tree is grown on a half-resolution grid and the tour walks around its outline, two by two. Following that tour alone could never crash, but it is slow, so the autopilot numbers the cells in tour order and jumps to any free neighbor that lies ahead of its head yet still behind its tail, with a margin for growth, so the body always occupies one contiguous stretch of the cycle and the tour is always there to fall back on. Shortcuts flash as they are taken, the dotted line is a replay of the same policy showing where it is heading, and once the board is half full it stops cutting corners and winds on, faster and faster, until the rainbow body fills all of it.

Try it. Take the wheel with the arrow keys, WASD or a swipe; after a few idle seconds the autopilot resumes (and repairs its position if you scrambled it). Tap or press F to fast-forward, C to hide the cycle, and R for a new cycle.

  • Hamiltonian cycles from spanning trees
  • Cycle-order shortcut invariant
  • Randomized Prim's algorithm
  • Policy lookahead

View the source · one module, plus a small shared runtime for sizing, the animation loop and input

Build your own

Paste this into Claude Code, Codex or any coding agent to get a simple version running, then take it wherever you like.

Build a snake game that plays itself and never dies, with JavaScript and the HTML canvas element. Put everything in a single index.html file with no libraries or build step, so I can open it directly in a browser.

Start simple:
- Make a canvas that fills the window and stays sharp on high-DPI screens (scale by devicePixelRatio). Use a 20 by 12 grid of cells (both sides even).
- Build a Hamiltonian cycle, a closed tour through every cell: make a random spanning tree on a 10 by 6 half-size grid, then walk around its outline. Each 2 by 2 block of cells normally loops counterclockwise, and where the tree has an edge, the tour crosses into the neighboring block instead. Store next[cell] and each cell's position along the tour.
- Have the snake simply follow next[cell] forever, eating food that appears on random empty cells. It can never crash, but it is slow.
- Draw the tour as a faint line through the cell centers, and the snake as a thick rounded line on top.

Once that works, make it smart and beautiful:
- Add shortcuts: let the snake move to any free neighbor whose tour position is ahead of its head but still behind its tail (leave a few cells of margin), never past the food, and stop taking shortcuts once the board is half full. The body then always lies in one stretch of the tour, so it stays safe.
- Color the body as a rainbow from head to tail and speed up as the board fills, so the ending is a satisfying full board.
- Let the arrow keys take over and hand control back after a few idle seconds.

Explain the key ideas in short code comments. When you're done, tell me how to open it and suggest three directions I could take it next, such as flashing each shortcut as it happens, drawing the route the AI plans to take, or celebrating the perfect final frame.
PreviousDouble PendulumPendulums that start almost identical and end up worlds apart. NextPseudo 3D RoadA sunset coastal highway faked the 80s arcade way, from flat segments and sprites.

Related visualizations

  • Topological SnakeGames Snake on a torus, a Klein bottle and a projective plane, with the real surface turning beside it.
  • Deep Q SnakeMachine learning A deep Q-network learns snake from scratch, live, on a retro dot-matrix LCD.
  • Maze SolverAlgorithms A maze carves itself, then A* hunts for the way out.
  • Route PlannerAlgorithms Dijkstra, A*, bidirectional search and contraction hierarchies race on a printed atlas.
  • Minesweeper OracleAlgorithms Every hidden cell shows its exact mine probability while an AI plays the safest move.
  • PCB AnnealerAlgorithms Simulated annealing places chips on a circuit board, then a maze router lays copper.
  • Rebound RobotsAlgorithms Robots slide until they hit something. A* finds the fewest moves to the target.
  • MCTS BloomAlgorithms Four-in-a-row against Monte Carlo Tree Search, its search tree blooming as a flower.
  • Dancing LinksAlgorithms Knuth's Algorithm X tiles boards with wooden pentominoes while its links visibly dance.

Use ← and → to move between demos. While the canvas has focus, keys go to the demo instead.

← More from Emergent Mind Labs