Open-source project
chynl/snake avatar
chynl/snake

chynl/snake: Two AI Agents That Play Snake, and What Each One Costs You

Playing the game of snake with AI.

1,792 stars583 forksPythonMIT

At a glance

What is it?
chynl/snake ships a graph-search agent and a Double DQN reinforcement learning agent for a 6x6 Snake grid. The graph search wins 94% of 1000 rounds; the RL agent wins 50%. Here is how both work, how to run them, and where each one breaks.
Who is it for?
Adopt chynl/snake if you want a small, readable reference for comparing a rule-based planner against a learned policy on the same environment, or if you need a working Hamiltonian-path demo on a 6x6 grid. Skip it if your grid is larger than 6x6, if you need a packaged library rather than a script, or if you want an RL agent that wins reliably: the README reports 50% success for the RL agent versus 94% for graph search.
Can I use it commercially?
Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
Is it still maintained?
Yes. The repository last received commits 152 days ago.
What is it written in?
Mainly Python, according to GitHub's language statistics.

Answers come from the project's GitHub data, last synced on September 19, 2026, and from our analysis. They are not legal advice.

DEEP OPEN-SOURCE ANALYSIS

What chynl/snake actually solves, and who it is for

Most Snake AI projects pick one approach and stop. This one ships two agents behind a single entry point, which makes it useful as a side-by-side reference rather than a game. The README frames the goal plainly: the project implements two AI algorithms to play Snake, a graph search strategy and a reinforcement learning agent. The repository is a Python package with a top-level main.py, a training script rl_train.py, a pre-trained checkpoint rl_model.pt, and an src/ tree holding the agent implementations.

The audience is narrow and specific. If you are learning how a Hamiltonian-cycle solver behaves on a small grid, or you want to see a Double DQN agent trained from scratch on the same environment, the code is short enough to read in an afternoon. The README publishes the comparison table directly, with average length and success rate for both agents over 1000 rounds on a 6x6 grid. That table is the whole pitch: graph search averages 35.86 and succeeds 94% of the time, reinforcement learning averages 29.33 and succeeds 50% of the time.

What it is not: a library. There is no published package, no API surface documented beyond the CLI flags, and no configuration file. You clone it, install two dependencies, and run a script. That is fine for study and awkward for embedding.

How the graph search agent decides a move

The graph search agent models the grid as a graph where nodes are positions and edges connect adjacent positions. Its decision procedure is a four-step fallback chain, and the ordering matters more than any individual step.

First, if the snake is long enough, it searches for a Hamiltonian path from the head to the tail. A Hamiltonian cycle visits every position exactly once, so following one guarantees the snake can eat all the food and reach maximum length without trapping itself. Finding a Hamiltonian path is NP-complete in general; the README states that on a 6x6 grid, backtracking guided by Warnsdorf's heuristic finds one in reasonable time, and that the search only runs once the snake is long enough to raise the odds of a quick hit.

Second, it computes the shortest path from head to food, simulates eating along that path, and checks whether a safe path from the new head back to the tail still exists. If yes, it eats. If no, it falls through.

Third, it builds a longer path to the tail by inserting perpendicular side-steps: a single right move becomes down, right, up. The README explains why this exists. When the head sits adjacent to the tail, the shortest path walks straight into the tail cell, which the rules allow because the tail vacates on the same tick, and the snake can then loop along a fixed route forever. The zig-zag detour fills empty cells near the tail before arriving, which opens space later.

Fourth, when neither eating nor reaching the tail is safe, the agent moves toward the reachable neighbor farthest from the food. That is a stall tactic, and it is worth naming as one: the agent is buying time, not solving anything.

The reinforcement learning path: Double DQN on a 6x6 grid

The RL agent treats the snake as the agent, the grid as the environment, and the four moves as actions. It approximates the action-value function with a neural network, which is what makes it deep reinforcement learning. The README names Double DQN as the technique used for better convergence and stability, citing the original paper.

The state representation is the part worth understanding, because it constrains everything downstream. Two tensors are concatenated. The first is a 4-channel 6x6 tensor fed into convolutional layers, encoding the food position, the snake body, the snake head, and the danger cells where moving would end the game. The second is a 1D tensor carrying the current moving direction and the current direction of the tail. That second tensor is what lets the network reason about where the tail will be, which is the same problem the graph agent solves with its longer-path trick.

Rewards are sparse and shaped by hand: positive for eating food, negative for hitting the snake itself or the wall. The README does not publish the numeric reward values, the discount factor, the learning rate, or the replay buffer size, and rl_train.py is the only place those would live. If you plan to retrain, expect to read the script rather than the documentation.

There is no release history in the repository, so the checkpoint at rl_model.pt is the only published artifact. The README does not state the PyTorch version it was trained against.

Install chynl/snake and play your first game

The project requires Python 3.10 or newer. The README's first step is a virtual environment, which is worth following because pygame and pillow are the only two entries in requirements.txt and you do not want them in your system interpreter.

bash
python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt

requirements.txt pins pillow==12.2.0 and pygame==2.6.1. After that, running the default entry point starts the graph search agent. The README notes that appending -h lists all supported options.

bash
python3 main.py

You should see a pygame window rendering the 6x6 grid with the snake moving under the graph search policy. To watch the learned policy instead, install PyTorch separately for your CPU or GPU, then pass the model flag.

bash
python3 main.py -m rl

Training your own model is a separate script, and the README points at the included checkpoint as the starting artifact.

bash
python3 rl_train.py

The README does not document training duration, hardware requirements, or how to resume from a checkpoint, so budget time for reading rl_train.py before you launch a long run.

Where the graph search agent fails, and when RL is the wrong choice

The four-step fallback chain is a priority list, and step four is an admission of defeat. When the snake can neither eat safely nor reach its tail, the agent walks toward the cell farthest from the food. That is not a plan. It is a way to spend a turn without dying immediately, and on a 6x6 grid with a 36-cell maximum it will eventually run out of room. The published 94% success rate is honest about this: roughly one game in seventeen ends badly.

The Hamiltonian search has a scaling wall that the README states directly. The problem is NP-complete, and the project gets away with it because the grid is 6x6 and Warnsdorf's heuristic prunes the search. Change the grid to 10x10 or 20x20 and that argument evaporates. Nothing in the README suggests the approach generalizes, and the agent is only triggered once the snake is long enough, which is a heuristic tuned to this board size.

The RL agent is the weaker of the two by the project's own numbers: 29.33 average length and 50% success against 35.86 and 94%. If your goal is a Snake agent that finishes games, the learned policy is the wrong tool here, and the README's table says so before you install anything. The RL path is worth the setup only if you want to study the training loop, the state encoding, or Double DQN on a small environment.

One more constraint: the RL path needs PyTorch, which is not in requirements.txt. The README tells you to install it from the PyTorch site based on your CPU or GPU preference. There is no pinned version, so reproducibility across machines is on you.

The real alternative: a single-strategy solver instead of two agents

If you only want a Snake agent that reaches maximum length, the honest comparison is not another Python repository. It is writing the Hamiltonian-cycle solver yourself and skipping the rest. The core idea fits in a paragraph: build the cycle once for the grid, then follow it, and the snake can never trap itself. The graph search agent here is that idea plus three fallback strategies for the early game, when the snake is too short for the Hamiltonian search to be worth running.

A pure cycle-following solver gives up efficiency for a guarantee. The snake takes a long, winding route to every piece of food. This project's agent does better on average length precisely because it eats greedily when it is safe to do so, and only falls back to the cycle when it must. That is the actual design difference, and it is the reason the four-step chain exists.

If you want a learned policy instead, the alternative is a general RL framework such as Stable-Baselines3, which gives you PPO, DQN and the rest with vectorized environments and logging. The trade-off is the opposite of this project's: you get tooling and scale, but you lose the readable 6x6-specific state encoding and the side-by-side comparison against a planner. This repository is a teaching artifact, not an RL platform.

Maintenance, licence, and what an upgrade would cost you

The repository is not archived, and its last push was on 2026-04-19. There are no releases, so there is no version number to pin and no changelog to read. Upgrades happen by pulling from main, which means the only compatibility surface you can inspect is requirements.txt: pillow==12.2.0 and pygame==2.6.1, both pinned exactly. Those two pins are the most stable thing in the project.

The Python floor is 3.10, stated in the README. If you are on 3.9 or older, nothing runs. PyTorch is deliberately unpinned and installed out of band, so the RL path carries the upgrade risk: a future PyTorch release that changes checkpoint loading would affect rl_model.pt, and the README gives no version guidance to fall back on. That is the one place where an upgrade could silently break the demo.

The licence is MIT, which is permissive and short. You can use, modify and redistribute the code, including commercially, provided the copyright notice and licence text travel with it. There is no warranty. The MIT grant covers the code in the repository; it says nothing about the pre-trained weights in rl_model.pt, and the README does not address that file separately. If you plan to redistribute the checkpoint rather than your own trained model, that is the question to resolve before you ship.

Editorial conclusion

Adopt chynl/snake if you want a small, readable reference for comparing a rule-based planner against a learned policy on the same environment, or if you need a working Hamiltonian-path demo on a 6x6 grid. Skip it if your grid is larger than 6x6, if you need a packaged library rather than a script, or if you want an RL agent that wins reliably: the README reports 50% success for the RL agent versus 94% for graph search. Verify three things before you build on it: that Python 3.10 or newer is available, that pygame and pillow install cleanly from requirements.txt, and that the checkpoint at rl_model.pt loads under your PyTorch build, since the README does not state which PyTorch version produced it.

Frequently asked questions

What is chynl/snake and what does it do?

It is a Python project that implements two AI algorithms to play the game of Snake: a graph search strategy and a reinforcement learning agent. The README reports average length and success rate for both over 1000 rounds on a 6x6 grid.

How do I install chynl/snake and run it?

The README requires Python 3.10 or newer, then a virtual environment, then pip3 install -r requirements.txt, which pulls pillow==12.2.0 and pygame==2.6.1. Running python3 main.py plays the game with graph search; adding -m rl uses the reinforcement learning model after you install PyTorch separately.

Which agent in chynl/snake performs better, graph search or reinforcement learning?

The README's comparison table gives graph search an average length of 35.86 and a 94% success rate, against 29.33 and 50% for reinforcement learning. Success means the snake consumes all the food and reaches the 36-cell maximum without hitting itself or the wall.

Does chynl/snake need PyTorch to run?

Only for the reinforcement learning path. The mandatory dependencies in requirements.txt are pillow and pygame; the README lists PyTorch as optional and points to the PyTorch install page for a CPU or GPU build.

Official sources

  1. chynl/snake on GitHub
  2. Issues
  3. License: MIT
  4. README
Community notes

Community notes