Machine LearningArticle11 min read

Teaching a snake to play, with no rules and a table of numbers

Learn2Slither: a snake that learns Snake by trial and error with Q-learning. How it sees, how it learns, explained with my own code, plus a snake you can train from scratch right here.

By Abdeljalil El HidaouiSource code
On this page

Nobody tells this snake the rules. It doesn't know that apples are food, that walls are deadly, or even which way is up. It just tries moves, gets rewarded or punished, and slowly writes down what worked. After a few thousand games it plays well enough to reach length 10 in nine games out of ten.

This is Learn2Slither, a 42 project about reinforcement learning, and more precisely Q-learning. There is no neural network here: the whole “brain” is a table of numbers. This article explains how that table is built, with code from my repository, and it has two live parts: the trained snake with its brain open, and a snake you can train yourself from nothing.

The idea

In most of machine learning, a model learns from examples that already have the right answer. Reinforcement learning is different: there are no answers, only consequences. An agent acts in an environment, receives a reward, and has to work out by itself which actions lead to good rewards over time. It is how you would teach a dog a trick, or how you learned to ride a bike.

board
10×10
lines of sight
4
numbers per state
12
of games reach length 10
91%

The subject adds a twist that makes it interesting: the snake does not see the board. It only sees what lies in the four straight lines from its head, like a periscope pointing up, left, down and right.

The game

The board is 10 by 10 cells, with 2 green apples and 1 red apple. A green apple makes the snake one cell longer, a red one makes it one cell shorter, and each eaten apple reappears somewhere free. The snake starts with length 3, and the game is over if it hits a wall, bites its own body, or shrinks to length 0.

All of that lives in environment.py. The heart of it is step(): move the head, check what is there, grow or shrink, and check for collisions. Note the order: the tail moves away before the collision test, so the snake may follow its own tail without dying.

environment.pyView on GitHub
row, col = self.snake[0]
d_row, d_col = action.value
new_head = (row + d_row, col + d_col)

if not self.in_bounds(new_head):
    return self.finish(Event.HIT_WALL)

event = Event.NOTHING
delta = 0
if new_head in self.green_apples:
    event, delta = Event.GREEN_APPLE, 1
elif new_head in self.red_apples:
    event, delta = Event.RED_APPLE, -1

new_len = len(self.snake) + delta
if new_len == 0:
    return self.finish(Event.ZERO_LENGTH)

body = [new_head]
for cell in self.snake:
    body.append(cell)
while len(body) > new_len:
    body.pop()

if body.count(new_head) > 1:
    return self.finish(Event.HIT_SELF)
self.snake = body

The learning loop

The subject asks for three separate modules, and they form the classic reinforcement-learning loop. The environment runs the board. The interpreter turns the board into what the snake can see (the state) and turns what just happened into a reward. The agent picks a move and learns from the result.

The environment, interpreter and agent passing the board, the state, the reward and the action around
One move: the environment produces a board, the interpreter turns it into a state and a reward, and the agent picks the next action.Open full size

In code, one game is this loop, in main.py:

main.pyView on GitHub
def run_session(env, interp, agent, viewer, args):
    verbose = args.visual == "on"
    env.reset()
    state = interp.state(env)
    while not env.done and env.steps < args.maxsteps:
        if viewer is not None:
            viewer.draw()
        if verbose:
            print(interp.render(env))
        if not wait_for_step(viewer, args):
            return False
        action = agent.choose(state)
        if verbose:
            print(f"{action.name}\n")
        result = env.step(action)
        reward = interp.reward(result.event)
        next_state = interp.state(env)
        agent.learn(state, action, reward, next_state, result.done)
        state = next_state
    if viewer is not None:
        viewer.draw()
    return True

The rewards are the only way to tell the snake what we want. Eating a green apple is good, a red one is bad, dying is very bad. The small penalty for an empty move matters more than it looks: without it, wandering around safely forever would cost nothing, and the snake would never bother hunting for food.

interpreter.pyView on GitHub
DEFAULT_REWARDS = {
    Event.GREEN_APPLE: 10.0,
    Event.RED_APPLE: -10.0,
    Event.NOTHING: -0.1,
    Event.HIT_WALL: -50.0,
    Event.HIT_SELF: -50.0,
    Event.ZERO_LENGTH: -50.0,
}

What the snake sees

From its head, the snake looks along the four directions until it reaches a wall, and notes what is in each cell: W wall, S its own body, G green apple, R red apple, 0 empty. The program prints this as a cross in the terminal before every move.

interpreter.pyView on GitHub
def vision(self, env):
    body = set(env.snake[1:])
    rays = {}
    for action in Action:
        row, col = env.snake[0]
        ray = []
        while True:
            row += action.value[0]
            col += action.value[1]
            if not (0 <= row < env.size and 0 <= col < env.size):
                ray.append(WALL)
                break
            cell = (row, col)
            if cell in body:
                ray.append(BODY)
            elif cell in env.green_apples:
                ray.append(GREEN)
            elif cell in env.red_apples:
                ray.append(RED)
            else:
                ray.append(EMPTY)
        rays[action] = ray
    return rays

A whole line of cells is too detailed to learn from, so each direction is squeezed into just three numbers: how close the first danger (wall or body) is, in three buckets (next cell, two cells away, three or more), whether a green apple is in sight, and whether a red one is.

interpreter.pyView on GitHub
def state(self, env):
    rays = self.vision(env)
    return tuple(self.encode(rays[action]) for action in Action)

@staticmethod
def encode(ray):
    distance = next(i + 1 for i, c in enumerate(ray) if c in (WALL, BODY))
    # danger (wall or body) distance: bucket 0 = 1 step,
    # bucket 1 = 2 steps, bucket 2 = 3+ steps
    bucket = min(distance, 3) - 1
    return (bucket, int(GREEN in ray), int(RED in ray))

Four directions × three numbers = a state of 12 numbers. Each direction can take 3 × 2 × 2 = 12 values, so there are at most 124 = 20,736 possible states. That is small enough to list every one of them in a table, which is exactly what Q-learning will do.

A board, the four lines of sight from the head, and the 12-number state they become
A real example, from the board to the state to the move the trained table picks.Open full size

The Q-table

The agent's memory is the Q-table: for every state it has met, four numbers, one per move. Each number, Q(s, a), is the agent's current guess of how much reward it will collect from now on if it plays move a in state s. At the start every value is 0: the snake knows nothing.

After every move, it updates the one value it just used, with the Q-learning rule:

Q(s, a) ← Q(s, a) + α · [ r + γ · maxa′ Q(s′, a′) − Q(s, a) ]

α = 0.1 (learning rate), γ = 0.9 (how much the future counts)

In words: the reward just received, plus the best value the snake expects from where it landed, is a slightly better guess than the old one. So the value moves 10% of the way towards it. Repeated over thousands of moves, good outcomes ripple backwards: a state next to an apple becomes valuable, then the state just before it, and so on.

A worked example with made-up numbers: say Q(s, RIGHT) is 2, the snake moves right and eats a green apple (r = 10), and the best value in the new state is 5. The target is 10 + 0.9 × 5 = 14.5, and the new value is 2 + 0.1 × (14.5 − 2) = 3.25. If instead the move had killed it, the target would just be −50, since nothing comes after a game over.

agent.pyView on GitHub
def learn(self, state, action, reward, next_state, done):
    """Q(s,a) += alpha * (r + gamma * max Q(s',.) - Q(s,a))."""
    if not self.learning:
        return
    values = self.q.setdefault(state, [0.0] * len(ACTIONS))
    future = 0.0
    if not done:
        future = max(self.q.get(next_state, ZEROS))
    i = INDEX[action]
    target = reward + self.gamma * future
    values[i] += self.alpha * (target - values[i])

Explore, then exploit

There is a catch. If the snake always picks the move with the best value, it keeps repeating the first thing that worked and never finds out whether something else is better. So it sometimes moves at random on purpose. That is the ε-greedy strategy: with probability ε, explore; otherwise, exploit the best known move (picking at random between ties).

agent.pyView on GitHub
def choose(self, state):
    if self.learning and self.rng.random() < self.epsilon:
        return self.rng.choice(ACTIONS)
    values = self.q.get(state, ZEROS)
    best = max(values)
    actions = []
    for i, value in enumerate(values):
        if value == best:
            actions.append(i)
    return ACTIONS[self.rng.choice(actions)]

ε starts at 1, so the first games are 100% random, and it is multiplied by 0.99 after every game, down to a floor of 0.01. It reaches that floor after about 460 games: from then on the snake mostly relies on what it has learned, with one random move in a hundred to keep discovering.

agent.pyView on GitHub
def end_session(self):
    self.sessions += 1
    if self.learning:
        self.epsilon = max(self.epsilon_min,
                           self.epsilon * self.epsilon_decay)

Inside its head

Here is the trained snake, running the real Q-table from models/10000sess.txt (2,681 states learned). Step through a game one move at a time and watch what it sees, the 12 numbers it turns that into, and the value it gives each move. It simply takes the move with the highest value.

The trained snake, step by step

The highlighted cells are its lines of sight. Positive values are moves it expects to pay off; very negative ones are moves it learned can kill it.

Loading the Q-table…

What it sees (like the terminal output)

Move · dangerGreen / redLearned value Q(s, a)
Up–· / ·
–
Left–· / ·
–
Down–· / ·
–
Right–· / ·
–

The tendencies it discovered on its own show up clearly when you read the whole table. A move into a wall or its body one cell away has an average value of −7.6, against +0.7 for every other move, and it is the top choice in fewer than 8% of situations. A safe direction with a green apple in sight averages +2.3, against −0.2 without one; when exactly one safe direction shows a green apple, it is the top choice 63% of the time. It is far from perfect, but none of it is written in the code: it all comes from the rewards.

Train your own snake

Now start from an empty table. This is the same Q-learning, ported from Python to TypeScript: same rewards, same α, γ and ε schedule. Every 250 training games, the snake plays 60 test games with exploration turned off, and the chart shows their average length. The small board plays continuously with whatever the table knows at that moment.

Q-learning from scratch, in your browser

5,000 games take a few seconds. Watch the small board: the snake goes from bumping into walls to hunting apples.

Games played
0 / 5,000
Exploration ε
100%
States known
0
Test average length
–
average length in test gamesmy best model (19.0)
051015202501,0002,0003,0004,0005,000training gamesPress Start training

Your snake, playing with what it knows now

The curve is noisy, and that is normal: a single new lesson can change several values at once, and 60 test games is a small sample. My best model went much further, to 20,000 games, which is why the dashed line sits above where a 5,000-game run usually ends.

Results

Each saved model was trained by continuing from the previous one, then measured on 300 games on a 10×10 board without learning or exploring:

ModelAvg lengthReached 10+Best length
1sess.txt3.00%4
10sess.txt3.00%5
100sess.txt3.10%5
1000sess.txt8.335%26
3000sess.txt14.876%29
10000sess.txt19.091%42
The best model's file records 20,000 sessions played in total.
States known and exploration rate across the saved models
Read from the saved models: the table grows from 3 known situations after one game to 2,681, while ε falls from 100% random moves to 1%.Open full size

And because the state does not depend on the board, the same model plays on any size:

Board5×58×810×1015×1520×20
Avg length10.216.219.026.632.5

Limits and lessons

  • The state is the real design decision. The learning rule is a single line. What the snake can see, and how it is compressed into 12 numbers, decides what it can ever learn.
  • Rewards shape behaviour. The −0.1 per empty move is what pushes the snake to look for food instead of circling safely.
  • It cannot plan. The snake only sees four straight lines, not the shape of its own body, so a long snake can still curl into a dead end it has no way to notice. This is also why games are capped at 2,000 moves: a snake that finds a safe loop could circle forever.
  • Separate learning from measuring. The -dontlearn switch turns off both updates and exploration, so a model can be evaluated without changing it. The test games in the lab work the same way.
  • Where to go next. A table works because there are only 20,736 states. For richer inputs, such as the whole board, the table is replaced by a neural network that estimates the values: that is deep Q-learning, and it builds directly on the neural network I wrote from scratch.

The full code, including the pygame interface and the lobby, is on GitHub.

About the project: Learn2Slither

A reinforcement learning agent that learns to play Snake by trial and error. It sees only the 4 lines from its head, and a Q-table learns which move pays off: after training, the best model reaches length 10 in 91% of games, with an average length of 19.

  • 91% reach length 10
  • Best length 42
  • Any board size

Built with

  • Python
  • Q-learning
  • pygame
  • flake8