Designing the Snake Game
Difficulty: Beginner Patterns: Strategy, State, Factory Asked at: Amazon, Google, PhonePe, Microsoft
Snake looks like the easiest problem on the list, and it is the one where most candidates write an O(n) game loop without noticing. The rules fit in four sentences: the snake is a sequence of cells, it steps one cell per tick in its current direction, it grows when its head lands on food, and it dies against a wall or against itself. Every one of those sentences is easy. The trap is in how you store the body.
Keep the body in a List and the obvious implementation shifts every segment forward each tick, then scans that same list to ask whether the head hit the body – O(n) twice per tick, on the one piece of work that happens sixty times a second. The body is a queue, not a list. Push the new head, pop the tail, and keep a parallel HashSet of the cells the snake occupies so that self-collision is one contains call. A tick becomes a fixed handful of operations whatever the snake’s length.
Then comes the detail that separates a working Snake from a Snake that kills the player for no reason: the cell the tail is leaving this tick is legal to enter. The departing segment is not something you can bite. Free the tail before you test the head, or a snake moving in a tight loop dies on its own vacating tail.
The second hard part is food. “Pick a random cell, retry if it is inside the snake” is three lines and it is perfectly fine on an empty board. On a board the snake has filled to 99% it is a loop with a finite average and no worst-case bound. Interviewers ask about it because the fix – hold the set of free cells and pick from that – is the moment you stop treating the board as a passive grid and start treating it as an index.
💡 A tick = one step of the simulated world. Nothing in this design decides when the next tick happens; the caller does, which is why the whole game is testable without waiting. Learn more →
💡 Amortised O(1) = each operation is constant time once you average over a run. ArrayDeque occasionally doubles its backing array, and spreading that one copy across the pushes that follow leaves the per-push cost constant. Learn more →
💡 Rejection sampling = draw at random, throw the draw away if it is not allowed, and draw again. Correct and uniform; the cost is that the number of draws depends on how often you reject.
Functional Requirements
- The snake moves one cell per tick in its current direction, with no input required to keep it moving.
- A direction change takes effect on the next tick, and a 180-degree reversal is rejected rather than accepted and then punished.
- The snake grows by one segment when its head lands on food: the head advances and the tail stays put for that tick.
- Food sits on exactly one cell at a time, chosen uniformly among the cells the snake does not occupy.
- Death on a wall or on the snake’s own body, after which the game accepts nothing.
- Score accumulates as food is eaten, under a rule that can be swapped without touching the loop.
- Win when the snake occupies every cell on the board.
Non-Functional Requirements
- O(1) amortised work per tick – the cost of a move must not grow with the snake’s length, and that includes the self-collision test.
- Food spawning with no retry loop – picking a free cell must cost the same on an empty board as on a board that is one cell from full.
- Deterministic and testable – time and randomness arrive through the constructor: the caller drives
tick()and hands in a seededRandom, so the tight-loop case and the win are assertions rather than a wait. - No corrupt state on a rejected input – a rejected turn leaves the committed direction untouched, and a fatal move leaves the body intact so the final frame still renders.
💡 The third requirement is the whole testing argument in one line: a class that calls Thread.sleep or new Random() internally has reached for a dependency instead of receiving one, and the branches that depend on it become unreachable from a test. Learn more →
Core Entities
| Entity | Description |
|---|---|
Cell |
One grid square as an immutable (row, col) value object – and the hash key everything else is built on |
Direction |
One of four unit steps; knows its own delta and whether another direction is its opposite |
Snake |
The body as a deque of cells plus a set of the same cells; the only class allowed to mutate either |
Board |
Bounds, plus the free-cell index that makes food spawning O(1) |
FoodSpawner |
The policy deciding where the next piece of food appears |
ScoringStrategy |
Turns one eaten piece of food into points |
GameState |
Enum: RUNNING, WON, LOST |
Game |
The orchestrator: the pending direction, the tick, collision resolution, and the win condition |
💡 Value object = a small type defined entirely by its contents rather than its identity, frozen at construction and compared field by field. Cell must be one, because it is a HashSet key: a cell whose row could change after insertion would hash to one bucket and then be looked up in another. Learn more →
💡 Occupancy set = a second, unordered view of exactly the cells already held in the body deque. It stores no new information; it exists purely so membership is a hash lookup instead of a walk.
Push the head, pop the tail, and free the tail first
Start with the version almost everyone writes first. The body is a List<Cell>, index 0 is the head, and a move does this:
- Compute the new head.
- Walk the list checking
list.contains(newHead)to detect a self-collision. - Insert the new head at index 0 and remove the last element, shifting everything.
Step 2 is O(n) and step 3 is O(n). For a snake of 30 segments nobody notices, which is why this survives into the finished program. Now take the sizes the game itself permits: a snake that has filled a 100x100 board is 10,000 segments, so at sixty ticks a second that implementation shifts 600,000 array slots a second to move the snake and scans up to another 600,000 to ask whether it hit itself. The deque version does about a dozen operations per tick at any length. The difference is not a constant factor you can ignore; at the lengths a good player reaches, the body bookkeeping is the game loop.
The fix is to stop treating the body as a list and notice what it really is. The snake only ever changes at its two ends: a cell appears at the head and a cell disappears at the tail. That is a deque. And membership – “is this cell part of me?” – has nothing to do with order, so it belongs in a hash set holding exactly the same cells. Two structures, one invariant: every mutation touches both, in step, and never one without the other.
| Operation | List<Cell> body |
ArrayDeque<Cell> plus HashSet<Cell> |
|---|---|---|
| Advance one cell | O(n) shift | O(1) amortised: one addFirst, one pollLast |
| Self-collision test | O(n) scan | O(1): one contains |
| Grow by one | O(n) shift | O(1): skip the pollLast |
| Per tick, total | O(n) | O(1) amortised |
Growth is the absence of work. This is worth saying out loud because it is the part that surprises people: the snake does not grow by appending a segment. It grows by not removing the tail. Pushing the head is unconditional; popping the tail is what the grow flag controls. One branch, one structure, no special case.
Now the ordering rule. The move is two operations against the set, and their order is load-bearing:
WRONG RIGHT
1. test newHead against the set 1. pop the tail and remove it from the set
2. pop the tail, remove from set 2. test newHead against the set
3. push newHead, add to set 3. push newHead, add to set
Picture a snake curled into a 2x2 loop: head at (2,1), then (2,2), (1,2), and the tail at (1,1). It is moving left, and the player turns it up. The new head is (1,1) – the exact cell the tail occupies right now. Is that a self-collision?
No. By the end of this tick the tail has moved on and (1,1) holds nothing but the new head. The segment is leaving, and you cannot bite a segment that is leaving. Test the head first and the set still contains (1,1), so the snake dies in the middle of a perfectly legal turn. A player going in circles – which is how you survive at length 200 – dies at random, and the bug reproduces only at the one length where the body closes a loop. Free the tail first and the set no longer contains (1,1) when the head is tested, so the move is allowed, which is what the arcade original does.
The one exception is the grow tick. If the head is landing on food the tail does not move, so there is nothing to free and the head is tested against the full body. That falls out of the same code: grow skips step 1, and step 2 then sees every segment including the tail.
The same ordering reappears one layer up, in the board’s free-cell index. When the head enters the cell the tail just left, the board is told to release that cell and to occupy it in the same tick. Release first, then occupy, or the cell ends up marked free while the head is standing on it – and the next piece of food spawns under the snake’s own head.
The second hard part: food that must not spawn inside the snake. The three-line version is rejection sampling:
do { c = randomCell(); } while (snake.occupies(c));
It is uniform and it is correct. The problem is the number of draws. If a fraction p of the board is free, each draw succeeds with probability p, so the expected number of draws is 1/p: one on an empty board, ten at 90% full, a hundred at 99% full, and 10,000 with a single free cell left on a 100x100 board. The chance of still failing after k draws is (1-p)^k, which shrinks but never reaches zero. So the loop has a finite expectation and no worst-case bound at all, on the happy path, on exactly the board states a good player creates. “It terminates with probability 1” is not a latency guarantee.
The fix is to make free cells explicit. Keep every cell id in one array, with the free ones in the first freeCount slots and the occupied ones after, plus a reverse map from cell id to its slot. Occupying a cell swaps it with the last free slot and decrements the boundary; releasing it swaps it to the boundary and increments. Both are one swap. Spawning food is then a single nextInt(freeCount) and an array read: uniform, with exactly one draw, at any fill level. The cost is two int arrays sized to the board and the discipline of telling the board every time a cell changes hands.
There is a middle option worth naming: pick an index k in [0, freeCount) and walk the grid for the k-th free cell. O(rows x cols) per spawn, but hard-bounded and needing no extra structure, which is reasonable if spawns are rare. The interview answer is the whole ladder: rejection sampling is what you would write in the first five minutes, the swap-to-boundary index is what you would ship, and you say why.
classDiagram
class Cell {
+int row
+int col
}
class Direction {
<<enumeration>>
+step(Cell from) Cell
+isOpposite(Direction other) boolean
}
class Snake {
-Deque~Cell~ body
-Set~Cell~ occupied
+move(Direction dir, boolean grow) boolean
+occupies(Cell c) boolean
+nextHead(Direction dir) Cell
+head() Cell
+tail() Cell
+length() int
}
class Board {
-int rows
-int cols
-Array~int~ freeAt
-Array~int~ slotOf
-int freeCount
+isWall(Cell c) boolean
+isFree(Cell c) boolean
+occupy(Cell c) void
+release(Cell c) void
+spawnFood(Random rng) Cell
}
class FoodSpawner {
<<interface>>
+next(Board b, Random rng) Cell
}
class UniformSpawner {
+next(Board b, Random rng) Cell
}
class ScriptedSpawner {
-Deque~Cell~ script
+next(Board b, Random rng) Cell
}
class ScoringStrategy {
<<interface>>
+pointsFor(int length, int eaten) int
}
class Game {
-Direction direction
-Direction pending
-Cell food
-GameState state
-int score
+turn(Direction d) boolean
+tick() GameState
}
FoodSpawner <|.. UniformSpawner
FoodSpawner <|.. ScriptedSpawner
Game --> Board
Game --> Snake
Game --> FoodSpawner
Game --> ScoringStrategy
Game --> Direction
Snake --> Cell
Board --> Cell
💡 In a class diagram the dashed hollow-headed arrow means “implements this interface” and the plain arrow means “holds a reference to this class”. Learn more →
Key classes:
Cell– an immutable(row, col)pair with value equality. It exists as a type rather than two looseints because it is the key in the occupancy set and the free-cell index, and becausesnake.occupies(cell)reads like the question it answers. Make it mutable and the set silently stops working.Direction– the four unit steps, each carrying its own(dRow, dCol)delta.step(cell)returns a new cell andisOpposite(other)is computed from the deltas rather than a hand-written lookup table, so a diagonal variant needs no new branch.Snake– owns the deque and the set, and is the only class that can change either. Itsmove(dir, grow)is where the ordering rule lives: pop the tail, remove it from the set, then test the new head. Nothing outside this class can get the order wrong, because nothing outside it can touch the structures.Board– bounds checking plus the free-cell index. It knows which cells are taken but nothing about why, which is what lets it answer “give me a free cell” in O(1) without ever looking at the snake.FoodSpawner– one method: where does the next food go. The uniform implementation delegates to the board; a scripted implementation makes the win path a test instead of a wait.ScoringStrategy– one method mapping the snake’s length and the food count to points. Pure, so no scoring rule can corrupt game state.Game– the orchestrator and the only mutable state outsideSnake: the committed direction, the one-slot pending direction, the food cell, the state and the score. It is also the only class that knows a tick is a sequence: commit the turn, check the wall, move, update the board, score, respawn.
Design Patterns
| Pattern | Where | Why |
|---|---|---|
| Strategy | ScoringStrategy, FoodSpawner |
Flat points or length-multiplied points, uniform food or a scripted sequence – each is a new class, and tick() never changes |
| State | GameState guards the top of tick() |
A dead or won game refuses to advance, so the loop cannot be driven past its ending |
| Factory | Board presets | “Classic 20x20” or “tight 2x2” assembled in one place instead of at every call site |
| Command (extension) | Each accepted turn as an object | A recorded list of turns plus the seed reproduces a run exactly, which gives replay and undo |
| Observer (extension) | Score display, sound, high-score table | The game loop should not know a UI exists; it announces that food was eaten and the listeners decide what that means |
💡 Strategy pattern = put each version of an algorithm behind one shared interface so the caller can swap it. Game only ever calls pointsFor(...) and next(...), so “longer snake, more points per apple” is a class you add, not a branch you insert into the tick.
💡 State pattern = let the object’s current state decide which operations are legal. Snake uses the lightweight form: a GameState enum checked at the top of tick() and inside turn(), which is the enum-based state machine version of the same idea. The states here carry no behaviour of their own, so full State classes would be over-engineering.
💡 Factory pattern = move assembly into one place that knows how the pieces fit, so callers ask for “a classic board” rather than wiring a board, a snake, a spawner and a scorer themselves. It is also where obstacles would be stamped onto the board.
💡 Command pattern = wrap “do this action” in an object carrying its own data. Here the action is tiny, a direction and a tick number, which is why replay is cheap: the body is derived state, so the turn list plus the seed is the whole save file.
💡 Observer pattern = let interested parties subscribe to events instead of being called by name. Game firing “food eaten” and “died” makes the score label, the sound effect and the analytics counter three listeners rather than three fields on Game.
Data Structures
| Component | Structure | Why |
|---|---|---|
| Snake body | ArrayDeque<Cell>, head at the front |
Push the head and pop the tail in O(1) amortised; a List shifts every segment |
| Occupancy | HashSet<Cell> holding the same cells |
The self-collision test is one contains rather than an O(n) walk |
| Free cells | int[] freeAt plus int[] slotOf and a freeCount boundary |
A uniform food pick in one draw, and occupy or release is one swap |
| Pending turn | a single nullable Direction field |
At most one turn can apply per tick, and the newest valid input wins |
| Score | int score plus an int foodEaten counter |
The scorer is pure, so there is nothing to recompute and no history to keep |
The consequential choice is the pair, not either half. A deque gives order and O(1) ends but O(n) membership; a hash set gives O(1) membership and no order. Snake needs both, so it keeps both, and pays for it with an invariant: the set contains exactly the cells in the deque, always. That invariant is why Snake owns both fields privately and exposes move, occupies, head, tail and length instead of the structures themselves. Hand the deque out and some caller will eventually pop it directly, the set will disagree, and the snake will start passing through a segment that is still on screen.
💡 This “two views of one collection” shape is the same trick as an LRU cache, which pairs a HashMap for lookup with a doubly linked list for order, and for the same reason: no single standard structure gives O(1) membership and O(1) ordered ends at once. Learn more →
💡 ArrayDeque is the right deque in Java, not LinkedList: one contiguous array with two cursors, so both ends are O(1) amortised with no allocation per segment.
Complete Code
Core Models (Cell, Direction, GameState)
Three small types that carry the whole vocabulary. Cell is immutable because it is a hash key; Direction owns its delta so geometry lives in one place; GameState makes an impossible game state impossible to write down.
package snake.model;
/**
* One grid square. A record gives value equality and a matching hashCode for free,
* and the fields are final, so a Cell cannot drift after it is put in a HashSet.
*/
public record Cell(int row, int col) {
@Override public String toString() { return "(" + row + "," + col + ")"; }
}
package snake.model;
public enum Direction {
UP(-1, 0), DOWN(1, 0), LEFT(0, -1), RIGHT(0, 1);
private final int dRow;
private final int dCol;
Direction(int dRow, int dCol) {
this.dRow = dRow;
this.dCol = dCol;
}
/** The cell one step this way. Pure: it never mutates `from`. */
public Cell step(Cell from) {
return new Cell(from.row() + dRow, from.col() + dCol);
}
/**
* Derived from the deltas rather than a hand-written table of pairs, so adding
* diagonals later needs no new cases: opposite means the two steps cancel.
*/
public boolean isOpposite(Direction other) {
return dRow + other.dRow == 0 && dCol + other.dCol == 0;
}
}
package snake.model;
public enum GameState { RUNNING, WON, LOST }
from dataclasses import dataclass
from enum import Enum
# frozen=True is the whole point: it generates __hash__ alongside __eq__ and blocks
# attribute assignment. A plain @dataclass is unhashable and cannot enter a set at all,
# and one with eq=True, frozen=False would hash by value while still being mutable,
# which is the silent version of the same bug.
@dataclass(frozen=True)
class Cell:
row: int
col: int
def __str__(self) -> str:
return f"({self.row},{self.col})"
class Direction(Enum):
UP = (-1, 0)
DOWN = (1, 0)
LEFT = (0, -1)
RIGHT = (0, 1)
@property
def d_row(self) -> int:
return self.value[0]
@property
def d_col(self) -> int:
return self.value[1]
def step(self, frm: Cell) -> Cell:
return Cell(frm.row + self.d_row, frm.col + self.d_col)
def is_opposite(self, other: "Direction") -> bool:
return self.d_row + other.d_row == 0 and self.d_col + other.d_col == 0
class GameState(Enum):
RUNNING = "RUNNING"
WON = "WON"
LOST = "LOST"
#pragma once
#include <cstddef>
#include <functional>
struct Cell {
int row = 0;
int col = 0;
bool operator==(const Cell& o) const { return row == o.row && col == o.col; }
};
// The genuinely different part: std::unordered_set has no hash for a user type, so
// the hash is a design decision here rather than something the language hands you.
// Packing the two axes into one size_t collides for nothing that fits a real board.
namespace std {
template<>
struct hash<Cell> {
size_t operator()(const Cell& c) const noexcept {
size_t r = static_cast<unsigned>(c.row);
size_t k = static_cast<unsigned>(c.col);
return (r << 32) ^ k;
}
};
}
enum class Direction { Up, Down, Left, Right };
// Free functions keep Direction a plain enum class, with the deltas in one place and
// indexed by the enumerator so the two tables cannot drift out of order.
inline int dRow(Direction d) {
static const int v[] = { -1, 1, 0, 0 };
return v[static_cast<int>(d)];
}
inline int dCol(Direction d) {
static const int v[] = { 0, 0, -1, 1 };
return v[static_cast<int>(d)];
}
inline Cell step(Direction d, const Cell& from) {
Cell next; // assigned rather than brace-initialised, so the
next.row = from.row + dRow(d); // call sites never nest braces
next.col = from.col + dCol(d);
return next;
}
inline bool isOpposite(Direction a, Direction b) {
return dRow(a) + dRow(b) == 0 && dCol(a) + dCol(b) == 0;
}
enum class GameState { Running, Won, Lost };
// The language difference that decides this whole design in JavaScript: a Set compares
// objects by reference, so set.has(new Cell(1, 1)) is false even with an identical cell
// already inside, and the snake would pass straight through itself. So every Cell
// carries a scalar key and every set in this design stores keys, not objects.
class Cell {
constructor(row, col) {
this.row = row;
this.col = col;
Object.freeze(this); // immutable, like the Java record
}
/** Stable string key. Pack into an int instead if the board width is known. */
key() {
return `${this.row},${this.col}`;
}
toString() {
return `(${this.row},${this.col})`;
}
}
const Direction = Object.freeze({
UP: Object.freeze({ name: "UP", dRow: -1, dCol: 0 }),
DOWN: Object.freeze({ name: "DOWN", dRow: 1, dCol: 0 }),
LEFT: Object.freeze({ name: "LEFT", dRow: 0, dCol: -1 }),
RIGHT: Object.freeze({ name: "RIGHT", dRow: 0, dCol: 1 }),
});
function step(dir, from) {
return new Cell(from.row + dir.dRow, from.col + dir.dCol);
}
function isOpposite(a, b) {
return a.dRow + b.dRow === 0 && a.dCol + b.dCol === 0;
}
const GameState = Object.freeze({ RUNNING: "RUNNING", WON: "WON", LOST: "LOST" });
Snake.java
The deque and the set, and the one method whose statement order is the point of this page. Nothing outside this class can touch either structure, which is how the ordering rule is enforced rather than merely documented.
package snake.model;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* The body, held twice: a deque for order (head at the front, tail at the back) and a
* set for membership. Two views of the same cells, and every mutation below touches
* both, in step. Neither structure is handed out: a caller that popped the deque
* directly would leave the set describing a snake that no longer exists.
*/
public class Snake {
private final Deque<Cell> body = new ArrayDeque<>();
private final Set<Cell> occupied = new HashSet<>();
public Snake(Cell start) {
this(List.of(start));
}
/** Head first. The set doubles as the duplicate check while loading. */
public Snake(List<Cell> bodyHeadFirst) {
if (bodyHeadFirst.isEmpty())
throw new IllegalArgumentException("a snake needs at least one cell");
for (Cell c : bodyHeadFirst) {
if (!occupied.add(c))
throw new IllegalArgumentException("duplicate cell in body: " + c);
body.addLast(c);
}
}
public Cell head() { return body.peekFirst(); }
public Cell tail() { return body.peekLast(); }
public int length() { return body.size(); }
/** O(1). This single call is the entire self-collision test. */
public boolean occupies(Cell c) { return occupied.contains(c); }
/** Where the head would land. Pure, so the caller can check the wall first. */
public Cell nextHead(Direction dir) { return dir.step(head()); }
/** Head first, read-only, no copy. For rendering and for seeding the board. */
public Iterable<Cell> cells() { return Collections.unmodifiableCollection(body); }
/**
* Advance one cell. THE ORDER OF THESE THREE STEPS IS THE DESIGN:
*
* 1. unless the snake is growing, pop the tail and remove it from the set
* 2. only then test the new head against what is left
* 3. push the new head
*
* Step 1 before step 2 is what makes a tight loop survivable: the cell the tail is
* leaving this same tick is free to enter, because by the end of the tick nothing
* is there. Swap them and a snake curled into a loop dies on its own departing tail.
* On a growing tick there is no step 1, so the head is tested against the whole
* body including the tail, which is correct: the tail is not going anywhere.
*
* Returns false if the snake genuinely bit itself, restoring the body first so the
* caller can render the frame the snake died on.
*/
public boolean move(Direction dir, boolean grow) {
Cell newHead = dir.step(head());
Cell vacated = null;
if (!grow) {
vacated = body.pollLast();
occupied.remove(vacated); // freed BEFORE the test below
}
if (occupied.contains(newHead)) { // a real collision, not a leaving segment
if (vacated != null) { // died intact
body.addLast(vacated);
occupied.add(vacated);
}
return false;
}
body.addFirst(newHead);
occupied.add(newHead);
return true; // growth is the absence of the pollLast
}
}
# Cell and Direction are the frozen dataclass and the enum from the tab above.
from collections import deque
from typing import Optional
class Snake:
"""Body as a deque (left end is the head) plus a set of the same cells."""
def __init__(self, body_head_first: list[Cell]) -> None:
if not body_head_first:
raise ValueError("a snake needs at least one cell")
self._body: deque[Cell] = deque()
self._occupied: set[Cell] = set()
for c in body_head_first:
if c in self._occupied:
raise ValueError(f"duplicate cell in body: {c}")
self._occupied.add(c)
self._body.append(c)
def head(self) -> Cell:
return self._body[0]
def tail(self) -> Cell:
return self._body[-1]
def length(self) -> int:
return len(self._body)
def occupies(self, c: Cell) -> bool:
return c in self._occupied
def next_head(self, d: Direction) -> Cell:
return d.step(self.head())
def cells(self) -> list[Cell]:
return list(self._body)
def move(self, d: Direction, grow: bool) -> bool:
"""Free the tail, THEN test the head, THEN push it. See the Java tab."""
new_head = d.step(self.head())
vacated: Optional[Cell] = None
if not grow:
vacated = self._body.pop() # right end is the tail
self._occupied.discard(vacated) # freed BEFORE the test below
if new_head in self._occupied:
if vacated is not None: # died intact, so the frame still renders
self._body.append(vacated)
self._occupied.add(vacated)
return False
self._body.appendleft(new_head)
self._occupied.add(new_head)
return True
#pragma once
#include <deque>
#include <stdexcept>
#include <unordered_set>
#include "Models.h" // Cell, the std::hash<Cell> specialisation, Direction
// std::deque is O(1) at both ends and std::unordered_set is the hash set; the only
// C++-specific work is owning the hash, which Models.h above already does.
class Snake {
std::deque<Cell> body_; // front is the head
std::unordered_set<Cell> occupied_;
public:
explicit Snake(const std::deque<Cell>& bodyHeadFirst)
: body_(bodyHeadFirst),
occupied_(bodyHeadFirst.begin(), bodyHeadFirst.end()) {
if (body_.empty()) throw std::invalid_argument("a snake needs at least one cell");
if (occupied_.size() != body_.size())
throw std::invalid_argument("duplicate cell in body");
}
const Cell& head() const { return body_.front(); }
const Cell& tail() const { return body_.back(); }
std::size_t length() const { return body_.size(); }
bool occupies(const Cell& c) const { return occupied_.count(c) > 0; }
Cell nextHead(Direction d) const { return step(d, body_.front()); }
const std::deque<Cell>& cells() const { return body_; }
/** Free the tail, THEN test the head, THEN push it. See the Java tab. */
bool move(Direction d, bool grow) {
Cell newHead = step(d, body_.front());
bool popped = false;
Cell vacated;
if (!grow) {
vacated = body_.back();
body_.pop_back();
occupied_.erase(vacated); // freed BEFORE the test below
popped = true;
}
if (occupied_.count(newHead) > 0) {
if (popped) { // died intact
body_.push_back(vacated);
occupied_.insert(vacated);
}
return false;
}
body_.push_front(newHead);
occupied_.insert(newHead);
return true;
}
};
// Two JavaScript-specific problems. (1) An Array is O(n) at one end, since shift and
// unshift move every element, so the body gets an index-keyed deque with two cursors.
// (2) A Set compares objects by reference, so occupancy holds Cell.key() strings.
class CellDeque {
#items = new Map();
#head = 0; // index of the front element
#tail = 0; // one past the back element
pushFront(c) { this.#head -= 1; this.#items.set(this.#head, c); }
pushBack(c) { this.#items.set(this.#tail, c); this.#tail += 1; }
popBack() {
this.#tail -= 1;
const c = this.#items.get(this.#tail);
this.#items.delete(this.#tail);
return c;
}
front() { return this.#items.get(this.#head); }
back() { return this.#items.get(this.#tail - 1); }
get size() { return this.#tail - this.#head; }
*[Symbol.iterator]() {
for (let i = this.#head; i < this.#tail; i++) yield this.#items.get(i);
}
}
class Snake {
#body = new CellDeque();
#occupied = new Set(); // holds keys, never Cell objects
constructor(bodyHeadFirst) {
if (bodyHeadFirst.length === 0) throw new Error("a snake needs at least one cell");
for (const c of bodyHeadFirst) {
if (this.#occupied.has(c.key())) throw new Error(`duplicate cell: ${c}`);
this.#occupied.add(c.key());
this.#body.pushBack(c);
}
}
head() { return this.#body.front(); }
tail() { return this.#body.back(); }
length() { return this.#body.size; }
occupies(c) { return this.#occupied.has(c.key()); }
nextHead(dir) { return step(dir, this.head()); }
cells() { return [...this.#body]; }
/** Free the tail, THEN test the head, THEN push it. See the Java tab. */
move(dir, grow) {
const newHead = step(dir, this.head());
let vacated = null;
if (!grow) {
vacated = this.#body.popBack();
this.#occupied.delete(vacated.key()); // freed BEFORE the test below
}
if (this.#occupied.has(newHead.key())) {
if (vacated !== null) { // died intact
this.#body.pushBack(vacated);
this.#occupied.add(vacated.key());
}
return false;
}
this.#body.pushFront(newHead);
this.#occupied.add(newHead.key());
return true;
}
}
Board.java
Bounds, the free-cell index, and the two spawner implementations that sit on top of it. The board never sees the snake: it is told which cells change hands and answers “give me a free one” in a single draw.
package snake.board;
import snake.model.Cell;
import java.util.Random;
/**
* Bounds plus a free-cell index. Every cell id stays in `freeAt` for the whole game:
* the ids in slots [0, freeCount) are free and the rest are occupied. Occupying a cell
* swaps it to the last free slot and moves the boundary down; releasing it swaps it to
* the boundary and moves the boundary up. Both are one swap, so a uniform pick among
* free cells is one nextInt and one array read at any fill level -- no retry loop.
*/
public class Board {
private final int rows;
private final int cols;
private final int[] freeAt; // slot -> cell id
private final int[] slotOf; // cell id -> slot
private int freeCount;
public Board(int rows, int cols) {
if (rows <= 0 || cols <= 0)
throw new IllegalArgumentException("board must have at least one cell");
this.rows = rows;
this.cols = cols;
int n = rows * cols;
this.freeAt = new int[n];
this.slotOf = new int[n];
for (int i = 0; i < n; i++) {
freeAt[i] = i;
slotOf[i] = i;
}
this.freeCount = n;
}
public int rows() { return rows; }
public int cols() { return cols; }
public int cellCount() { return rows * cols; }
public int freeCount() { return freeCount; }
/** The only definition of "off the board". Obstacles would also answer true here. */
public boolean isWall(Cell c) {
return c.row() < 0 || c.row() >= rows || c.col() < 0 || c.col() >= cols;
}
public boolean isFree(Cell c) {
return !isWall(c) && slotOf[id(c)] < freeCount;
}
/** Mark a cell as taken. Idempotent, and O(1). */
public void occupy(Cell c) {
int cell = id(c);
if (slotOf[cell] >= freeCount) return; // already occupied
swap(slotOf[cell], freeCount - 1);
freeCount--;
}
/** Hand a cell back to the free pool. Idempotent, and O(1). */
public void release(Cell c) {
int cell = id(c);
if (slotOf[cell] < freeCount) return; // already free
swap(slotOf[cell], freeCount);
freeCount++;
}
/**
* A uniformly chosen free cell, or null when the snake fills the board -- which the
* caller reads as a win. Exactly one draw, so a board that is 99% snake costs the
* same as an empty one. The Random arrives from the caller so a run can be replayed.
*/
public Cell spawnFood(Random rng) {
if (freeCount == 0) return null;
return cellAt(freeAt[rng.nextInt(freeCount)]);
}
private void swap(int slotA, int slotB) {
int a = freeAt[slotA];
int b = freeAt[slotB];
freeAt[slotA] = b;
freeAt[slotB] = a;
slotOf[b] = slotA;
slotOf[a] = slotB;
}
/** One guard for every array index in this class. */
private int id(Cell c) {
if (isWall(c)) throw new IllegalArgumentException("cell is off the board: " + c);
return c.row() * cols + c.col();
}
private Cell cellAt(int id) { return new Cell(id / cols, id % cols); }
}
package snake.board;
import snake.model.Cell;
import java.util.Random;
/** Where the next food appears. Swapping the policy does not touch the game loop. */
public interface FoodSpawner {
/** The next food cell, or null when the board has no free cell left. */
Cell next(Board board, Random rng);
}
package snake.board;
import snake.model.Cell;
import java.util.Random;
/** Every free cell equally likely. The default, and one draw per spawn. */
public class UniformSpawner implements FoodSpawner {
@Override
public Cell next(Board board, Random rng) {
return board.spawnFood(rng);
}
}
package snake.board;
import snake.model.Cell;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Random;
/**
* A fixed sequence, then uniform once the script runs out. This is the seam that turns
* the win path into an assertion instead of a wait: the test says where each piece of
* food goes, so the snake cannot wander. Cells that are no longer free are skipped.
*/
public class ScriptedSpawner implements FoodSpawner {
private final Deque<Cell> script;
public ScriptedSpawner(List<Cell> cells) {
this.script = new ArrayDeque<>(cells);
}
@Override
public Cell next(Board board, Random rng) {
while (!script.isEmpty()) {
Cell c = script.pollFirst();
if (board.isFree(c)) return c;
}
return board.spawnFood(rng);
}
}
# The two-array free-cell index is identical to the Java tab, line for line, so only
# the parts Python does differently are shown here: the injected random.Random, the
# Optional return that carries "no free cell", and spawners as closures over their
# state rather than classes implementing an interface.
import random
from collections import deque
from typing import Optional
class Board:
# __init__, is_wall, is_free, occupy, release and _swap are as in the Java tab:
# _free_at[0:_free_count] holds the free cell ids and _slot_of is the reverse map.
def spawn_food(self, rng: random.Random) -> Optional[Cell]:
"""One randrange call whatever the fill level. rng is injected, so
random.Random(42) replays an entire run."""
if self._free_count == 0:
return None
return self._cell_at(self._free_at[rng.randrange(self._free_count)])
def uniform_spawner(board: Board, rng: random.Random) -> Optional[Cell]:
return board.spawn_food(rng)
def scripted_spawner(cells: list[Cell]):
"""Returns a spawner closure: the script first, then uniform."""
pending = deque(cells)
def spawn(board: Board, rng: random.Random) -> Optional[Cell]:
while pending:
c = pending.popleft()
if board.is_free(c):
return c
return board.spawn_food(rng)
return spawn
#pragma once
#include <deque>
#include <functional>
#include <optional>
#include <random>
#include "Snake.h"
// The two-array index is identical to the Java tab. Three things differ in C++ and all
// three are here: std::optional puts "no free cell" in the return type, the random
// source is a seeded std::mt19937 the caller owns, and a one-method interface is a
// std::function rather than a class hierarchy.
std::optional<Cell> Board::spawnFood(std::mt19937& rng) const {
if (freeCount_ == 0) return std::nullopt;
std::uniform_int_distribution<int> pick(0, freeCount_ - 1);
return cellAt(freeAt_[pick(rng)]);
}
using FoodSpawner = std::function<std::optional<Cell>(Board&, std::mt19937&)>;
inline FoodSpawner uniformSpawner() {
return [](Board& b, std::mt19937& r) { return b.spawnFood(r); };
}
// `mutable` is what lets the closure pop its own script, which is the whole of
// ScriptedSpawner in nine lines.
inline FoodSpawner scriptedSpawner(std::deque<Cell> script) {
return [script](Board& b, std::mt19937& r) mutable -> std::optional<Cell> {
while (!script.empty()) {
Cell c = script.front();
script.pop_front();
if (b.isFree(c)) return c;
}
return b.spawnFood(r);
};
}
// The index is identical to the Java tab. What JavaScript forces you to change is the
// random source: Math.random cannot be seeded, so a reproducible demo has to inject a
// generator. Any zero-argument function returning a number in [0, 1) will do -- a tiny
// linear congruential generator in tests, Math.random in production.
function seededRng(seed) {
let s = seed >>> 0;
return () => {
s = (s * 1664525 + 1013904223) >>> 0;
return s / 4294967296;
};
}
class Board {
// The # private fields and isWall, isFree, occupy, release and the swap are as in
// the Java tab. Only the draw differs, because the rng is a function now.
/** One draw from the injected rng, or null when the snake fills the board. */
spawnFood(rng) {
if (this.#freeCount === 0) return null;
const slot = Math.floor(rng() * this.#freeCount);
return this.#cellAt(this.#freeAt[slot]);
}
}
// A spawner is a function, so the two implementations are a one-liner and a closure.
const uniformSpawner = (board, rng) => board.spawnFood(rng);
function scriptedSpawner(cells) {
const pending = [...cells];
return (board, rng) => {
while (pending.length > 0) {
const c = pending.shift();
if (board.isFree(c)) return c;
}
return board.spawnFood(rng);
};
}
ScoringStrategy.java
One method, two implementations, and the interface plus both are shown together because none of them is more than a few lines. The point is that “how many points is an apple worth” is never a branch inside the tick.
package snake.score;
/**
* Points for one eaten piece of food. It reads the snake's size and the running count,
* never its cells, and it is pure -- so no scoring rule can corrupt game state, and a
* new rule needs no test of the game loop.
*/
public interface ScoringStrategy {
int pointsFor(int snakeLength, int foodEaten);
}
package snake.score;
/** Arcade classic: every apple is worth the same. */
public class FlatScorer implements ScoringStrategy {
private final int perFood;
public FlatScorer(int perFood) { this.perFood = perFood; }
@Override
public int pointsFor(int snakeLength, int foodEaten) { return perFood; }
}
package snake.score;
/**
* Pays for the risk of a long snake: the longer you are, the more each apple is worth.
* A length-20 snake has far less room to manoeuvre, so the same apple is worth more.
*/
public class LengthMultiplierScorer implements ScoringStrategy {
private final int base;
public LengthMultiplierScorer(int base) { this.base = base; }
@Override
public int pointsFor(int snakeLength, int foodEaten) { return base * snakeLength; }
}
from typing import Callable
# A one-method interface is a function in Python, so the type alias IS the contract and
# the two implementations are two closures. Reach for typing.Protocol only when the
# strategy grows a second method or needs state the caller can inspect.
ScoringStrategy = Callable[[int, int], int] # (snake_length, food_eaten) -> points
def flat_scorer(per_food: int) -> ScoringStrategy:
return lambda snake_length, food_eaten: per_food
def length_multiplier_scorer(base: int) -> ScoringStrategy:
return lambda snake_length, food_eaten: base * snake_length
#pragma once
#include <functional>
// Same move as the Python tab: one method means std::function, and the two scorers are
// lambdas capturing their configuration by value. A class with a virtual method buys
// nothing here, since nothing ever asks a scorer what kind it is.
using ScoringStrategy = std::function<int(int, int)>; // length, eaten -> points
inline ScoringStrategy flatScorer(int perFood) {
return [perFood](int, int) { return perFood; };
}
inline ScoringStrategy lengthMultiplierScorer(int base) {
return [base](int snakeLength, int) { return base * snakeLength; };
}
// A scorer is (snakeLength, foodEaten) => points. No class, no interface, no registry.
const flatScorer = (perFood) => (snakeLength, foodEaten) => perFood;
const lengthMultiplierScorer = (base) => (snakeLength, foodEaten) => base * snakeLength;
Game.java
The orchestrator. It holds the committed direction, the one-slot pending direction, the food cell and the state, and it is the only class that knows a tick is an ordered sequence of steps. Note what is absent: there is no clock, no sleep and no thread. The caller decides when time passes.
package snake;
import snake.board.Board;
import snake.board.FoodSpawner;
import snake.model.Cell;
import snake.model.Direction;
import snake.model.GameState;
import snake.model.Snake;
import snake.score.ScoringStrategy;
import java.util.Arrays;
import java.util.Random;
public class Game {
private final Board board;
private final Snake snake;
private final FoodSpawner spawner;
private final ScoringStrategy scorer;
private final Random rng;
private Direction direction; // the direction the last move actually used
private Direction pending; // one slot; null means nothing buffered
private Cell food;
private GameState state = GameState.RUNNING;
private int score;
private int foodEaten;
/**
* Everything variable arrives through the constructor: the board, the snake, the
* spawn policy, the scoring rule and the Random. A seeded Random replays a run
* exactly, which is the difference between a test and a session of watching.
*/
public Game(Board board, Snake snake, Direction facing,
FoodSpawner spawner, ScoringStrategy scorer, Random rng) {
this.board = board;
this.snake = snake;
this.direction = facing;
this.spawner = spawner;
this.scorer = scorer;
this.rng = rng;
for (Cell c : snake.cells()) board.occupy(c); // the board learns the body once
this.food = spawner.next(board, rng);
if (food == null) state = GameState.WON; // degenerate: already full
}
/**
* Buffer a turn. Both input rules live here rather than in tick():
*
* - A reversal is rejected. A 180-degree turn puts the head on the neck on the
* very next move, so accepting it and then killing the player is a bug dressed
* as a rule. The guard belongs on the pending direction, not on the move.
*
* - The slot holds one turn, so at most one turn applies per tick. Otherwise two
* keypresses between ticks compose: facing RIGHT, pressing UP and then LEFT
* passes both checks in turn if each is measured against the last keypress, and
* the tick then drives the snake into its own neck.
*
* So validation is always against `direction`, the direction the last move used,
* never against whatever is sitting in the slot. The newest valid input wins.
*/
public boolean turn(Direction d) {
if (state != GameState.RUNNING) return false;
if (d.isOpposite(direction)) return false;
pending = d;
return true;
}
/**
* One step of the world, and the only place game state changes. The caller drives
* this: a UI from a timer, a test from a loop. Nothing here sleeps.
*/
public GameState tick() {
if (state != GameState.RUNNING) return state; // the State guard
if (pending != null) { // commit at most one turn
direction = pending;
pending = null;
}
Cell next = snake.nextHead(direction);
if (board.isWall(next)) { // death 1: the wall
state = GameState.LOST;
return state;
}
boolean grow = next.equals(food);
Cell vacating = grow ? null : snake.tail(); // captured before the move
if (!snake.move(direction, grow)) { // death 2: itself
state = GameState.LOST;
return state;
}
// Release before occupy. In a tight loop `next` IS `vacating`, and the other
// order would leave the cell under the snake's head marked free -- the next
// piece of food would spawn directly under the head. Same ordering rule as
// inside Snake.move, one layer up.
if (vacating != null) board.release(vacating);
board.occupy(next);
if (grow) {
foodEaten++;
score += scorer.pointsFor(snake.length(), foodEaten);
food = spawner.next(board, rng);
if (food == null) state = GameState.WON; // no free cell: snake is board
}
return state;
}
public GameState state() { return state; }
public int score() { return score; }
public int foodEaten() { return foodEaten; }
public int length() { return snake.length(); }
public Cell head() { return snake.head(); }
public Cell tail() { return snake.tail(); }
public Cell food() { return food; }
public Direction facing() { return direction; }
/** The naive pre-move test, exposed so the demo can print what it would have said. */
public boolean snakeOccupies(Cell c) { return snake.occupies(c); }
public void render() {
char[][] frame = new char[board.rows()][board.cols()];
for (char[] row : frame) Arrays.fill(row, '.');
for (Cell c : snake.cells()) frame[c.row()][c.col()] = 'o';
Cell h = snake.head();
frame[h.row()][h.col()] = '@';
if (food != null) frame[food.row()][food.col()] = '*';
for (char[] row : frame) System.out.println(" " + new String(row));
System.out.println(" state=" + state + " length=" + snake.length()
+ " score=" + score + " free=" + board.freeCount());
}
}
# Board, Snake and the scorers are as in the tabs above, and __init__ does what the
# Java constructor does: stores the collaborators, tells the board about the body, and
# takes the first food. In Python the spawner and the scorer are plain callables, so
# there is nothing to implement -- they are parameters. The two methods below are the
# ones worth reading.
from typing import Optional
class Game:
def turn(self, d: Direction) -> bool:
"""Checked against the direction the last move used, never against the slot."""
if self._state is not GameState.RUNNING or d.is_opposite(self._direction):
return False
self._pending = d # one slot; the newest valid input wins
return True
def tick(self) -> GameState:
if self._state is not GameState.RUNNING:
return self._state
if self._pending is not None:
self._direction, self._pending = self._pending, None
nxt = self._snake.next_head(self._direction)
if self._board.is_wall(nxt):
self._state = GameState.LOST
return self._state
grow = nxt == self._food
vacating = None if grow else self._snake.tail()
if not self._snake.move(self._direction, grow):
self._state = GameState.LOST
return self._state
# release before occupy: in a tight loop nxt IS vacating
if vacating is not None:
self._board.release(vacating)
self._board.occupy(nxt)
if grow:
self._food_eaten += 1
self._score += self._scorer(self._snake.length(), self._food_eaten)
self._food = self._spawner(self._board, self._rng)
if self._food is None:
self._state = GameState.WON
return self._state
@property
def state(self) -> GameState:
return self._state
@property
def score(self) -> int:
return self._score
#pragma once
#include <iostream>
#include <optional>
#include <random>
#include <string>
#include <vector>
#include "Board.h"
#include "Scoring.h"
// Ownership is the C++-specific part. Game holds the Board and the Snake by value
// because their lifetime is exactly the game's, and takes the mt19937 by reference
// because the caller owns the seed -- which is what keeps a run reproducible.
class Game {
Board board_;
Snake snake_;
FoodSpawner spawner_;
ScoringStrategy scorer_;
std::mt19937& rng_;
Direction direction_;
std::optional<Direction> pending_; // one slot, in the type
std::optional<Cell> food_;
GameState state_ = GameState::Running;
int score_ = 0;
int foodEaten_ = 0;
public:
Game(Board board, Snake snake, Direction facing,
FoodSpawner spawner, ScoringStrategy scorer, std::mt19937& rng)
: board_(std::move(board)), snake_(std::move(snake)),
spawner_(std::move(spawner)), scorer_(std::move(scorer)),
rng_(rng), direction_(facing) {
for (const Cell& c : snake_.cells()) board_.occupy(c);
food_ = spawner_(board_, rng_);
if (!food_.has_value()) state_ = GameState::Won;
}
/** Validated against direction_, never against pending_. */
bool turn(Direction d) {
if (state_ != GameState::Running) return false;
if (isOpposite(d, direction_)) return false;
pending_ = d;
return true;
}
GameState tick() {
if (state_ != GameState::Running) return state_;
if (pending_.has_value()) {
direction_ = *pending_;
pending_.reset();
}
Cell next = snake_.nextHead(direction_);
if (board_.isWall(next)) {
state_ = GameState::Lost;
return state_;
}
bool grow = food_.has_value() && next == *food_;
std::optional<Cell> vacating;
if (!grow) vacating = snake_.tail();
if (!snake_.move(direction_, grow)) {
state_ = GameState::Lost;
return state_;
}
if (vacating.has_value()) board_.release(*vacating); // release before occupy
board_.occupy(next);
if (grow) {
++foodEaten_;
score_ += scorer_(static_cast<int>(snake_.length()), foodEaten_);
food_ = spawner_(board_, rng_);
if (!food_.has_value()) state_ = GameState::Won;
}
return state_;
}
GameState state() const { return state_; }
int score() const { return score_; }
std::size_t length() const { return snake_.length(); }
const Cell& head() const { return snake_.head(); }
};
// Board, Snake and the scorers are as in the tabs above, and the constructor does what
// the Java one does: store the collaborators in # private fields, call board.occupy on
// every body cell, then take the first food. The spawner and the scorer are plain
// functions here. One line inside tick is genuinely JavaScript-specific -- the food
// comparison goes through key(), because two equal Cell objects are not ===.
class Game {
/** Validated against the committed direction, never against the buffered one. */
turn(dir) {
if (this.#state !== GameState.RUNNING) return false;
if (isOpposite(dir, this.#direction)) return false;
this.#pending = dir;
return true;
}
tick() {
if (this.#state !== GameState.RUNNING) return this.#state;
if (this.#pending !== null) {
this.#direction = this.#pending;
this.#pending = null;
}
const next = this.#snake.nextHead(this.#direction);
if (this.#board.isWall(next)) {
this.#state = GameState.LOST;
return this.#state;
}
const grow = this.#food !== null && next.key() === this.#food.key();
const vacating = grow ? null : this.#snake.tail();
if (!this.#snake.move(this.#direction, grow)) {
this.#state = GameState.LOST;
return this.#state;
}
if (vacating !== null) this.#board.release(vacating); // release before occupy
this.#board.occupy(next);
if (grow) {
this.#foodEaten += 1;
this.#score += this.#scorer(this.#snake.length(), this.#foodEaten);
this.#food = this.#spawner(this.#board, this.#rng);
if (this.#food === null) this.#state = GameState.WON;
}
return this.#state;
}
get state() { return this.#state; }
get score() { return this.#score; }
head() { return this.#snake.head(); }
facing() { return this.#direction; }
}
Demo.java (Runnable end-to-end)
Seven scenarios, each printing the value next to what it should be: a normal step, eating and growing, the tight loop that proves the tail is freed first, a rejected 180-degree turn, a wall death, a real self-collision, and the win. Scenarios 3 and 6 are the same shape of move with opposite outcomes, and the only difference is whether the cell the head enters is the one the tail is leaving.
package snake;
import snake.board.Board;
import snake.board.ScriptedSpawner;
import snake.model.Cell;
import snake.model.Direction;
import snake.model.Snake;
import snake.score.FlatScorer;
import snake.score.LengthMultiplierScorer;
import java.util.List;
import java.util.Random;
public class Demo {
public static void main(String[] args) {
// Seeded, and the demo drives tick() itself. No Thread.sleep anywhere: the
// game does not own the clock, so every scenario below runs instantly and the
// same way every time.
Random rng = new Random(42);
System.out.println("=== 1 and 2. A normal step, then eating and growing (5x5) ===");
Board b1 = new Board(5, 5);
Game g1 = new Game(b1, new Snake(new Cell(2, 2)), Direction.RIGHT,
new ScriptedSpawner(List.of(new Cell(2, 4), new Cell(0, 0))),
new FlatScorer(10), rng);
System.out.println("food at " + g1.food() + " (expected (2,4))");
g1.tick();
System.out.println("after 1 tick -> head " + g1.head() + " length " + g1.length()
+ " score " + g1.score() + " (expected head (2,3) length 1 score 0)");
g1.tick();
System.out.println("after 2 ticks -> head " + g1.head() + " length " + g1.length()
+ " score " + g1.score() + " (expected head (2,4) length 2 score 10)");
System.out.println("the tail did not advance on the eating tick, which is the growth");
g1.render();
System.out.println("\n=== 3. Tight loop: entering the cell the tail is vacating ===");
Board b2 = new Board(5, 5);
Snake loop = new Snake(List.of(
new Cell(2, 1), new Cell(2, 2), new Cell(1, 2), new Cell(1, 1)));
Game g2 = new Game(b2, loop, Direction.LEFT,
new ScriptedSpawner(List.of(new Cell(4, 4))), new FlatScorer(10), rng);
Cell target = Direction.UP.step(g2.head());
System.out.println("head " + g2.head() + " tail " + g2.tail()
+ ", turning UP into " + target + " -- which is the tail cell");
System.out.println("naive test, taken before the move: is " + target
+ " occupied? " + g2.snakeOccupies(target)
+ " (true -- an implementation that tests here kills the snake)");
g2.turn(Direction.UP);
System.out.println("real tick -> " + g2.tick() + " head " + g2.head()
+ " length " + g2.length()
+ " (expected RUNNING head (1,1) length 4)");
g2.render();
System.out.println("\n=== 4. Reversal rejected, and one turn per tick ===");
Board b3 = new Board(5, 5);
Game g3 = new Game(b3, new Snake(List.of(new Cell(2, 2), new Cell(2, 1))),
Direction.RIGHT, new ScriptedSpawner(List.of(new Cell(4, 4))),
new FlatScorer(10), rng);
System.out.println("facing RIGHT, turn(LEFT) accepted? " + g3.turn(Direction.LEFT)
+ " (expected false -- it would bite the neck at (2,1))");
System.out.println("facing RIGHT, turn(UP) accepted? " + g3.turn(Direction.UP)
+ " (expected true -- buffered)");
System.out.println("same tick, turn(LEFT) again? " + g3.turn(Direction.LEFT)
+ " (expected false -- checked against RIGHT, not against the buffered UP)");
g3.tick();
System.out.println("after the tick -> facing " + g3.facing() + " head " + g3.head()
+ " (expected facing UP head (1,2))");
System.out.println("\n=== 5. Wall death ===");
Board b4 = new Board(5, 5);
Game g4 = new Game(b4, new Snake(new Cell(2, 4)), Direction.RIGHT,
new ScriptedSpawner(List.of(new Cell(0, 0))), new FlatScorer(10), rng);
System.out.println("head " + g4.head() + " facing RIGHT on a board 5 columns wide");
System.out.println("tick -> " + g4.tick() + " (expected LOST)");
System.out.println("tick again -> " + g4.tick()
+ " (expected LOST -- the state guard refuses to advance a dead game)");
System.out.println("\n=== 6. Self-collision death ===");
Board b5 = new Board(5, 5);
Snake coiled = new Snake(List.of(
new Cell(1, 1), new Cell(1, 2), new Cell(1, 3), new Cell(2, 3),
new Cell(2, 2), new Cell(2, 1), new Cell(3, 1)));
Game g5 = new Game(b5, coiled, Direction.LEFT,
new ScriptedSpawner(List.of(new Cell(4, 4))), new FlatScorer(10), rng);
System.out.println("head " + g5.head() + " tail " + g5.tail()
+ ", turning DOWN into (2,1) -- a body cell that is NOT the tail");
g5.turn(Direction.DOWN);
System.out.println("tick -> " + g5.tick() + " length " + g5.length()
+ " (expected LOST, body intact at length 7)");
g5.render();
System.out.println("\n=== 7. Win: the snake fills a 2x2 board ===");
Board b6 = new Board(2, 2);
Game g6 = new Game(b6, new Snake(new Cell(0, 0)), Direction.RIGHT,
new ScriptedSpawner(List.of(new Cell(0, 1), new Cell(1, 1), new Cell(1, 0))),
new LengthMultiplierScorer(5), rng);
g6.tick(); // eats (0,1): length 2, plus 5x2
g6.turn(Direction.DOWN);
g6.tick(); // eats (1,1): length 3, plus 5x3
g6.turn(Direction.LEFT);
g6.tick(); // eats (1,0): length 4, plus 5x4
System.out.println("state " + g6.state() + " length " + g6.length()
+ " score " + g6.score() + " free cells " + b6.freeCount()
+ " (expected WON length 4 score 45 free cells 0)");
System.out.println("the scorer was swapped, not edited: 5x2 + 5x3 + 5x4 = 45");
g6.render();
}
}
# Scenarios 1, 4, 5 and 6 are as in the Java tab. These two carry the insight: the
# tight loop, and the win. Note that the demo holds the Snake and the Board directly,
# so it can ask them questions the Game does not need to expose.
import random
def main() -> None:
rng = random.Random(42) # seeded, and the demo drives tick itself
print("=== 3. Tight loop: entering the cell the tail is vacating ===")
loop = Snake([Cell(2, 1), Cell(2, 2), Cell(1, 2), Cell(1, 1)])
g = Game(Board(5, 5), loop, Direction.LEFT,
scripted_spawner([Cell(4, 4)]), flat_scorer(10), rng)
target = Direction.UP.step(loop.head())
print(f"head {loop.head()} tail {loop.tail()}, turning UP into {target}")
print(f"naive test before the move: is {target} occupied? {loop.occupies(target)}"
" (True -- testing here kills the snake)")
print(f"turn accepted? {g.turn(Direction.UP)} (expected True)")
state = g.tick()
print(f"real tick -> {state.name} head {loop.head()} length {loop.length()}"
" (expected RUNNING head (1,1) length 4)")
print("\n=== 7. Win: the snake fills a 2x2 board ===")
board = Board(2, 2)
snake = Snake([Cell(0, 0)])
win = Game(board, snake, Direction.RIGHT,
scripted_spawner([Cell(0, 1), Cell(1, 1), Cell(1, 0)]),
length_multiplier_scorer(5), rng)
win.tick() # eats (0,1): length 2, plus 5x2
win.turn(Direction.DOWN)
win.tick() # eats (1,1): length 3, plus 5x3
win.turn(Direction.LEFT)
win.tick() # eats (1,0): length 4, plus 5x4
print(f"state {win.state.name} length {snake.length()} score {win.score} "
f"free {board.free_count} (expected WON length 4 score 45 free 0)")
if __name__ == "__main__":
main()
#include <deque>
#include <iostream>
#include <optional>
#include <random>
#include "Game.h"
// Scenario 3, the tight loop. The other six are as in the Java tab. A local maker
// function builds cells by assignment rather than brace-initialising them inline,
// which keeps every call site free of nested braces.
static Cell cellAt(int r, int c) {
Cell x;
x.row = r;
x.col = c;
return x;
}
int main() {
std::mt19937 rng(42); // seeded, and main drives tick itself
std::deque<Cell> body;
body.push_back(cellAt(2, 1));
body.push_back(cellAt(2, 2));
body.push_back(cellAt(1, 2));
body.push_back(cellAt(1, 1));
std::deque<Cell> script;
script.push_back(cellAt(4, 4));
auto show = [](const Cell& c) {
return "(" + std::to_string(c.row) + "," + std::to_string(c.col) + ")";
};
Snake probe(body);
Cell target = step(Direction::Up, probe.head());
std::cout << "=== 3. Tight loop: entering the cell the tail is vacating ===\n"
<< "head " << show(probe.head()) << " tail " << show(probe.tail())
<< ", turning UP into " << show(target) << "\n"
<< "naive test before the move: occupied? " << std::boolalpha
<< probe.occupies(target) << " (true -- testing here kills it)\n";
Game game(Board(5, 5), Snake(body), Direction::Left,
scriptedSpawner(script), flatScorer(10), rng);
game.turn(Direction::Up);
GameState s = game.tick();
std::cout << "real tick -> "
<< (s == GameState::Running ? "RUNNING" : "NOT RUNNING")
<< " head " << show(game.head()) << " length " << game.length()
<< " (expected RUNNING head (1,1) length 4)\n";
return 0;
}
// Scenario 4, the input rule. The other six are as in the Java tab. This is the one
// worth isolating in JavaScript, because the keydown handler is exactly where people
// assign to the direction field directly and let two events land between two frames.
const rng = seededRng(42);
const board = new Board(5, 5);
const snake = new Snake([new Cell(2, 2), new Cell(2, 1)]);
const game = new Game(board, snake, Direction.RIGHT,
scriptedSpawner([new Cell(4, 4)]), flatScorer(10), rng);
console.log("=== 4. Reversal rejected, and one turn per tick ===");
console.log(`facing RIGHT, turn(LEFT) accepted? ${game.turn(Direction.LEFT)}`
+ " (expected false -- it would bite the neck at (2,1))");
console.log(`facing RIGHT, turn(UP) accepted? ${game.turn(Direction.UP)}`
+ " (expected true -- buffered)");
console.log(`same tick, turn(LEFT) again? ${game.turn(Direction.LEFT)}`
+ " (expected false -- checked against RIGHT, not against the buffered UP)");
game.tick();
console.log(`after the tick -> facing ${game.facing().name} head ${game.head()}`
+ " (expected facing UP head (1,2))");
Sequence Diagram – One Tick
💡 A sequence diagram reads top to bottom as time passing: each vertical line is one object staying alive, and each horizontal arrow is one call from the object on the left to the object on the right.
sequenceDiagram
participant D as Driver
participant G as Game
participant S as Snake
participant B as Board
participant F as FoodSpawner
D->>G: tick
G->>G: commit the pending direction
G->>S: nextHead for that direction
S-->>G: the cell the head would enter
G->>B: isWall for that cell
B-->>G: false
alt the cell holds the food
G->>S: move with grow
S->>S: push the head and keep the tail
S-->>G: alive
G->>B: occupy the new head
G->>F: next free cell
F-->>G: a cell or nothing left
else an ordinary step
G->>S: move without grow
S->>S: pop the tail and drop it from the set
S->>S: only now test the head against the set
S-->>G: alive or bitten
G->>B: release the tail then occupy the head
end
G-->>D: GameState
The left branch is the eating tick: no tail is freed, so the head is tested against the whole body. The right branch is every other tick, and its two Snake self-calls are the ordering rule. “Nothing left” from the spawner is the win condition: no free cell means the snake is the board.
How to Extend
| Extension | Implementation |
|---|---|
| Obstacles and inner walls | A BoardPreset factory calls board.occupy(...) on each wall cell at construction, so food never spawns on one, and isWall consults the same set |
| Wrap-around edges | A WrapBoard extends Board whose isWall is always false and which maps an off-grid step back onto the grid, plus one line in tick that asks the board to resolve the stepped cell |
| Multiple food items | FoodSpawner is unchanged; Game holds a Map<Cell, Food> instead of one Cell, so the eat test is a map lookup and still O(1) |
| Poison food that shrinks | A Food value carrying a length delta. Snake.move already branches on a grow flag, so it generalises to trimming extra cells off the tail with the same two structures |
| Two snakes on one board | A List<Snake> plus one shared occupancy set, so each snake’s occupies already sees the other. The ordering rule gets harder: two tails vacate in the same tick, and both must be freed before either head is tested |
| Speed that ramps up | A TickPolicy the driver consults for the next delay. The game stays clock-free: it never decides when the next tick happens, only what a tick does |
| Replay and undo | Each accepted turn recorded as a Command with its tick number. The body is derived state, so the turn list plus the seed is the entire save file |
💡 Command pattern = wrap “do this action” in an object carrying its own data. Replaying a Snake run needs only the turns and the seed, because everything else – body, food, score – is recomputed by replaying them, which is event sourcing in miniature.
What Interviewers Look For
- ✅ A deque plus a set, not a list – O(1) amortised per tick on both the move and the self-collision test, instead of O(n) twice
- ✅ The tail is freed before the head is tested – volunteering this unprompted shows you have thought about a snake moving in a loop, which is the only way the bug gets found
- ✅ Growth is the absence of the tail pop – not an append, not a special case, one flag through one branch
- ✅ Food spawning that does not rely on retrying – naming rejection sampling, giving its 1/p expected draws, and then replacing it with the free-cell index
- ✅ The reversal guard sits on the input – rejected when the turn is buffered, not discovered when the move kills the snake
- ✅ One buffered turn per tick, validated against the committed direction – so two keypresses between ticks cannot compose two legal 90-degree turns into a fatal 180
- ✅ An immutable
Cellwith value equality – because it is a hash key, and a mutable key is an entry that cannot be found in the set it is sitting in - ✅ No sleeping inside the game – the caller drives
tick()and hands in a seededRandom, so the tight loop, the two deaths and the win all run as assertions
Related Designs
- Tic-Tac-Toe – the same “maintain an aggregate instead of rescanning” move, applied to win detection rather than to collision detection
- Snake and Ladder – a turn-based loop next to this tick-based one, which is a good way to see what the driver of a game loop actually owns
- Deck of Cards – immutable value objects as hash keys and an injected seeded
Random, both for the same reasons they appear here - Traffic Light Controller – another tick-driven state machine with injected time, where the ordering of transitions is similarly load-bearing
Related Concepts
Scale this design past a single process and these are the concepts it runs into:
- WebSockets vs SSE → – a browser client needs the frame pushed every tick, and at sixty ticks a second the question becomes whether you send the whole board or just the new head cell and the freed tail cell, which is exactly the two-operation model this design already produces
- Idempotency → – once turns arrive over a network, a retried keypress must not turn twice. Give each input the tick it belongs to and the one-slot pending direction becomes naturally idempotent: the second copy overwrites the first instead of queueing behind it
- Performance Metrics → – the per-tick budget is the whole non-functional requirement, and it is also what makes the O(n) body and the retry loop in the spawner visible: both are fine at the median and both blow the budget exactly when the player is doing well
Discussion
Newest first