Build a Fox-and-Geese Turn-Based Grid Game Engine
Data Structure DesignModel answerLast updated
Model the board state, movement rules, and win conditions for an asymmetric two-player grid game where geese try to reach the far side while foxes hunt them.
Background
You are building the core engine for a digital board game called Foxes and Geese, played on an 8 x 8 grid. Two players alternate turns:
- Goose Player (
GOOSE): Starts with 7 geese placed at row7, columns1through7. Geese move first. - Fox Player (
FOX): Starts with 2 foxes placed at row0, columns2and5.
Movement Rules
Geese move exactly one cell in any orthogonal direction (up, down, left, right) into an unoccupied cell. They cannot jump over or capture any piece.
Foxes have two options on their turn:
- Step: Move one cell orthogonally into an empty cell.
- Leap: If a goose occupies an adjacent orthogonal cell and the cell directly beyond it (in the same direction) is empty and within bounds, the fox may jump over the goose and land there. The leaped-over goose is permanently removed from the board. Only one leap is permitted per turn.
Win Conditions
GOOSEwins if any goose reaches row0, or if the foxes have no legal moves at the start of their turn.FOXwins if fewer than 2 geese remain on the board, or if the geese have no legal moves at the start of their turn.
What to Implement
Design the object model and implement the class below. Explain your layering strategy, how move generation and validation share a single code path, how win conditions are evaluated, and what the complexity of each operation is.
class PieceType(Enum):
GOOSE = "GOOSE"
FOX = "FOX"
class Position:
row: int
col: int
class GameStatus(Enum):
IN_PROGRESS = "IN_PROGRESS"
GOOSE_WON = "GOOSE_WON"
FOX_WON = "FOX_WON"
class FoxAndGeeseGame:
def __init__(self):
"""
Set up the 8x8 board with starting positions.
GOOSE moves first.
"""
pass
def get_valid_moves(self, player: PieceType) -> list[tuple[Position, Position]]:
"""
Return all legal (from_pos, to_pos) pairs for the given player
in the current board state.
"""
pass
def make_move(self, from_pos: Position, to_pos: Position) -> GameStatus:
"""
Validate and apply the move for the currently active player.
Raise ValueError if the move is illegal or it is not that player's turn.
Update game status and switch the active player.
Return the resulting GameStatus.
"""
pass
Constraints
- Board coordinates satisfy
0 <= row < 8and0 <= col < 8. - No piece may move outside the board.
make_movemust run inO(1)time relative to board size.get_valid_movesmust run inO(P)time, wherePis the number of active pieces for that player.
Hints
Hint 1
Separate pure piece storage from game logic. A Board class that only handles placement, removal, and lookup makes it much easier to test the rules layer independently.
Hint 2
Generate and validate moves using the same function. One method, _moves_from(pos), produces every legal move for a single piece. make_move validates a requested move simply by checking whether the destination appears in that piece's candidate list. This guarantees the generator and validator can never disagree.
Hint 3
Evaluate win conditions in a fixed order immediately after applying the move: (1) did the moved goose land on row 0? (2) are fewer than 2 geese left? (3) does the opponent have any legal move? Checking stalemate last means you only reach that check when neither piece-count nor goal-row condition was triggered.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Layering
The engine splits into three distinct layers:
- Value types —
Positionis a frozen, hashable dataclass.PieceTypeandGameStatusare enums. Keeping these immutable means they can be stored in sets and used as dict keys safely. - Board — responsible only for storing and retrieving pieces. It maintains a
dict[Position, PieceType]for O(1) cell lookup and adict[PieceType, set[Position]]for O(1) piece enumeration and counting. It has no concept of turns, rules, or win conditions. - Game (rules engine) — owns turn state, generates moves, validates requests, applies moves, and evaluates win conditions.
The most consequential design decision is the single source of truth for legal moves: one method, _moves_from(pos), generates every legal move for one piece and returns a list of internal Move objects (each carrying from_pos, to_pos, and an optional captured cell). make_move validates a request by checking whether the destination appears in that piece's candidate list. Because you never write the rules twice, the generator and validator are structurally incapable of disagreeing — a common bug in naive implementations.
Move Generation
For each of the four orthogonal directions (dr, dc):
- Step (both piece types): the target cell
pos + (dr, dc)is in bounds and empty → legal. - Leap (foxes only): the adjacent cell
mid = pos + (dr, dc)holds aGOOSE, and the landing cellland = pos + (2·dr, 2·dc)is in bounds and empty → legal, withcaptured = mid. Foxes cannot leap over other foxes, and geese never leap.
A single piece has at most eight candidates (four steps, four potential leaps), so _moves_from is O(1). get_valid_moves iterates the player's position set, so it is O(P).
Turn Enforcement and Move Application
make_move rejects the request if:
- the game is already over,
from_posis empty or holds the opponent's piece,to_posdoes not appear in_moves_from(from_pos).
On a valid move, the engine:
- Removes any captured goose (if the move is a leap).
- Moves the piece from source to destination.
- Evaluates win conditions (see below).
- Toggles the active player.
Win Condition Evaluation Order
Conditions are checked in this order immediately after the move is applied:
- Goal row: the moved piece is a goose and
to_pos.row == 0→GOOSE_WON. Only the piece that just moved can newly satisfy this, so the check is O(1). - Piece count:
board.count(GOOSE) < 2→FOX_WON. Reading a set's length is O(1). - Stalemate: the player about to move has no legal moves → the player who just moved wins. This calls
_has_any_move, which short-circuits on the first legal move found and is bounded by the number of pieces (at most 7 + 2 = 9), not by board area.
Ordering matters: a leap that drops geese below 2 must trigger condition 2 before reaching the stalemate check, so a game never enters an unplayable state.
Complexity Summary
| Operation | Time | Notes |
|---|---|---|
_moves_from(pos) | O(1) | At most 8 candidates |
get_valid_moves(player) | O(P) | Iterates the player's position set |
make_move (apply + checks 1–2) | O(1) | Hash lookups and set update |
| Stalemate check | O(P) worst case | Short-circuits; bounded by piece count, not board size |
Space is O(P) — one dict entry and one set entry per piece. No 8×8 array scan ever occurs.
Common Mistakes
- Duplicating rules in the validator: checking legality with different logic than generation causes subtle disagreements (e.g., allowing a step that the generator would never emit). The shared
_moves_frompath eliminates this. - Wrong stalemate attribution: stalemate is "you have no moves on your turn", so it must be checked for the next player after a move completes, not the player who just moved.
- Off-by-one in leap landing: the landed cell is
from + 2·direction, notfrom + 1·direction. Leaping onto the midpoint (the goose's cell) is a common transcription error. - Leaping off the board:
landmust be validated with an in-bounds check independently of the midpoint check. - Calling
make_moveafter game over: should raiseValueErrorimmediately; never mutate state after a terminal status is set. - Checking win conditions before applying the move: the capture must happen first so the piece count is accurate when condition 2 is evaluated.
Python Implementation
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Optional
class PieceType(Enum):
GOOSE = "GOOSE"
FOX = "FOX"
class GameStatus(Enum):
IN_PROGRESS = "IN_PROGRESS"
GOOSE_WON = "GOOSE_WON"
FOX_WON = "FOX_WON"
@dataclass(frozen=True)
class Position:
row: int
col: int
def offset(self, dr: int, dc: int) -> Position:
return Position(self.row + dr, self.col + dc)
def in_bounds(self, size: int) -> bool:
return 0 <= self.row < size and 0 <= self.col < size
@dataclass(frozen=True)
class Move:
from_pos: Position
to_pos: Position
captured: Optional[Position] = None
DIRECTIONS = ((-1, 0), (1, 0), (0, -1), (0, 1))
class Board:
"""Pure piece storage — no rules, no turns."""
def __init__(self, size: int = 8):
self.size = size
self._cells: dict[Position, PieceType] = {}
self._by_type: dict[PieceType, set[Position]] = {t: set() for t in PieceType}
def get(self, pos: Position) -> Optional[PieceType]:
return self._cells.get(pos)
def is_empty(self, pos: Position) -> bool:
return pos.in_bounds(self.size) and pos not in self._cells
def place(self, pos: Position, piece: PieceType) -> None:
self._cells[pos] = piece
self._by_type[piece].add(pos)
def remove(self, pos: Position) -> PieceType:
piece = self._cells.pop(pos)
self._by_type[piece].discard(pos)
return piece
def move_piece(self, src: Position, dst: Position) -> None:
self.place(dst, self.remove(src))
def positions_of(self, piece: PieceType) -> set[Position]:
return self._by_type[piece]
def count(self, piece: PieceType) -> int:
return len(self._by_type[piece])
class FoxAndGeeseGame:
SIZE = 8
def __init__(self):
self.board = Board(self.SIZE)
# Place geese at row 7, columns 1–7
for col in range(1, 8):
self.board.place(Position(7, col), PieceType.GOOSE)
# Place foxes at row 0, columns 2 and 5
for col in (2, 5):
self.board.place(Position(0, col), PieceType.FOX)
self.current: PieceType = PieceType.GOOSE
self.status: GameStatus = GameStatus.IN_PROGRESS
@staticmethod
def _opponent(player: PieceType) -> PieceType:
return PieceType.FOX if player is PieceType.GOOSE else PieceType.GOOSE
def _moves_from(self, pos: Position) -> list[Move]:
"""Generate all legal moves for the piece at pos. O(1) — at most 8 candidates."""
piece = self.board.get(pos)
if piece is None:
return []
moves: list[Move] = []
for dr, dc in DIRECTIONS:
step = pos.offset(dr, dc)
if self.board.is_empty(step):
moves.append(Move(pos, step))
elif piece is PieceType.FOX and self.board.get(step) is PieceType.GOOSE:
land = pos.offset(2 * dr, 2 * dc)
if self.board.is_empty(land):
moves.append(Move(pos, land, captured=step))
return moves
def _all_moves(self, player: PieceType) -> list[Move]:
result: list[Move] = []
for pos in self.board.positions_of(player):
result.extend(self._moves_from(pos))
return result
def _has_any_move(self, player: PieceType) -> bool:
return any(self._moves_from(p) for p in self.board.positions_of(player))
def get_valid_moves(self, player: PieceType) -> list[tuple[Position, Position]]:
if self.status is not GameStatus.IN_PROGRESS:
return []
return [(m.from_pos, m.to_pos) for m in self._all_moves(player)]
def make_move(self, from_pos: Position, to_pos: Position) -> GameStatus:
if self.status is not GameStatus.IN_PROGRESS:
raise ValueError("Game is already over.")
piece = self.board.get(from_pos)
if piece is None:
raise ValueError(f"No piece at {from_pos}.")
if piece is not self.current:
raise ValueError(f"It is {self.current.value}'s turn, not {piece.value}'s.")
# Find matching move in the legal set (validates destination implicitly)
candidate: Optional[Move] = None
for m in self._moves_from(from_pos):
if m.to_pos == to_pos:
candidate = m
break
if candidate is None:
raise ValueError(f"Move from {from_pos} to {to_pos} is not legal.")
# Apply capture first so win checks see the updated piece count
if candidate.captured is not None:
self.board.remove(candidate.captured)
self.board.move_piece(from_pos, to_pos)
# Evaluate win conditions in priority order
if self.current is PieceType.GOOSE and to_pos.row == 0:
self.status = GameStatus.GOOSE_WON
elif self.board.count(PieceType.GOOSE) < 2:
self.status = GameStatus.FOX_WON
else:
opponent = self._opponent(self.current)
if not self._has_any_move(opponent):
# Opponent is stalemated on their turn — current player wins
self.status = (
GameStatus.GOOSE_WON
if self.current is PieceType.GOOSE
else GameStatus.FOX_WON
)
if self.status is GameStatus.IN_PROGRESS:
self.current = self._opponent(self.current)
return self.status