← MAIN
09 // LEARNED AGENTS

SNAKE

Watch two learned agents steer a snake, or take the wheel yourself.
STATUS LOADING APPLES 0 STEPS 0 LENGTH 3

HOW TO PLAY

Steer the snake to eat apples, and it grows by one segment with each. The game ends when the snake hits a wall or its own body, or when it goes 288 steps without an apple.

Steer with W A S D or the arrow keys, with the steering pad on a phone, or by swiping on the board. The snake cannot reverse, so the opposite key is ignored.

Press WATCH THE AGENT to see the selected learned agent play, and ONE STEP to advance it one move at a time. PLANNER HINT draws the route the planner would take.

Watch the learned agent, or take the wheel with W A S D or the arrow keys.
AGENT
STEER
More settings
120 ms per step
WHAT THE AGENT IS THINKING
Waiting for a move.
Game log
HOW IT LEARNED
Apples per game, by generation.
best of generation population mean
THE CHAMPION
Loading the committed weights.

HOW IT WORKS

A snake on a 12 × 12 board steers by choosing one of three actions each step. Its goal is to eat apples, and each apple adds a segment to its body. The game ends if it runs into a wall or its own body, or if it goes too long without food.

Two learned agents steer the snake, and both are shown here. The default is an evaluation function: it scores each safe move by a weighted sum of eight numbers computed from the position the move leads to, and its eight weights were tuned by the cross-entropy method. The other is a neural net, a function built from weighted sums, with 339 weights bred by a genetic algorithm. Two classic baselines, greedy and a breadth-first search planner, are measured on the same boards for comparison.

The game and its rules

The board is a 12 × 12 grid of cells, each addressed by coordinates (x, y), where x is the column and y the row, growing downward. The snake is a list of segments. The first is its head and the last its tail. It starts in the middle of the board with three segments at (6, 6), (5, 6) and (4, 6), heading east. A heading is one of north, east, south or west, numbered 0 to 3 in clockwise order.

Each step the snake takes one action: left, straight or right, measured from its heading. The actions are relative, so the policy never needs compass directions. A left or right action turns the heading by a quarter turn, and straight leaves it alone. The snake cannot reverse, so these three actions are the only choices1.

h' = (h + \delta_a) \bmod 4, \qquad \delta_{\text{left}} = -1,\quad \delta_{\text{straight}} = 0,\quad \delta_{\text{right}} = +1
123

Here h is the heading before the step and h' the heading after it, and \delta_a is the quarter turn of action a. Adding 1 turns clockwise, and the modulo keeps the result in 0 to 33. Example. In a new game the head is at (6, 6) heading east. Straight enters (7, 6), and left turns the head north and enters (6, 5).

The head then moves into the cell ahead. The move ends the game if that cell is outside the board (a wall death) or holds a body cell (a body death). The tail is treated with care. If the snake does not eat, the tail leaves its cell in the same step, so the tail's cell can be entered. If the snake eats, the tail stays in place and blocks its cell45.

Eating adds one apple to the score and one segment to the body, and the food moves to a uniformly random empty cell. Each empty cell is equally likely, so with |E| empty cells each has probability 1/|E|6. An idle counter counts the steps since the last apple. The game ends as starved when the counter reaches the cap of two laps of the board, 2N^2 = 288 steps. Filling the whole board ends the game as full, the only win78.

\text{starved} \iff \text{idle} \ge 2N^2 = 2 \cdot 12^2 = 288
78

Here N = 12 is the side of the board. The cap stops a looping snake from playing forever, and it is the same for every agent in the benchmark below.

The score of one game

Both learned agents are trained on one number per game, the game score, which is also called fitness when it is used to rank candidates. A game that does not end by starvation scores its apples, plus a small survival bonus of at most 0.25 for lasting up to 300 steps. Beyond 300 steps each extra step costs 0.0002, so drifting for thousands of moves earns no bonus and pays a small cost. A starved game is penalised instead: it keeps its apples, loses 0.5, and gets no survival bonus, so looping is worse than dying cleanly910.

s(g) = \begin{cases} \text{apples} - 0.5 & \text{if starved} \\ \text{apples} + 0.25\,\dfrac{\min(\text{steps},\,300)}{300} - 0.0002\,\max(0,\ \text{steps} - 300) & \text{otherwise} \end{cases}
10

Here s(g) is the score of game g. The constants are the survival cap of 300 steps, the survival bonus of 0.25, the step cost of 0.0002 and the starvation penalty of 0.5, all set in the code11. A candidate's fitness is the mean of this score over the boards it played.

The default agent: an evaluation function

The default agent is an evaluation function, a rule that gives each position a number. For each move that does not end the game, it imagines the resulting position, computes eight features (numbers between 0 and 1 read from that position), and takes the move whose weighted sum of features is largest. A weight is the number that multiplies one feature. The features and the rules are hand-built, and the eight weights are the only part that was learned12.

A move is first applied in imagination. Let h' be the new head, and B' the new body: the new head followed by the old body, with the old tail removed unless the snake ate. The last cell of B' is the new tail t'. Every feature comes from one breadth-first search (BFS) that starts at h'. A BFS visits cells in order of their distance in steps, so the first time it reaches a cell it has the shortest route there. This search runs over empty cells and gives three values at once: the distance d_f in steps from the head to the food, the number R of empty cells it reaches, and whether it reaches a cell next to the tail. The tail t' is a goal the search may touch but not pass through, because it moves away on the next step13.

\begin{aligned} S(a) &= \sum_{k=1}^{8} w_k\, f_k(a) \\ a^\ast &= \operatorname{argmax}_{a \in A_{\text{safe}}} S(a) \end{aligned}
14

Here f_k(a) is feature k of the position after move a, w_k its weight, and A_{\text{safe}} the moves that do not end the game. If A_{\text{safe}} is empty, the snake goes straight. Ties keep the earlier move in the order straight, left, right, because a later move must score strictly higher to replace it15.

\begin{aligned} f_1 &= \mathbf{1}[\text{eats}] \\ f_2 &= \begin{cases} 1 & \text{if eats} \\ \max\!\left(0,\ 1 - \dfrac{d_f}{2N}\right) & \text{if the food is reachable} \\ 0 & \text{otherwise} \end{cases} \\ f_3 &= \begin{cases} 1 & \text{if eats or the food is reachable} \\ 0 & \text{otherwise} \end{cases} \\ f_4 &= \begin{cases} R\,/\,(N^2 - |B'|) & \text{if } N^2 > |B'| \\ 0 & \text{otherwise} \end{cases} \\ f_5 &= \min\!\left(1,\ R\,/\,|B'|\right) \\ f_6 &= \mathbf{1}[\text{a reached cell is next to } t'] \\ f_7 &= \tfrac{1}{4}\,\bigl|\{\text{neighbours of } h' \text{ on the board that are not in } B'\}\bigr| \\ f_8 &= |B'|\,/\,N^2 \end{aligned}
161718

Here N = 12, so 2N = 24 and N^2 = 144. The food features use d_f, and R is the number of empty cells the search reaches, not counting the head. The room feature f_5 divides by the body length |B'|, and the area feature f_4 divides by the number of empty cells on the board after the move. f_7 counts the head's neighbours that are on the board and free, and the new tail counts as occupied19.

The committed weights are in snake/data/evaluator.json20. They were learned by the cross-entropy method described below.

FeatureWeightWhat it measures
apple0.72661 if the move eats
food near0.82611 if it eats; else 1 − d_f / 24 when the food is reachable; else 0
food reachable−0.69411 if it eats or the food is reachable; else 0
area−0.2007Empty cells reached, as a share of all empty cells
room for body0.3796Empty cells reached over the body length, capped at 1
tail reachable1.54041 if a reached cell is next to the new tail
exits0.1065Free neighbours of the new head, over 4
length0.7549Body length over 144

The tail-reachable weight is the largest. The two food terms together need a closer look. For food that is reachable and not eaten, they add 0.8261\,(1 - d_f/24) - 0.6941 = 0.1320 - 0.0344\,d_f. That is positive for food within 3 steps, and negative beyond it. Beyond 24 steps it is the full -0.6941. So from the food terms alone, reachable food farther than about 3 steps scores below food that cannot be reached at all, which scores 0. The tuner found this combination; the page does not claim it as a design goal. The other features, and the apple term, shape the choice as well.

Example. A move that eats has f_1 = f_2 = f_3 = 1. Its apple and food terms add 0.7266 + 0.8261 - 0.6941 = 0.8586 to its score, before the area, room, tail, exits and length terms are added.

The simple version below shows only the choice. The full version adds the feature computation and the safety test.

142122
function CHOOSE(game, weights):
    best ← none
    for each action a in (straight, left, right):    # ties keep the earlier action
        if DIES(game, a):
            continue                                 # a move that ends the game is never chosen
        score ← sum over k of weights[k] · FEATURES(game, a)[k]
        if best is none or score > best.score:
            best ← (a, score)
    if best is none:
        return straight                              # every move ends the game
    return best.action

The search runs once and feeds five features: the food distance, the area, the room, the tail test and the food reachability. The tail is a goal, so the escape check can succeed at the tail without the search continuing through it. Distances are counted in whole steps and the food feature is scaled by 2N = 24, so food 24 steps away counts as 0 for f_2, while food on a reachable path still counts for f_3.

The order of the neighbours does not change any feature, since a BFS gives the same distances and reach in any order. The order matters only for the choice, through the tie rule.

Learning the weights: the cross-entropy method

The cross-entropy method (CEM) learns parameters by sampling. It keeps a Gaussian distribution, a bell curve with a mean and a standard deviation, for each parameter. Each generation it draws a population of candidate parameter vectors from that distribution, scores each candidate, keeps the best few (the elites), and moves the distribution toward them. Here the vector has eight entries, one per weight, and each weight has its own Gaussian23.

Each generation draws 48 candidates. Each candidate plays the same 6 boards, whose seeds are drawn anew each generation from 1000 up to 39,999, and its fitness is the mean game score over them. The 12 best are the elites. The Gaussian is then refit to them: its mean becomes the elites' mean, and its standard deviation becomes the elites' spread, floored at 0.05 so that the search never collapses to a single point2425.

\begin{aligned} \theta^{(i)} &= \mu + \sigma \odot \varepsilon^{(i)}, \qquad \varepsilon^{(i)} \sim \mathcal{N}(0, I) \\ F(\theta) &= \frac{1}{G} \sum_{g=1}^{G} s_g(\theta) \\ \mu' &= \frac{1}{K} \sum_{i \in E} \theta^{(i)} \\ \sigma'_j &= \max\!\left(\sqrt{\frac{1}{K} \sum_{i \in E} \bigl(\theta^{(i)}_j - \mu'_j\bigr)^2},\ 0.05\right) \end{aligned}
262725

Here \mu and \sigma are the mean and standard deviation vectors, \odot multiplies each weight by its own standard deviation, and \varepsilon^{(i)} is a standard normal draw. G = 6 is the number of boards, s_g(\theta) the game score of board g, and E the set of K = 12 elites out of 48 candidates. The start is \mu = 0 and \sigma = 1.0 for every weight. The standard deviation divides by K, which is numpy's default, not K - 1.

The champion is chosen on fixed boards, not on the training fitness, since the training boards change each generation. The best candidate of any generation and the top five of the last generation are rounded to four decimals. Each is scored on 32 validation seeds, 40000 to 40031, which lie above the training range and below the benchmark's 50000, and the highest validation score is committed28. The committed run used 30 generations. Its champion came from generation 30, and scored a mean of 96.344 apples and 2,777 steps per game on those 32 boards20.

2930
function CROSS-ENTROPY(generations):
    mean ← zeros(8);  sigma ← 1.0 for every weight
    repeat generations times:
        population ← 48 samples from Normal(mean, sigma)
        score each sample by its mean game score on 6 new boards
        elites ← the 12 best samples
        mean ← average of the elites
        sigma ← max(spread of the elites, 0.05)
    return the candidate that scores best on the validation boards

The simple version shows the idea: sample, keep the best, refit. The full version adds the seeded boards, the candidate ordering and the validation step. Ties in the ordering keep the candidate with the lower index, so the run is repeatable. The worker count changes only the speed, since each candidate's score depends only on its weights and seeds31.

SettingValueNotes
Candidates per generation48Samples from the Gaussian
Games per candidate6All candidates share the same 6 boards in a generation
Generations30The committed run took about 55 minutes on two cores
Elites12The Gaussian is refit to them
Initial sigma, minimum sigma1.0, 0.05Start wide, never narrower than 0.05 per weight
Random seed1Makes the run repeatable: python -m snake cem

The neural net and its 17 senses

The neural net maps 17 numbers, its senses, to 3 numbers, one score per action. It is a function built from weighted sums. The snake takes the action with the largest score. The senses are read in the snake's own frame: ahead is the direction of the heading, and left and right are a quarter turn either side. One learned rule therefore works whichever way the snake faces32.

Six of the senses come from a run, the three danger flags and the three free runs: the number of free cells walking from the head in one direction before the first obstacle, where an obstacle is a wall or any body cell, tail included. A flood fill is a breadth-first search over empty cells that counts how much room a direction opens up. The senses are the danger flag, the run, the room, the food and tail offsets, and a one-hot heading. A one-hot heading has a 1 for the current heading and 0 elsewhere3334.

\begin{aligned} x_k &= \mathbf{1}[\text{run}_k = 0], \qquad x_{3+k} = \frac{\text{run}_k}{11}, \qquad x_{14+k} = \frac{R_k}{30}, \qquad k \in \{\text{ahead}, \text{left}, \text{right}\} \\ x_{6} &= \operatorname{clip}\!\left(\frac{(f - h) \cdot a}{11}\right), \qquad x_{7} = \operatorname{clip}\!\left(\frac{(f - h) \cdot r}{11}\right) \\ x_{8} &= \operatorname{clip}\!\left(\frac{(t - h) \cdot a}{11}\right), \qquad x_{9} = \operatorname{clip}\!\left(\frac{(t - h) \cdot r}{11}\right) \\ x_{10+H} &= 1, \quad \text{all other heading inputs } 0 \\ \operatorname{clip}(v) &= \max(-1,\ \min(1,\ v)) \end{aligned}
34

Here \text{run}_k is the run in direction k, R_k the flood-fill count from the cell next to the head in that direction, capped at 30, h the head, f the food, t the tail, a the unit vector of the heading and r the unit vector a quarter turn to its right. The offsets are divided by N - 1 = 11, the largest possible distance across the board, and clipped to [-1, 1]3536. Example. The snake heads east at (6, 6) and the food is at (9, 6). Its forward offset is 3/11 \approx 0.273 and its right offset is 0.

The net is one hidden layer of 16 hidden units, followed by 3 outputs. Each hidden unit takes a weighted sum of the 17 senses plus a bias, a constant offset, and passes it through tanh, a squashing function that maps any number into the range (−1, 1). Each output is a weighted sum of the hidden units plus its own bias. The outputs are in the order left, straight, right, and the largest one is the action. The net does not check for danger itself, so a poor output can send the snake into a wall. Avoiding that has to be learned from the game score37.

h = \tanh(x\,W_1 + b_1), \qquad z = h\,W_2 + b_2, \qquad \text{action} = \operatorname{argmax}_k\, z_k, \qquad 17 \cdot 16 + 16 + 16 \cdot 3 + 3 = 339
3837

Here W_1 is a 17 \times 16 matrix of input weights, b_1 the 16 hidden biases, W_2 a 16 \times 3 matrix of output weights and b_2 the 3 output biases. Ties in z go to the lower index, which is the order left, straight, right. The 339 numbers are stored as one flat vector called a genome, and the genetic algorithm works on that vector39.

403441
function ACT(game):
    x ← SENSE(game)                                  # 17 inputs, in the snake's frame
    h ← tanh(x · W1 + b1)                            # 16 hidden units
    z ← h · W2 + b2                                  # left, straight, right
    return the index of the largest z                # ties go to the lower index

The run counts only cells in a straight line, so it cannot show a pocket that the snake would enter by turning. The room counts every empty cell that a flood fill reaches from the adjacent cell, so it shows the size of the pocket. The cap of 30 keeps each flood fill cheap, since the net only needs to know whether a pocket is small42.

The same arithmetic runs in the browser, in web/js/snake-core.js, so the page's network view matches the benchmark43.

Learning the weights: the genetic algorithm

A genetic algorithm (GA) improves a population of genomes by three operators. Selection picks parents, favouring the fitter genomes. Crossover mixes two parents into a child. Mutation adds small random changes. No gradients are computed. The best genomes are copied unchanged each generation, a practice called elitism, so the best result never gets lost44.

The 60 starting genomes are random: each of their 339 weights is drawn from a normal distribution with mean 0 and standard deviation 0.545. Each generation, 8 boards are drawn from seeds 1000 up to 39,999, and every genome plays the same 8 boards. Its fitness is the mean game score over them. The 4 best genomes are copied unchanged, and the other 56 are children4647.

A parent is chosen by a tournament of size 3. Three genomes are drawn at random with replacement, and the fittest of the three is the parent. Two parents are chosen per child. Uniform crossover then takes each of the 339 weights from one parent or the other with probability ½. Gaussian mutation changes each weight with probability 0.1, by a random amount drawn from a normal distribution with standard deviation 0.1548.

\begin{aligned} \text{parent} &= \operatorname{argmax}_{i \in C} F(g_i), \qquad C \text{: three indices drawn uniformly with replacement} \\ c_j &= m_j\, a_j + (1 - m_j)\, b_j, \qquad m_j \sim \text{Bernoulli}(\tfrac{1}{2}) \\ c_j &\leftarrow c_j + \varepsilon_j, \qquad \varepsilon_j \sim \mathcal{N}(0,\ 0.15^2) \text{ with probability } 0.1 \end{aligned}
4950

Here a and b are the two parents, c the child, m_j the crossover bit of weight j, and F the fitness. Example. With 60 genomes and 4 elites, each generation makes 56 children, so the population size stays at 6051.

5248
function EVOLVE(generations):
    population ← 60 genomes, each weight drawn from Normal(0, 0.5²)
    repeat generations times:
        fitness ← each genome's mean game score on 8 new boards
        next ← the 4 fittest genomes, unchanged           # elitism
        while |next| < 60:
            a ← TOURNAMENT(fitness, 3);  b ← TOURNAMENT(fitness, 3)
            next ← next + [MUTATE(CROSSOVER(a, b))]
        population ← next
    return the best genome, chosen on the validation boards

Elitism keeps the top four genomes unchanged, so crossover and mutation cannot destroy them. Because the boards change each generation, a genome's fitness is measured again on new boards, so the fitness of one generation is not comparable with another's. The champion is therefore picked on fixed boards, as in the cross-entropy method. The best genome ever seen and the top five of the last generation are scored on seeds 20000 to 200155354. Those seeds fall inside the training range, so this check is same-distribution, not held-out.

Each genome's fitness is one mean over the 8 boards, so the same boards decide between genomes in a generation. A genome cannot memorise a fixed set of boards, because the next generation draws new ones55.

Baselines: random and greedy

The random policy takes each action with the same probability. It uses its own seeded generator, so a game can be repeated exactly. It senses nothing, so it dies quickly56.

P(\text{left}) = P(\text{straight}) = P(\text{right}) = \tfrac{1}{3}
57

The greedy policy makes a one-step decision with no search. For each safe move it measures the Manhattan distance, the number of grid steps between two cells ignoring walls, from the new head to the food. It takes the move with the smallest distance. It has no learned part.

d(a) = |x_a - x_f| + |y_a - y_f|, \qquad a^\ast = \operatorname{argmin}_{a \in A_{\text{safe}}} d(a)
58

Here (x_a, y_a) is the head's cell after move a and (x_f, y_f) the food. Straight is tried first, so a tie keeps the snake going straight.

58
function GREEDY(game):
    if game has no food:
        return straight
    best ← straight;  best_distance ← none
    for each action a in (straight, left, right):   # straight first, so ties go straight
        if DIES(game, a):
            continue
        cell ← the head's cell after a
        distance ← |cell.x − food.x| + |cell.y − food.y|
        if best_distance is none or distance < best_distance:
            best ← a;  best_distance ← distance
    return best

Baseline: the breadth-first search planner

The planner is the strongest classic baseline. It uses breadth-first search (BFS) for a shortest route to the food, then for a safety check, and, if needed, for a route to the tail. Its key idea is a safety check. After the snake eats, the tail stays in place, so the head must still be able to reach it. The planner takes the food route only if that holds5960.

The check is a second BFS, from the food to the tail, through the cells the snake would occupy after eating: its body and the food route. If the check fails, the planner follows its tail instead. The tail moves away each step, so a route to it is always open, and this is called tail-chasing. The planner re-plans every step, so it switches to the food route as soon as the check passes. If the planned step is unsafe or no route exists, it picks the safe move that leaves the largest flood-fill region, and if no move is safe it goes straight61.

The page's PLANNER HINT calls the same code on the server, and the route it returns is labelled as food, tail or none62.

61605963
function PLANNER(game):
    path ← PLAN-ROUTE(game)
    if path is not empty and its first cell is a legal, safe step:
        return the action that turns the head toward the first cell of path
    # boxed in: take the safe move with the most room
    return the safe action whose cell opens the largest flood-fill region, else straight

function PLAN-ROUTE(game):
    if the food route passes the tail-chasing check:
        return the food route
    return the route to the tail

The core of the planner is BFS, which finds a shortest route in steps because it reaches each cell first along a shortest path. The planned move is the first step of the route, and the room rule replaces it only when that step is unsafe or no route exists64.

Results on held-out boards

The table compares every agent on the same 200 seeded games, seeds 50000 to 50199 on the 12 × 12 board. These seeds are never used for training or for validation. The median is the middle value of the apples counts, and the death rate is the share of games that ended in a wall or body collision. A starved game is different: the snake is still alive, but it has looped for two laps without an apple6566.

AgentMean applesMedianMaxDeath rateStarved (of 200)
evaluation function90.13861330.0%200
planner (BFS)56.1349.51370.0%200
greedy20.121947100.0%0
neural net (v2)13.69132638.5%123
random0.1602100.0%0

The table is measured on 200 games per agent, seeds 50000 to 50199, and is committed in results/snake_benchmark.md67. The evaluation function eats the most apples, and it never dies. But every one of its 200 games ends by starvation, so it stalls instead of losing. The planner is the same: it never dies, and it starves on all 200 boards, not on some of them.

The evolved net (v2) eats 13.69 apples on average, which beats random by a wide margin and shows that it learned to eat. It does not beat greedy's 20.12, and it dies in 38.5% of games. Greedy dies in every game, but it eats more before it does. Treat the evolved net's row as a result, not a win.

Which way the net turns

The mean score hides the turning pattern. Over the first 40 benchmark boards, seeds 50000 to 50039, the net made 19,829 moves: 17,033 straight (85.9%), 2,793 left (14.1%), and 3 right (0.02%). The net almost never turns right, and it turns left about one move in seven. The counts are committed in results/snake_net_actions.json, from python -m snake actions --write6869.

\text{share}_a = \frac{n_a}{\sum_{b} n_b}, \qquad \sum_b n_b = 19{,}829
70

Here n_a is the number of moves the net made with action a. The shares are 85.9% straight, 14.1% left and 0.02% right, from the counts above.

Training history

Each row is one version of the net. The first version was trained on three fixed boards. The live champion, v2, uses fresh boards each generation. The two longer runs were scratch runs that were not committed, so no file in results/ backs their numbers.

VersionWhat changedEvolved mean applesMedianDeath rateStarved (of 200)
v13 fixed training boards, 14 senses, 291 weights, 100 generations of 80 × 3 games2.0515.0%190
v2 (live)Fresh boards each generation, 8 games, starvation penalty 0.5, room senses, 339 weights, 80 generations of 6013.691338.5%123
v3aStarvation penalty 2.0, population 100, 200 generations, 8 games. Scratch run, not committed: no file in results/ backs these numbers.0.931100.0%0
v3bStarvation penalty 0.5, population 100, 200 generations, 8 games. Scratch run, not committed: no file in results/ backs these numbers.13.221353.5%93

The v2 run is logged in results/snake_train_log.jsonl. Its 80 generations took 583 seconds, about ten minutes on two cores, and its best generation was the 80th71. The v1 log is results/snake_train_log_v1.jsonl, and the evaluation function's log is results/snake_eval_train_log.jsonl7273.

Parameters and how they were chosen

The genetic algorithm's settings are listed below. Its defaults are the committed run, and python -m snake evolve --help lists the flags74.

ParameterValueNotes
Board12 × 12Fixed by the rules. The snake starts with 3 segments heading east.
Starvation2 laps (288 steps) without foodEnds the game. Same rule for every agent in the benchmark.
Population60Sized to fit about 10 minutes on two cores.
Generations80Time budget. The 200-generation runs (v3a, v3b) were still improving at the end.
Games per genome8Every genome in a generation plays the same 8 boards.
Training boardsSeeds drawn from 1000 to 39999, new each generationNever overlaps the benchmark seeds (50000 and up).
Fitness per gameapples + up to 0.25 survival bonus; −0.0002 per step beyond 300Survival bonus breaks ties between early learners.
Starvation penalty0.5, and no survival bonusLooping is worse than dying cleanly. A penalty of 2.0 was tried in v3a and made the population learn to die early (see the history).
Elites4Copied unchanged each generation.
Tournament size3Parents are the best of 3 random genomes.
CrossoverUniform, p = 1/2 per weightEach weight comes from either parent.
Mutationrate 0.10 per weight, sigma 0.15A first try at sigma 0.3 on 8% of weights learned slowly.
Initial weightsNormal, sigma 0.5Random start.
ChampionBest of the best-ever genome and the last generation's top 5Re-scored on 16 fixed validation seeds (20000 to 20015), not on the benchmark. These seeds fall inside the training range (1000 to 39999), so this check is same-distribution, not held-out.
Random seed1Makes the run repeatable: python -m snake evolve.

The evaluation function's cross-entropy settings are in the table in its section above.

How these were chosen: by trial, not by a systematic sweep. The first version used three fixed training boards and learned to memorise them: its best generation scored 6.0 apples per game on those boards, against 2.05 on the benchmark boards. Fresh boards each generation fixed most of that. The starvation cap was first set to four laps, then cut to two to keep looping games cheap; the benchmark uses the same cap for every agent. The population and generation counts were set by the time budget. Two longer runs (v3a, v3b: 200 generations, population 100) did not beat v2. v3a's penalty of 2.0 collapsed into early death. v3b, with the penalty back at 0.5, reached 13.22 apples, within noise of v2's 13.69 and not better, so v2 stays the live champion. No parameter was tuned on the benchmark seeds.