All AI games
🐍
Pathfinding

Snake AI — Hamiltonian Cycle + A* Shortcuts

How a Hamiltonian-cycle planner with safe A* shortcuts plays a perfect game of Snake — heading straight for the apple while never trapping itself.

Play the game

How the AI works

This Snake is solved with planning, not learning. A Hamiltonian cycle — a closed loop that visits every cell of the grid exactly once — is computed up front. Following it blindly can never cause a collision, which guarantees the snake survives.

Going straight for the apple

Following the full loop every time would be safe but painfully slow. So the agent takes A / greedy shortcuts*: it heads directly toward the apple whenever a move is provably safe — i.e. it can still reach its own tail afterwards. If a shortcut would risk trapping itself, it falls back to the safe cycle.

Why it's perfect

Because every shortcut is verified against the cycle and the tail, the snake never dies. In simulation it clears the entire board (score 397) on every single run.

What you see on screen

The side panel shows the real Hamiltonian cycle, the live planned path to the apple (green = shortcut to food, orange = following the cycle), and live stats — board fill %, apple distance, and shortcut count.

Need a Data Scientist or AI Engineer?

I build custom ML models, RAG chatbots, data pipelines, and production APIs — from analysis to deployment.