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 float64 vector of length 5 + 2 * target_length: status, length, steps since food, food row and column, then the body cells head first, with -1 in unused slots. The heading is not stored; it is the direction from the second body cell to the head.

  • Actions (discrete) — 0 turn left, 1 go straight, 2 turn 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 probability detection_probability; -1, -1 otherwise. 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:

\[s = \big(\mathrm{status},\; \mathbf{z},\; f,\; m\big), \qquad S = \mathcal{T} \times G^{\leq L} \times (G \cup \{\varnothing\}) \times \{0..K\}\]

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:

\[\mathcal{T} = \{\textsf{RUNNING}, \textsf{WALL}, \textsf{SELF}, \textsf{WIN}, \textsf{STARVATION}\}\]

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:

\[A = \{\textsf{turn\_left},\; \textsf{straight},\; \textsf{turn\_right}\} = \{0, 1, 2\}\]
  • \(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.

\[Z = \{\textsf{TERM}\} \;\cup\; \{\textsf{LIVE}\} \times \{0,1,2,3\} \times (G \cup \{\varnothing\}) \times G^{\leq L}\]

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:

\[h' = \mathcal{R}_a(h), \qquad z'_1 = z_1 + h'\]
\[\begin{split}\mathbf{z}' = \begin{cases} (z'_1, z_1, \dots, z_\ell) & z'_1 = f \quad (\text{eat: tail held}) \\ (z'_1, z_1, \dots, z_{\ell-1}) & \text{otherwise} \quad (\text{tail released}) \end{cases}\end{split}\]

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:

\[\begin{split}\mathrm{status}' = \begin{cases} \textsf{WALL} & z'_1 \notin G \\ \textsf{SELF} & z'_1 \in \{z'_2, \dots\} \\ \textsf{WIN} & |\mathbf{z}'| \geq L \\ \textsf{STARVATION} & m' \geq K \\ \textsf{RUNNING} & \text{otherwise} \end{cases}\end{split}\]

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:

\[\Pr[f' = k] = \frac{1}{|G \setminus \mathbf{z}'|}, \qquad k \in G \setminus \mathbf{z}'\]

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:

\[o = \big(\textsf{LIVE},\; q,\; \hat{f},\; \mathbf{z}'\big)\]

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:

\[\Pr[\hat{f} = f'] = p_{\text{det}} \cdot \mathbb{1}\big[\lVert f' - z'_1 \rVert_\infty \leq r\big], \qquad \hat{f} = \varnothing \text{ otherwise}\]

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:

\[\begin{split}\Pr[q = k] = \begin{cases} p_{\text{scent}} / |Q| & k \in Q \\ (1 - p_{\text{scent}}) / (4 - |Q|) & k \notin Q \end{cases}\end{split}\]

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:

\[\begin{split}R(s, a) = \begin{cases} +1 & \text{the step eats} \\ -1 & \mathrm{status}' \in \{\textsf{WALL}, \textsf{SELF}, \textsf{STARVATION}\} \\ 0 & \text{otherwise, and for terminal } s \end{cases}\end{split}\]

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:

\[b_0(s) = \mathbb{1}[\mathbf{z} = \mathbf{z}_0] \cdot \frac{\mathbb{1}[f \in G \setminus \mathbf{z}_0]}{|G \setminus \mathbf{z}_0|} \cdot \mathbb{1}[m = 0] \cdot \mathbb{1}[\mathrm{status} = \textsf{RUNNING}]\]

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}\):

\[S_T = \{s : \mathrm{status} \neq \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

grid_size

12

Side of the playable grid; must be at least 4.

target_length

10

Body length that ends the episode as a win.

window_radius

2

Chebyshev radius of the vision window (a 5×5 window by default).

detection_probability

0.9

Chance of reporting food inside the window.

scent_accuracy

0.7

Chance the scent names a quadrant compatible with the food.

starvation_limit

None (2 * grid_size ** 2)

Steps without food before the snake starves.

discount_factor

0.98

Metrics

  • task_completion_rate is the fraction of episodes that reached target_length.

  • ended_by_goal_rate, ended_by_failure_rate and ended_by_timeout_rate partition the episodes between winning, dying and running out of the runner’s steps.

  • wall_death_rate, self_death_rate and starvation_death_rate say 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_food reports 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_length slots with -1 past the current length; a live snake is shorter than target_length, so the slots always suffice.

  • Observation rows are the scalar reading padded with -1 to 4 + 2 * target_length columns. The terminal reading (0,) becomes [0, -1, ..., -1].

  • Conversions between the two are snake_observation_to_row and snake_row_to_observation.

  • Observation keys pack the reading into one int64. The packing is one to one while it fits in 63 bits (target_length up 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?

SnakePOMDP

Discrete

Continuous

State

✔️

❌

Action

✔️

❌

Observation

✔️

❌

Also supports

Native C++ backend

❌

Vectorized (torch) model

✔️ SnakeVectorizedModel (every configuration)

In the get_environment registry

❌ (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: DiscreteActionsEnvironment

Grow the snake to target_length without 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_probability when the food is inside it and nothing when it is not – there are no false positives. The scent names a diagonal quadrant, correct with probability scent_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:

+1 for eating, -1 for dying to a wall, to itself or to starvation, 0 otherwise. Winning happens by eating, so it pays the +1 and 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_limit steps with no food, or target_length reached. 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 (int)

  • target_length (int)

  • window_radius (int)

  • detection_probability (float)

  • scent_accuracy (float)

  • starvation_limit (int | None)

  • discount_factor (float)

  • name (str)

  • output_dir (Path | None)

  • debug (bool)

  • use_queue_logger (bool)

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
body(state)[source]

Return the ordered body cells of state, head first.

Return type:

Tuple[Tuple[int, int], ...]

Parameters:

state (ndarray)

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 observation is 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:

Tuple[int, ...]

Returns:

(OBSERVATION_LIVE, scent, seen_row, seen_col, r0, c0, r1, c1, ...) with -1, -1 standing for “nothing seen”.

episode_visualizer()[source]

Return the visualizer that writes this environment’s traces.

Return type:

SnakeVisualizer

food(state)[source]

Return the food cell of state, or None when there is none.

Return type:

Optional[Tuple[int, int]]

Parameters:

state (ndarray)

free_cells(body)[source]

Flat indices of the grid cells body does not occupy.

Return type:

ndarray

Parameters:

body (Sequence[Tuple[int, int]])

get_actions()[source]

Return the three actions: turn left, go straight, turn right.

Return type:

List[int]

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 with LAST – 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 LAST rather than SUM, 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_food is 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:

List[StepInfoMetric]

Returns:

One spec per metric named in SnakePOMDPMetrics.

hash_action(action)[source]

Return a hashable key for an action (already an int).

Return type:

Hashable

Parameters:

action (Any)

hash_observation(observation)[source]

Return a hashable key agreeing with is_equal_observation().

Return type:

Hashable

Parameters:

observation (Any)

heading(state)[source]

Return the heading of state as 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:

Tuple[int, int]

Returns:

One of DIRECTIONS.

Raises:

ValueError – If the body is shorter than two cells, which no reachable state has.

in_grid(cell)[source]

Whether cell is one of the playable cells.

Return type:

bool

Parameters:

cell (Tuple[int, int])

initial_observation_dist()[source]

The pre-step reading, which carries no information.

Return type:

DiscreteDistribution

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 Distribution so callers can reach SnakeInitialStateDistribution.body and SnakeInitialStateDistribution.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.

Return type:

bool

Parameters:
  • observation1 (Any)

  • observation2 (Any)

is_terminal(state)[source]

Whether state is one of the four terminal states.

Return type:

bool

Parameters:

state (ndarray)

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.

Parameters:
  • next_state (ndarray) – The post-transition state.

  • action (int) – Unused.

  • observations (Any) – Candidate readings, or one reading.

Return type:

ndarray

Returns:

(N,) float64 array of log-likelihoods.

reward(state, action, next_state=None)[source]

Score one step: +1 for eating, -1 for dying, 0 otherwise.

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, so next_state is accepted and ignored and reward_requires_next_state stays False.

Parameters:
  • state (ndarray) – The state the step is taken from.

  • action (int) – A SnakeAction value.

  • next_state (Any) – Unused.

Return type:

float

Returns:

The immediate reward.

reward_batch(states, action, next_states=None)[source]

Score one action against a batch of states.

Parameters:
Return type:

ndarray

Returns:

(N,) float64 array agreeing element-wise with reward().

sample_next_state(state, action, n_samples=1)[source]

Move the snake, and respawn the food when it was eaten.

Runs in the C++ _native module. The respawn cell is drawn from that module’s RNG, which _native.set_seed seeds and np.random.seed does not.

Parameters:
  • state (ndarray) – Current state.

  • action (int) – A SnakeAction value.

  • n_samples (int) – How many successor samples to return. Defaults to 1.

Return type:

Any

Returns:

A single float64 state when n_samples == 1, else an (n_samples, state_size) float64 array.

Raises:

ValueError – If the new body leaves no free cell for the food, which cannot happen while target_length fits in the grid.

sample_next_state_batch(states, action)[source]

Move every input snake under one action.

Parameters:
  • states (Any) – (N, state_size) array-like of particles.

  • action (int) – The action shared by every particle.

Return type:

ndarray

Returns:

(N, state_size) float64 array. The dtype matches sample_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 by sample_observation() would make, in the same order, so under one seed of _native.set_seed the 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.

Parameters:
  • state (ndarray) – Current state.

  • action (int) – A SnakeAction value.

Return type:

Tuple[ndarray, Any, float]

Returns:

The successor state, its reading, and the reward of (state, action).

sample_observation(next_state, action, n_samples=1)[source]

Report the body, a possible sighting and a noisy scent.

Runs in the C++ _native module. The detection and scent draws come from that module’s RNG, which _native.set_seed seeds and np.random.seed does not.

Parameters:
  • next_state (ndarray) – The post-transition state.

  • action (int) – Unused; the reading depends on the next state alone.

  • n_samples (int) – How many readings to draw. Defaults to 1.

Return type:

Any

Returns:

One observation tuple when n_samples == 1, else a list of them.

scent_probabilities(head, food)[source]

Probability of each quadrant given the head and the food cell.

Parameters:
Return type:

ndarray

Returns:

(4,) float64 array indexed by SnakeQuadrant. The compatible quadrants share scent_accuracy between 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.randint before the call, not from action_sampler: the native loop cannot call back into Python per step. That is the same law as a uniform action_sampler, which is what the planners that call this pass.

Parameters:
  • state (Any) – State the rollout starts from.

  • action_sampler (Any) – Unused; see above.

  • max_depth (int) – Depth at which the rollout stops.

  • discount_factor (float) – Per-step discount factor.

  • depth (int) – Depth already used by the search tree. Defaults to 0.

Return type:

float

Returns:

The discounted sum of rewards from depth to max_depth or the first terminal state.

snake_length(state)[source]

Return the number of body cells in state.

Return type:

int

Parameters:

state (ndarray)

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_state when 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 from state alone would score that win as a timeout.

Parameters:
  • state (Any) – The state the step was taken from, or the final state on the terminal bookkeeping step.

  • action (Any) – The action taken, or None on the terminal step.

  • next_state (Any) – The realised successor, or None on the terminal step.

Return type:

Dict[str, float]

Returns:

The channels named by SnakeStepChannel. The eat channel reports 0.0 on the terminal step, where no action was taken.

steps_since_food(state)[source]

Return the steps-since-food counter of state.

Return type:

int

Parameters:

state (ndarray)

termination(state)[source]

Return why state is terminal, or RUNNING when 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 -inf unless 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.

Parameters:
  • state (ndarray) – Current state.

  • action (int) – A SnakeAction value.

  • next_states (Any) – Candidate successors.

Return type:

ndarray

Returns:

(N,) float64 array of log-probabilities.

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.

Parameters:
  • state (ndarray) – The state the step is taken from. Must not be terminal.

  • action (int) – A SnakeAction value.

Return type:

Tuple[Tuple[Tuple[int, int], ...], bool, int, SnakeTermination]

Returns:

(new_body, eat, steps_since_food, termination). new_body keeps the head the step moved into even when that cell is off the grid or inside the body, so a renderer can mark where the snake died.

turn(heading, action)[source]

Return the heading after applying action to heading.

Parameters:
  • heading (Tuple[int, int]) – The current heading, one of DIRECTIONS.

  • action (int) – A SnakeAction value.

Return type:

Tuple[int, int]

Returns:

The new heading.

Raises:

ValueError – If heading is not an axis step or action is not one of the three actions.

window_cells(head)[source]

Return the in-grid cells within the vision window around head.

Return type:

Tuple[Tuple[int, int], ...]

Parameters:

head (Tuple[int, int])

See also