Build a Dropping Tile Game with Win Detection
Data Structure DesignModel answerLast updated
Implement game logic for a gravity-based two-player board game: handle piece placement, detect wins efficiently, and analyze complexity.
You're building a two-player board game where pieces drop into columns and stack vertically due to gravity. Design and implement the core game engine.
Rules
- The board has R rows and C columns (default 6×7)
- Two players alternate turns, dropping circular pieces into columns
- Pieces fall to the lowest available position in the chosen column
- A player wins by forming a continuous line of K pieces (default K=4) in any direction: horizontal, vertical, or diagonal
- The game ends in a draw when the board fills completely with no winner
Requirements
Implement a game class that supports:
- Piece placement: Accept a column number and place the current player's piece
- Move validation: Reject invalid moves (full columns, out of bounds, wrong turn, game already finished)
- Win detection: Determine if the last move created a winning line
- Game state: Track whose turn it is and whether the game is ongoing, won, or drawn
Make the board dimensions and win-length configurable.
What to discuss
- Time and space complexity of each operation
- How your win-checking algorithm avoids scanning the entire board
- Edge cases and error handling
- Possible extensions (AI player, multiplayer service, different board shapes)
Hints
Hint 1
Track the fill level of each column to avoid scanning for empty cells
Hint 2
A newly formed winning line must pass through the piece that was just placed
Hint 3
Count matching pieces in both directions along each line type (horizontal, vertical, two diagonals)
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarifying Requirements
Start by confirming the game rules and error-handling expectations:
- Board dimensions: Rows R, columns C, and win-length K should all be parameters
- Player representation: Use distinct values (1 and 2) with player 1 starting
- Move semantics: A move specifies only the column; gravity determines the row
- Invalid move handling: Throw exceptions for out-of-bounds columns, full columns, moves by the wrong player, or moves after game completion
- Game outcomes: After each move, the state is either ongoing, won by the moving player, or drawn (board full with no winner)
Core Approach
The solution hinges on two optimizations:
1. Column height tracking
Maintain an array heights[c] storing how many pieces occupy each column. When placing a piece in column c, the landing row is simply heights[c]. This makes placement O(1) instead of O(R).
2. Local win detection
Only examine lines passing through the newly placed piece. Since no other cells changed, any new winning line must include this piece. For each of four line orientations (horizontal, vertical, and two diagonals), walk outward in both directions counting consecutive pieces:
matching_count = 1 + count_forward + count_backward
If matching_count >= K, the player wins.
A draw occurs when total_moves == R * C and no win was detected.
Correctness Argument
- The board had no winning lines before this move (otherwise the game would have ended)
- Other cells are unchanged, so pre-existing non-winning lines remain non-winning
- Every possible line through a cell belongs to one of four directional families
- Walking both ways along each direction captures all windows of length K containing the cell
- The board has exactly R×C cells, so after that many successful moves it must be full
Complexity Analysis
| Operation | Time | Space |
|---|---|---|
| Place piece | O(1) | — |
| Check for win | O(K) | — |
| Check for draw | O(1) | — |
| Total storage | — | O(R·C) |
The naive approach—scanning all board positions after every move—costs O(R·C·K). The optimized version improves this by a factor of (R·C).
Edge Cases to Handle
- Column index below 0 or at least C
- Attempting to drop into a completely filled column
- Player 2 moving when it's player 1's turn, or vice versa
- Any move after the game has concluded
- Winning on the final available cell (test win condition before declaring draw)
- Winning lines that extend beyond K pieces (use
>=not==) - Boundary checking when walking diagonals near edges
- K larger than both dimensions (mathematically impossible to win)
Python Implementation
from enum import Enum
class GameState(Enum):
ONGOING = "ONGOING"
WON = "WON"
DRAWN = "DRAWN"
class DroppingTileGame:
VACANT = 0
LINE_TYPES = [(0, 1), (1, 0), (1, 1), (1, -1)] # →, ↑, ↗, ↘
def __init__(self, rows=6, cols=7, target=4):
if rows <= 0 or cols <= 0 or target <= 0:
raise ValueError("Dimensions and target must be positive")
self.rows = rows
self.cols = cols
self.target = target
self.grid = [[self.VACANT] * cols for _ in range(rows)]
self.heights = [0] * cols
self.active_player = 1
self.move_count = 0
self.state = GameState.ONGOING
self.victor = None
def place_piece(self, column, player):
"""Drop player's piece into the specified column."""
if self.state != GameState.ONGOING:
raise RuntimeError("Game has ended")
if player != self.active_player:
raise ValueError(f"Player {self.active_player}'s turn")
if not (0 <= column < self.cols):
raise ValueError(f"Column {column} is out of bounds")
if self.heights[column] >= self.rows:
raise ValueError(f"Column {column} is full")
landing_row = self.heights[column]
self.grid[landing_row][column] = player
self.heights[column] += 1
self.move_count += 1
if self._has_winning_line(landing_row, column, player):
self.state = GameState.WON
self.victor = player
elif self.move_count == self.rows * self.cols:
self.state = GameState.DRAWN
else:
self.active_player = 3 - player # toggle 1↔2
return self.state
def available_columns(self):
"""Return list of columns that can accept a piece."""
if self.state != GameState.ONGOING:
return []
return [c for c in range(self.cols) if self.heights[c] < self.rows]
def _count_direction(self, row, col, drow, dcol, player):
"""Count consecutive pieces of player starting from adjacent cell."""
found = 0
r, c = row + drow, col + dcol
while (0 <= r < self.rows and
0 <= c < self.cols and
self.grid[r][c] == player and
found < self.target - 1):
found += 1
r += drow
c += dcol
return found
def _has_winning_line(self, row, col, player):
"""Check if piece at (row, col) completes a winning line."""
for drow, dcol in self.LINE_TYPES:
line_length = (1 +
self._count_direction(row, col, drow, dcol, player) +
self._count_direction(row, col, -drow, -dcol, player))
if line_length >= self.target:
return True
return False
def display(self):
"""Return string representation with top row first."""
tokens = {0: "·", 1: "X", 2: "O"}
lines = []
for r in range(self.rows - 1, -1, -1):
lines.append(" ".join(tokens[self.grid[r][c]] for c in range(self.cols)))
return "\n".join(lines)
Usage example:
game = DroppingTileGame()
moves = [(3, 1), (3, 2), (4, 1), (4, 2), (5, 1), (5, 2), (6, 1)]
for col, p in moves:
result = game.place_piece(col, p)
assert result == GameState.WON
assert game.victor == 1
The cap found < target - 1 in the directional walk bounds each search at K−1 steps, guaranteeing O(K) total win detection.
Extension: AI Opponent
Algorithm: Minimax search with alpha-beta pruning to depth D.
available_columns()gives a branching factor of at most C- Implement
undo_last_move(column)to efficiently explore game trees without copying boards - At leaf nodes (depth limit reached), use a heuristic evaluation function
Heuristic scoring:
- Scan all windows of length K
- Award points for windows with (K−1) own pieces and 1 vacant cell (threat)
- Deduct points for opponent threats
- Bonus for center-column control (more strategic options)
Optimizations:
- Move ordering: Evaluate center columns first to improve pruning effectiveness
- Zobrist hashing: Cache evaluated positions to skip redundant subtrees
- Iterative deepening: Search progressively deeper (depth 1, 2, 3…) so a move is always available when time expires
- Bitboard representation: For standard 6×7 boards, encode each player's pieces in a 64-bit integer, enabling constant-time win checks via bit manipulation
Extension: Multiplayer Service
Scaling considerations:
- Store game state in a database (PostgreSQL, DynamoDB) keyed by game ID
- Use optimistic locking or versioning to handle concurrent move attempts
- Implement Redis caching for active games to reduce database load
- WebSocket or long-polling for real-time move notifications
- Rate limiting per player to prevent abuse
- Separate matchmaking service to pair players by skill rating (ELO/Glicko)
Tradeoffs: In-memory game state offers lowest latency but requires sticky sessions or shared state (Redis). Persistent storage supports scaling and recovery but adds 10-50ms latency per move.