Defensive Coding: Validate and Harden a Snake Game
Data Structure DesignModel answerLast updated
Design an input-validation strategy, error-handling policy, and test suite to protect a Snake game implementation from every class of bad input.
Defensive Coding: Validate and Harden a Snake Game
You have just finished implementing a Snake game with the following interface:
SnakeGame(width, height, food) # constructs the game
move(direction) -> int # returns current score, or -1 on game over
The grid is width × height. The snake starts at (0, 0). The food list contains [row, col] positions that appear one at a time. move accepts a cardinal direction ("U", "D", "L", "R") and returns the current score, or -1 when the snake goes out of bounds or collides with itself.
Now think adversarially about your own code.
Your task:
- Identify every category of input or runtime scenario that could cause your implementation to produce a wrong answer, crash, or silently corrupt state.
- Propose a clear input-validation strategy and error-handling policy that distinguishes programmer/caller errors from legitimate game outcomes.
- List the subtle rule-ordering bugs that appear in otherwise-correct implementations.
- Provide a complete, working implementation with all defenses in place.
- Write a representative unit test suite covering each breaking category.
- Discuss the trade-offs between thorough defensive checks and runtime performance.
A strong answer explains why each check is placed where it is, not just what to check.
Hints
Hint 1
Separate concerns: inputs the caller controls (width, height, food, direction) are fundamentally different from game outcomes (wall hit, self-collision). These two categories deserve different handling mechanisms — don't conflate them.
Hint 2
The most common correctness bug has nothing to do with validation: it's the order in which you update the occupied set when the snake moves. Think carefully about whether the tail should be removed before or after you check for self-collision, and why eating changes that order.
Hint 3
Validate expensive things once at construction time so the hot path stays O(1). A move is called potentially thousands of times; a constructor is called once. Put the heavy lifting where it costs least.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that "bad input" and "game over" are not the same thing. Mixing them up leads to either swallowed bugs or misleading error messages. The solution is a two-layer contract:
- Contract violations (wrong types, out-of-bounds food coordinates, unknown directions) are programmer errors. Raise an exception immediately with a message that names the offending value.
- Game outcomes (hitting a wall, biting yourself) are expected states the game rules define. Return
-1and keep returning-1on all subsequent calls — game over is sticky and side-effect-free.
Input categories and policies
Construction-time (width, height, food)
Validate once, thoroughly, before any state is allocated. A non-positive dimension, a wrong type, a food coordinate outside the grid, or a malformed food entry all raise immediately. The one edge case worth calling out: if the first food item sits on (0, 0) — where the snake already is — the behavior is ambiguous (was it eaten instantly?). Reject it with ValueError rather than silently picking a side.
food=None is treated as an empty list if your documentation says so; otherwise raise TypeError. Pick one and document it.
Per-call (direction)
An unknown direction string is a caller error, so raise ValueError. This also handles None for free because None is not in the valid-directions map.
Integer overflow (Java / C++)
In Python there is no issue. In statically typed languages, if you encode a cell as row * width + col, the product can exceed 32-bit range on large grids. Use long or store coordinates as a tuple/pair rather than a single integer.
Subtle rule-ordering bug
This is where most "working" implementations are actually broken. The correct sequence inside move is:
- Compute the new head position.
- Check bounds — return
-1if out of range. - If not eating, remove the tail from the occupied set.
- Check whether the new head is already in the occupied set — return
-1on collision. - Add the new head.
If you remove the tail after checking self-collision (steps 4 and 3 swapped), a snake chasing its own tail is wrongly killed. If you remove the tail after adding the head (steps 5 and 3 swapped), you corrupt the set. The eating branch skips tail removal entirely because the snake grows.
Complexity
- Construction: O(F) time and space to validate F food items.
move: O(1) amortized — deque append/pop and hash-set lookup are all constant.- Validation overhead per move: O(1), a single dict lookup for the direction.
Implementation
from collections import deque
from typing import List, Optional
class SnakeGame:
_DIRS = {"U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1)}
def __init__(self, width: int, height: int, food: Optional[List[List[int]]]):
# Validate dimensions
for name, val in (("width", width), ("height", height)):
if not isinstance(val, int) or isinstance(val, bool):
raise TypeError(f"{name} must be an int, got {type(val).__name__!r}")
if val <= 0:
raise ValueError(f"{name} must be positive, got {val}")
# Normalise food
if food is None:
food = []
if not isinstance(food, (list, tuple)):
raise TypeError("food must be a list of [row, col] pairs")
self.width, self.height = width, height
self._food: List[tuple] = []
for i, item in enumerate(food):
if not isinstance(item, (list, tuple)) or len(item) != 2:
raise ValueError(
f"food[{i}] must be a two-element [row, col] pair, got {item!r}"
)
r, c = item
if not all(isinstance(x, int) and not isinstance(x, bool) for x in (r, c)):
raise TypeError(
f"food[{i}] coordinates must be ints, got {item!r}"
)
if not (0 <= r < height and 0 <= c < width):
raise ValueError(
f"food[{i}]={item!r} is outside the {width}x{height} grid"
)
self._food.append((r, c))
if self._food and self._food[0] == (0, 0):
raise ValueError(
"first food item cannot coincide with the snake's starting cell (0, 0)"
)
# Game state
self._body: deque = deque([(0, 0)]) # tail at left, head at right
self._occupied: set = {(0, 0)}
self._food_idx = 0
self._score = 0
self._over = False
def move(self, direction: str) -> int:
if direction not in self._DIRS:
raise ValueError(
f"direction must be one of {set(self._DIRS)!r}, got {direction!r}"
)
if self._over:
return -1
dr, dc = self._DIRS[direction]
hr, hc = self._body[-1]
nr, nc = hr + dr, hc + dc
# Bounds check
if not (0 <= nr < self.height and 0 <= nc < self.width):
self._over = True
return -1
eating = (
self._food_idx < len(self._food)
and self._food[self._food_idx] == (nr, nc)
)
if eating:
self._food_idx += 1
self._score += 1
else:
# Tail vacates before we test for self-collision
self._occupied.discard(self._body.popleft())
# Self-collision check
if (nr, nc) in self._occupied:
self._over = True
return -1
self._body.append((nr, nc))
self._occupied.add((nr, nc))
return self._score
def _assert_invariants(self) -> None:
"""Debug / test helper — O(L), never call in production hot path."""
assert len(self._body) == len(self._occupied) == self._score + 1, \
"body deque and occupied set are out of sync"
assert set(self._body) == self._occupied, \
"occupied set does not mirror body deque"
assert all(
0 <= r < self.height and 0 <= c < self.width
for r, c in self._body
), "body contains out-of-bounds cell"
Unit tests
import pytest
from snake_game import SnakeGame
# --- Construction errors ---
@pytest.mark.parametrize("w,h,food,exc", [
(0, 3, [], ValueError), # zero width
(3, -1, [], ValueError), # negative height
("3", 3, [], TypeError), # string dimension
(True, 3, [], TypeError), # bool masquerading as int
(3, 3, [[1]], ValueError), # food item too short
(3, 3, [[1, 2, 3]], ValueError), # food item too long
(3, 3, [[1.5, 2]], TypeError), # float coordinate
(3, 3, [[3, 0]], ValueError), # row equals height (out of bounds)
(3, 3, [[-1, 0]], ValueError), # negative row
(3, 3, [[0, 0]], ValueError), # first food on start cell
(3, 3, "oops", TypeError), # food is a string
])
def test_construction_errors(w, h, food, exc):
with pytest.raises(exc):
SnakeGame(w, h, food)
def test_none_food_is_accepted():
g = SnakeGame(3, 3, None)
assert g.move("R") == 0 # no food, score stays 0
# --- Direction validation ---
@pytest.mark.parametrize("bad", ["X", "up", "u", "", None, 42])
def test_invalid_direction(bad):
g = SnakeGame(3, 3, [])
with pytest.raises((ValueError, TypeError)):
g.move(bad)
# --- Game-over is sticky ---
def test_game_over_is_idempotent():
g = SnakeGame(1, 1, []) # 1x1 grid: any move is out of bounds
assert g.move("R") == -1
assert g.move("U") == -1 # no exception, no state change
# --- Tail-chase correctness ---
def test_snake_can_follow_its_own_tail():
# 3x1 grid, food at (0,2): snake grows to length 3 filling the row,
# then turns and the new head enters the cell the tail just vacated.
g = SnakeGame(3, 1, [[0, 1], [0, 2]])
assert g.move("R") == 1 # eat food at (0,1), length 2
assert g.move("R") == 2 # eat food at (0,2), length 3, fills row
# No move is possible without collision on a 3x1 grid at this point;
# confirm game-over behaviour rather than a crash.
assert g.move("R") == -1
# --- Invariant checks ---
def test_invariants_hold_through_play():
g = SnakeGame(5, 5, [[0, 1], [1, 1], [2, 1]])
for direction in ["R", "D", "D", "L", "U"]:
result = g.move(direction)
if result != -1:
g._assert_invariants()
Trade-offs: defensive checks vs. performance
Thorough validation at construction costs O(F) but runs once. Every move call benefits from that upfront work because the hot path only does constant-time lookups with no type checking.
The only runtime check per move is a single dict lookup for the direction — negligible. Bounds checking and set lookups are also O(1) and unavoidable for correctness.
Where you would pull back on defensiveness is in a trusted internal API called exclusively by your own validated code. Public-facing constructors and any method accepting external input should always validate; internal helpers can skip redundant re-checks for speed.
The invariant assertion method (_assert_invariants) is the right pattern for production: it exists and can be enabled in tests or debug builds, but is never called in the production hot path.