Snake
One recorded episode planned by PFT-DPW, replayed in 3D. Drag to orbit, scroll to zoom, and use the bar to play, scrub and switch camera.
SnakePOMDP is the arcade game with the food hidden. The snake observes its
own body exactly and has to find food it cannot see, using a short-range vision
window and a noisy directional scent. The task is to grow to target_length
without hitting a wall, hitting itself, or going too long without eating.
Ported from the MDP version in snake-rl, which is fully observable and rewards the same events.
What the agent sees and does
State — a
float64vector of length5 + 2 * target_length: status, length, steps since food, food row and column, then the body cells head first, with-1in unused slots. The heading is not stored; it is the direction from the second body cell to the head.Actions (discrete) —
0turn left,1go straight,2turn right, relative to the current heading. There is no reversing action, because a snake that turned back on itself would walk into its own neck every time.Observations (discrete) — a flat tuple of integers,
(1, scent, seen_row, seen_col, r0, c0, r1, c1, ...), with three parts:the body, reported exactly, head first. The body update is deterministic, so this tells the agent nothing it could not have computed — it is there so the state is fully recoverable from the observation history;
seen, the food’s exact cell when the food is inside the vision window (a square of Chebyshev radius
window_radius, clipped to the grid) and the window fires, which happens with probabilitydetection_probability;-1, -1otherwise. There are no false positives, so a sighting is conclusive;scent, one of four diagonal quadrants relative to the head, correct with probability
scent_accuracy. Food that shares the head’s row or column is compatible with two quadrants, which split that probability between them.
Every terminal state emits one fixed reading,
(0,), instead, so a win and a wall hit are indistinguishable through the sensor.
Formal definition
The environment is the POMDP \(\langle S, A, Z, T, O, R, b_0, \gamma \rangle\).
State space. Let:
\(n\) =
grid_size;\(G = \{0..n{-}1\}^2\) the playable cells, each written (row, column);
\(L\) =
target_length;\(K\) =
starvation_limit(default \(2n^2\)).
A state is a body (head first), a food cell, a starvation counter and a status tag:
with:
\(\mathbf{z} = (z_1, \dots, z_\ell)\) the occupied cells;
\(f\) the food (\(\varnothing\) if none);
\(m\) steps since food;
the status \(\textsf{RUNNING}\) while alive, or why the episode ended — head off the grid, head into the body, target length reached, or \(K\) steps without food:
The heading is not stored — it is recovered as \(z_1 - z_2\), so the body alone determines where the snake can go next.
Action space. Relative to the heading, so reversing is unrepresentable:
\(0\) turns the heading 90° counter-clockwise;
\(1\) keeps it;
\(2\) turns it 90° clockwise.
Then the head moves one cell along the new heading.
Observation space. The sentinel \(\textsf{TERM}\) from a terminal state, or a \(\textsf{LIVE}\) reading with three components:
a scent quadrant in \(\{0,1,2,3\}\) — the food’s direction from the head: \(0\) north-east, \(1\) north-west, \(2\) south-east, \(3\) south-west (north is row \(-1\), east is column \(+1\));
the food’s cell if it was sighted, \(\varnothing\) if not;
the body, head first.
Transition model. Deterministic except for where the food respawns. The model uses:
Heading. \(h = z_1 - z_2\), one of north \((-1, 0)\), east \((0, 1)\), south \((1, 0)\), west \((0, -1)\).
Rotation. \(\mathcal{R}_a\) rotates it as action \(a\) says.
Rotate the heading, step, then resolve:
Releasing the tail is what makes the cell it has just left safe to enter. The counter resets on a meal, \(m' = 0\) if eating else \(m + 1\), and the status is decided in this order:
Wall and self are checked first: a snake that reaches its target length by walking into a wall has still hit the wall. The only randomness is the respawn, uniform over the cells the new body leaves free:
and only when the step ate and did not win; otherwise \(f' = f\).
Observation model. A terminal state emits the sentinel \(\textsf{TERM}\). Otherwise the snake sees its own body exactly, a scent quadrant \(q\) and a possible sighting \(\hat f\) of the food:
Sighting. The food is reported only when it is inside the Chebyshev window
of radius \(r\) = window_radius (default 2) around the head, and then
only with probability \(p_{\text{det}}\) =
detection_probability:
With \(p_{\text{det}} < 1\) a silent window is not proof the food is elsewhere — absence of evidence stays weak evidence rather than a certainty.
Scent. A noisy quadrant reading, with these quadrants of the head:
\(0\) north-east;
\(1\) north-west;
\(2\) south-east;
\(3\) south-west.
Let \(Q(f' - z'_1) \subseteq \{0,1,2,3\}\) be the quadrants compatible
with the offset — two of them when the
food shares the head’s row or column, one otherwise. With \(p_{\text{scent}}\) =
scent_accuracy:
which sums to one in the tie case too. At \(p_{\text{scent}} = 0.25\) the scent is pure noise; at \(1.0\) it localises the food to a quadrant in one step. The default \(0.7\) makes several readings worth accumulating.
Reward function. A pure function of \((s, a)\) — eating and dying are both settled by the deterministic half of the transition, and the respawn cannot change either:
so \(R \in [-1, 1]\). Note a \(\textsf{WIN}\) pays nothing beyond the meal that caused it.
Initial belief. A fixed three-cell snake, \(\mathbf{z}_0 = ((c, c), (c, c-1), (c, c-2))\) with \(c = \lfloor n/2 \rfloor\), heading east, with the food uniform over every cell it leaves free:
The opening observation is the sentinel and nothing conditions on it: the belief starts from this prior, and the first sensor reading arrives after the first action.
Discount. \(\gamma\) = discount_factor, default \(0.98\).
Reaching the target takes hundreds of steps at \(n = 12\), so a shorter
horizon would flatten the difference between finding food soon and finding it
eventually.
Terminal set. Anything but \(\textsf{RUNNING}\):
Dynamics
The body update is deterministic. The action turns the heading, the head steps into the next cell, and the tail is released — unless the step ate the food, in which case the tail stays and the snake grows by one. That pair decides a rule that is easy to get wrong: stepping into the cell the tail has just left is legal, but stepping into the tail while eating is a self hit.
The only random part of a transition is where the food respawns after it is eaten: uniformly over the cells the new body does not occupy.
Wall and self hits are checked first, then the win, then starvation. A snake
that reaches its target length by walking into a wall has still hit the wall.
starvation_limit defaults to 2 * grid_size ** 2.
The playable area is grid_size by grid_size cells. The walls are not
cells of the state: they sit just outside that area, so a head that steps off
the grid has hit one. The renderer draws them as a border around the board.
Rewards
Event |
Reward |
|---|---|
Eat the food (including the winning meal) |
+1.0 |
Die to a wall, to itself or to starvation |
-1.0 |
Anything else |
0.0 |
reward_range is (-1.0, 1.0). Winning happens by eating, so it pays the
same +1 and nothing more. Eating and dying cannot both happen on one step:
the food is never on a body cell, so the step that reaches it can be neither a
wall nor a self hit.
Key settings
Argument |
Default |
What it changes |
|---|---|---|
|
|
Side of the playable grid; must be at least 4. |
|
|
Body length that ends the episode as a win. |
|
|
Chebyshev radius of the vision window (a 5×5 window by default). |
|
|
Chance of reporting food inside the window. |
|
|
Chance the scent names a quadrant compatible with the food. |
|
|
Steps without food before the snake starves. |
|
|
Metrics
task_completion_rateis the fraction of episodes that reachedtarget_length.ended_by_goal_rate,ended_by_failure_rateandended_by_timeout_ratepartition the episodes between winning, dying and running out of the runner’s steps.wall_death_rate,self_death_rateandstarvation_death_ratesay which death it was, which matters because they call for opposite fixes — a planner that walks into walls is searching badly, one that starves is not searching at all.max_steps_since_foodreports how close an episode came to starving even when it did not.
Visualization
Runs write a trace of each episode through the environment’s episode visualizer. The results site replays it in 3D, as the replay on this page does.
Vectorized model
SnakeVectorizedModel is the torch generative model VOPP plans on. It
supports every SnakePOMDP configuration, so it declines none.
State rows are the scalar state vectors unchanged. The body has
target_lengthslots with-1past the current length; a live snake is shorter thantarget_length, so the slots always suffice.Observation rows are the scalar reading padded with
-1to4 + 2 * target_lengthcolumns. The terminal reading(0,)becomes[0, -1, ..., -1].Conversions between the two are
snake_observation_to_rowandsnake_row_to_observation.Observation keys pack the reading into one int64. The packing is one to one while it fits in 63 bits (
target_lengthup to 22 on the default 12×12 grid). Past that the arithmetic wraps, and two readings can share a search-tree node.
Can I use?
|
Discrete |
Continuous |
|---|---|---|
State |
✔️ |
❌ |
Action |
✔️ |
❌ |
Observation |
✔️ |
❌ |
Also supports |
|
|---|---|
Native C++ backend |
❌ |
Vectorized (torch) model |
✔️ |
In the |
❌ (import the class directly) |
Optional dependencies |
None |
Example
from POMDPPlanners.environments.snake_pomdp import SnakePOMDP, SnakeBelief
env = SnakePOMDP(grid_size=12, target_length=10)
belief = SnakeBelief.from_environment(env, n_particles=200)
Parameters
- class POMDPPlanners.environments.snake_pomdp.SnakePOMDP(grid_size=12, target_length=10, window_radius=2, detection_probability=0.9, scent_accuracy=0.7, starvation_limit=None, discount_factor=0.98, name='Snake', output_dir=None, debug=False, use_queue_logger=False)[source]
Bases:
DiscreteActionsEnvironmentGrow the snake to
target_lengthwithout hitting a wall, itself or the clock.- Dynamics:
The body update is deterministic. The action turns the heading, the head steps into the next cell, and the tail is released unless the step ate the food – which is what makes the snake grow. Stepping into the cell the tail has just left is legal; stepping into the tail while eating is not, because an eaten step keeps the tail where it is. The only random part of a transition is where the food respawns after it is eaten: uniformly over the cells the new body does not occupy.
- Observation model:
The body is reported exactly. The 5x5 window around the head reports the food’s cell with probability
detection_probabilitywhen the food is inside it and nothing when it is not – there are no false positives. The scent names a diagonal quadrant, correct with probabilityscent_accuracy; when the food shares the head’s row or column two quadrants are correct, and they split that probability between them. Every terminal state emits one fixed reading instead.- Reward:
+1for eating,-1for dying to a wall, to itself or to starvation,0otherwise. Winning happens by eating, so it pays the+1and nothing more. Eating and dying cannot both happen on one step: the food is never on a body cell, so a step that reaches it neither leaves the grid nor lands on the body.- Terminal:
A wall hit, a self hit,
starvation_limitsteps with no food, ortarget_lengthreached. The four are distinguished in the state so the metrics can report why an episode ended, but the agent’s sensor reports the same reading for all of them.
- Parameters:
- grid_size
Side length of the playable grid.
- target_length
Body length that counts as completing the task.
- window_radius
Chebyshev radius of the vision window.
- detection_probability
Chance of seeing food that is inside the window.
- scent_accuracy
Chance the scent names a correct quadrant.
- starvation_limit
Steps without food before the snake starves.
- state_size
Width of a state vector.
Example
>>> import numpy as np >>> np.random.seed(0) >>> env = SnakePOMDP() >>> state = env.initial_state_dist().sample()[0] >>> env.is_terminal(state) False >>> env.snake_length(state) 3 >>> next_state, observation, reward = env.sample_next_step(state, 1) >>> observation[0] 1
- decode_observation(observation)[source]
Unpack a reading into
(body, seen, scent).- Parameters:
observation (
Tuple[int,...]) – A reading produced by this environment.- Return type:
Tuple[Tuple[Tuple[int,int],...],Optional[Tuple[int,int]],int]- Returns:
The observed body, the sighted cell or
None, and the quadrant.- Raises:
ValueError – If
observationis the terminal reading, which has no body, sighting or scent to unpack.
- encode_observation_tuple(body, seen, scent)[source]
Pack one reading into the flat integer tuple the agent receives.
- Parameters:
- Return type:
- Returns:
(OBSERVATION_LIVE, scent, seen_row, seen_col, r0, c0, r1, c1, ...)with-1, -1standing for “nothing seen”.
- episode_visualizer()[source]
Return the visualizer that writes this environment’s traces.
- Return type:
SnakeVisualizer
- get_metric_specs()[source]
Declare the Snake metrics.
Completion reduces with
ANY: reaching the target length is something that happens once and ends the episode, not a condition every step has to hold.ended_by_*reduce withLAST– a won episode’s last recorded step is the terminal bookkeeping step, a dead one’s is the death, and an episode that simply ran out of runner steps is neither.The dangers here are the three ways to die. Each reduces with
LASTrather thanSUM, so each is a rate over episodes: a death happens at most once and ends the episode, and summing a state-derived channel would double-count it, because the death state is recorded twice – once as a step’s successor and again as the terminal bookkeeping step.max_steps_since_foodis the one severity metric that means something, since it is the only danger signal an episode that did not die reports at all.- Return type:
- Returns:
One spec per metric named in
SnakePOMDPMetrics.
- hash_observation(observation)[source]
Return a hashable key agreeing with
is_equal_observation().
- heading(state)[source]
Return the heading of
stateas a(row, col)step.The heading is not stored: it is the direction from the second body cell to the head, which is the only direction the head can have arrived from.
- Parameters:
state (
ndarray) – A state vector.- Return type:
- Returns:
One of
DIRECTIONS.- Raises:
ValueError – If the body is shorter than two cells, which no reachable state has.
- initial_observation_dist()[source]
The pre-step reading, which carries no information.
- Return type:
- Returns:
A point mass on the terminal reading’s tag with no body, sighting or scent. Nothing conditions on it: the belief starts from the initial state distribution’s own uniform prior over the free cells, and the first real reading arrives after the first action.
- initial_state_dist()[source]
The fixed starting snake with the food uniform over the free cells.
The return type is narrowed from
Distributionso callers can reachSnakeInitialStateDistribution.bodyandSnakeInitialStateDistribution.free_cells()– the belief’s prior is built from both, and casting at every call site would be noise.- Return type:
SnakeInitialStateDistribution
- is_equal_observation(observation1, observation2)[source]
Check whether two readings are the same tuple of integers.
- observation_log_probability(next_state, action, observations)[source]
Log-likelihood of each candidate reading under
next_state.The three parts of a reading are independent given the state, so their log-likelihoods add: the body is a point mass, the sighting is a Bernoulli draw with no false positives, and the scent is the categorical law
scent_probabilities()returns.
- reward(state, action, next_state=None)[source]
Score one step:
+1for eating,-1for dying,0otherwise.The reward is a pure function of
(state, action). Eating and dying are both settled by the deterministic half of the transition, and the only random part – where the food respawns – cannot change either, sonext_stateis accepted and ignored andreward_requires_next_statestaysFalse.
- sample_next_state(state, action, n_samples=1)[source]
Move the snake, and respawn the food when it was eaten.
Runs in the C++
_nativemodule. The respawn cell is drawn from that module’s RNG, which_native.set_seedseeds andnp.random.seeddoes not.- Parameters:
- Return type:
- Returns:
A single
float64state whenn_samples == 1, else an(n_samples, state_size)float64array.- Raises:
ValueError – If the new body leaves no free cell for the food, which cannot happen while
target_lengthfits in the grid.
- sample_next_state_batch(states, action)[source]
Move every input snake under one action.
- Parameters:
- Return type:
- Returns:
(N, state_size)float64array. The dtype matchessample_next_state()so a particle filter mixing the two paths cannot silently change particle precision.
- sample_next_step(state, action)[source]
Draw
(next_state, observation, reward)in one native call.The draws are the ones
sample_next_state()followed bysample_observation()would make, in the same order, so under one seed of_native.set_seedthe two routes return the same step. The single call exists because POMCP calls this once per tree step and per rollout step, and three Python-to-C++ crossings cost more than the step itself.
- sample_observation(next_state, action, n_samples=1)[source]
Report the body, a possible sighting and a noisy scent.
Runs in the C++
_nativemodule. The detection and scent draws come from that module’s RNG, which_native.set_seedseeds andnp.random.seeddoes not.
- scent_probabilities(head, food)[source]
Probability of each quadrant given the head and the food cell.
- Parameters:
- Return type:
- Returns:
(4,)float64array indexed bySnakeQuadrant. The compatible quadrants sharescent_accuracybetween them and the rest share what is left, so the four always sum to one – including the tie case, where the food shares the head’s row or column and two quadrants are compatible.
- simulate_random_rollout(state, action_sampler, max_depth, discount_factor, depth=0)[source]
Random rollout run step by step in C++.
Actions are drawn uniformly from the three actions with
np.random.randintbefore the call, not fromaction_sampler: the native loop cannot call back into Python per step. That is the same law as a uniformaction_sampler, which is what the planners that call this pass.- Parameters:
- Return type:
- Returns:
The discounted sum of rewards from
depthtomax_depthor the first terminal state.
- step_info(state, action, next_state)[source]
Report the per-step channels this environment’s metrics are built on.
Draws no randomness: the eat and death channels re-run the deterministic half of the transition, and everything else is read off a state.
The progress channels are read from
next_statewhen there is one, for the reason Battleship documents: the episode runner checks its step budget before it checks terminality, so an episode whose final allowed step reaches the target length records no terminal bookkeeping step, and reading progress fromstatealone would score that win as a timeout.- Parameters:
- Return type:
- Returns:
The channels named by
SnakeStepChannel. The eat channel reports0.0on the terminal step, where no action was taken.
- termination(state)[source]
Return why
stateis terminal, orRUNNINGwhen it is not.- Return type:
SnakeTermination- Parameters:
state (ndarray)
- transition_log_probability(state, action, next_states)[source]
Log-probability of each candidate successor.
The body update is deterministic, so a candidate scores
-infunless it agrees with it exactly. When the step ate and the episode continues, the food respawns uniformly over the free cells and every consistent candidate shares that probability.
- transition_outcome(state, action)[source]
Resolve the deterministic half of one transition.
Everything except where the food respawns is settled here: the new body, whether the step ate, the new counter and the termination reason. The reward and the metrics both read this, so the rules are stated once.
See also
Base Environment Class — the full catalog and the environment interface.