Build a Configurable Disc-Drop Game Engine
Data Structure DesignModel answerLast updated
Design and implement a gravity-based four-in-a-row game engine with a clean API, local win detection, and support for arbitrary board sizes and run lengths.
Disc-Drop Game Engine
A classic two-player game is played on a vertical grid. Players alternate dropping discs into columns; each disc falls to the lowest unoccupied cell in that column. The first player to form an unbroken line of k discs — horizontally, vertically, or diagonally — wins. If every cell is filled with no winner, the game is a draw.
Your task is to implement a reusable engine for this game.
Default configuration
- Board: 6 rows × 7 columns
- Two players, identified as
1and2. Player1moves first. - Winning run length: k = 4
- Row
0is the bottom of the board;row = rows - 1is the top.
The constructor should accept rows, cols, and k as optional parameters so the engine works on any valid board size.
Required API
drop(col, player) → int
Places the current player's disc in column col. Returns the row index where the disc lands.
Raises an InvalidMoveError (or equivalent) — without changing any state — for any of the following:
- The game is already over (won or drawn).
playeris not1or2.- It is not
player's turn. colis out of range or not a valid integer.- The chosen column is already full.
get_status() → (str, player | None)
Returns the current game state as a tuple:
("inProgress", None)— the game is still going("win", player)— that player has formed a run of k("draw", None)— the board is full with no winner
reset()
Restores the board to its initial empty state. Player 1 moves next.
Implementation requirements
Gravity in O(1). You must not scan a column to find the next empty cell. Instead, track the current fill height of each column directly.
Win detection in O(k). After each valid move, check only the four lines passing through the newly placed disc (horizontal, vertical, and both diagonals). Walk outward from the disc in both directions along each line, counting consecutive same-player cells. Do not scan the entire board.
Draw detection. Track the total number of moves made. A draw is declared when no win occurred and the board is completely filled. A move that simultaneously fills the last cell and forms a winning run must be reported as a win, not a draw.
Discussion points
Be ready to address:
- Why does local win detection (from the last move only) always produce a correct result? Argue from invariants.
- Compare a 2D array representation with bitboards: when does each approach pay off?
- What is the time and space complexity of each API method?
- What edge cases should unit tests cover? Write at least five meaningful test cases.
Constraints
1 ≤ rows, cols ≤ 1001 ≤ k ≤ max(rows, cols)- A winning move on the very last empty cell counts as a win.
klarger than every dimension means no win is ever possible; the game will end in a draw if the board fills.
Hints
Hint 1
Track column fill heights in a separate array so the landing row for any drop is a direct lookup — no column scan needed. After placing the disc, increment the height for that column.
Hint 2
For win detection, walk outward from the newly placed cell along each of the four axis directions, counting consecutive same-player cells in both directions. The run through that cell is 1 + cells_forward + cells_backward. Cap each walk at k−1 steps so the total work stays O(k).
Hint 3
To distinguish a winning last move from a draw, always run the win check before checking whether moves == rows * cols. Only declare a draw if the board is full and no win was found.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Contract and design decisions
Nail down the interface before writing a line of code.
- Players are
1and2; player1moves first. dropreturns the row where the disc lands (row0is the bottom).- Any invalid call raises
InvalidMoveErrorand leaves every piece of state — board, turn, status — unchanged. Validate in full before mutating anything. - Once the game ends, all further
dropcalls are rejected untilreset().
Gravity in O(1)
The naive approach scans a column upward to find the first empty cell — that is O(rows) per move. Instead, keep a heights array of length cols. heights[c] is the number of discs already in column c, so it is also the row index where the next disc will land. After placing, increment heights[c]. This makes every placement O(1).
Local win detection in O(k)
A full-board scan after every move is O(rows × cols). You can do much better by exploiting one invariant: before the move just made, no run of length k existed anywhere on the board. Therefore any new run of length k must pass through the newly placed disc. It lies on exactly one of four lines through that cell: horizontal, vertical, diagonal (↗), anti-diagonal (↘).
For each direction, walk in both directions from the new cell while the cells belong to the same player, stopping after at most k−1 steps per side. The run length through the cell is 1 + forward_count + backward_count. If this reaches k, the player wins.
Total cell reads per drop: at most 4 directions × 2 sides × (k−1) steps = 8(k−1), so O(k).
Draw detection
Track moves, a simple counter incremented on every valid placement. If the win check returns false and moves == rows * cols, the board is full — declare a draw. Always check for a win first so a move that fills the last cell and completes a run is recorded as a win.
Validation order
Check in this order, cheapest and most global first:
- Game already over.
playernot in{1, 2}.- Wrong turn.
colis not a plain integer, or is out of[0, cols). Guard against Pythonboolvalues, which are a subclass ofint.- Column is full.
Complexity summary
| Method | Time | Extra space |
|---|---|---|
drop | O(k) | O(1) |
get_status | O(1) | — |
reset | O(rows × cols) | O(rows × cols) for the grid |
2D array vs. bitboards
2D array is the right default for an interview. It is easy to read, generalizes to any M×N×k without changes, and already achieves O(k) win detection. There is nothing to optimize about the logic.
Bitboards encode one player's positions as a single integer bitmask. Using bit-shift distances of 1 (vertical), cols+1 (horizontal), cols and cols+2 (diagonals), a four-in-a-row check reduces to two AND + two shift operations per direction — fast enough for an AI solver running millions of positions per second. The downsides are poor readability, awkward generalization for large boards (you need big integers or multiple machine words), and the cognitive overhead of the column-sentinel bit that prevents runs from wrapping between columns. Reach for bitboards only when building a minimax or alpha-beta solver where copy-and-hash speed matters.
Python implementation
from typing import Optional, Tuple
IN_PROGRESS, WIN, DRAW = "inProgress", "win", "draw"
DIRECTIONS = ((0, 1), (1, 0), (1, 1), (1, -1))
class InvalidMoveError(ValueError):
pass
class DiscDrop:
def __init__(self, rows: int = 6, cols: int = 7, k: int = 4) -> None:
if rows < 1 or cols < 1 or k < 1:
raise ValueError("rows, cols, and k must each be at least 1")
self.rows = rows
self.cols = cols
self.k = k
self.reset()
def reset(self) -> None:
# grid[row][col]; row 0 is the bottom of the board
self.grid: list[list[int]] = [[0] * self.cols for _ in range(self.rows)]
self.heights: list[int] = [0] * self.cols
self.current: int = 1
self.moves: int = 0
self._status: Tuple[str, Optional[int]] = (IN_PROGRESS, None)
def get_status(self) -> Tuple[str, Optional[int]]:
return self._status
def drop(self, col: int, player: int) -> int:
# --- validation (no state mutation until all checks pass) ---
if self._status[0] != IN_PROGRESS:
raise InvalidMoveError("the game is already over")
if player not in (1, 2):
raise InvalidMoveError(f"unrecognised player: {player!r}")
if player != self.current:
raise InvalidMoveError(f"it is not player {player}'s turn")
# reject booleans, which are int subclasses in Python
if isinstance(col, bool) or not isinstance(col, int) or not (0 <= col < self.cols):
raise InvalidMoveError(f"column {col!r} is out of range")
if self.heights[col] == self.rows:
raise InvalidMoveError(f"column {col} is full")
# --- placement ---
row = self.heights[col]
self.grid[row][col] = player
self.heights[col] += 1
self.moves += 1
# --- outcome detection ---
if self._check_win(row, col, player):
self._status = (WIN, player)
elif self.moves == self.rows * self.cols:
self._status = (DRAW, None)
else:
self.current = 3 - player # toggles between 1 and 2
return row
# Walk in direction (dr, dc) from (r, c), counting contiguous same-player cells.
def _count_run(self, r: int, c: int, dr: int, dc: int, player: int) -> int:
count = 0
r, c = r + dr, c + dc
while count < self.k - 1 and 0 <= r < self.rows and 0 <= c < self.cols and self.grid[r][c] == player:
count += 1
r += dr
c += dc
return count
def _check_win(self, r: int, c: int, player: int) -> bool:
for dr, dc in DIRECTIONS:
forward = self._count_run(r, c, dr, dc, player)
backward = self._count_run(r, c, -dr, -dc, player)
if 1 + forward + backward >= self.k:
return True
return False
Edge cases to test
- Column
−1, column equal tocols, afloat, and a PythonTrue/Falsevalue. - Dropping into a column that is completely full.
- The same player calling
droptwice in a row. - Any
dropcall after the game has ended. - A move that fills the board's last empty cell and simultaneously completes a winning run — must report a win, not a draw.
k = 1: the very first move wins.klarger than both dimensions: the game can only end in a draw.- Wins in all four directions (horizontal, vertical, both diagonals).
Common mistakes
- Scanning a column for the empty row instead of tracking heights — costs O(rows) per move and signals unfamiliarity with amortized bookkeeping.
- Full-board win scan after every move — O(rows × cols) and misses the local invariant argument.
- Checking draw before win — a filling last-cell win gets misclassified as a draw.
- Not resetting
currentinsidereset(), leaving the turn order broken after a restart. - Mutating state before validation is complete — a rejected move should leave the board identical to before the call.