Designing a Board Game Engine as a Production Library or Service API
System DesignModel answerLast updated
Transform a prototype game engine script into a production-grade software library and stateful HTTP microservice with clean architecture and robust edge-case handling.
Imagine you have just written a working implementation of a two-player grid-based game engine during a coding session.
The core game mechanics operate as follows:
- The game board has dimensions of $R$ rows by $C$ columns.
- A turn consists of dropping a colored piece into the bottom of a specific column. This action shifts all pre-existing pieces in that column upward by one position. If the column is completely full, the top piece falls off the top of the board and is removed.
- The game engine identifies win conditions by finding $K$ contiguous pieces of the same color arranged in any single row or column.
Your current implementation works correctly and passes preliminary test cases, but it exists as a single, unorganized script with global variables, bare arrays, and embedded constants.
The interviewer asks:
"How would you restructure and extend this code so it can be published as a reusable, production-ready software library for other teams—or deployed as a standalone backend API service?"
Explain the specific engineering steps, architectural boundaries, edge-case definitions, and trade-offs required to transform this prototype into production software.
Hints
Hint 1
Distinguish internal state representations (like flat arrays or bitboards) from public interface contracts, ensuring users cannot mutate internal board arrays directly.
Hint 2
Consider subtle domain edge cases caused by column shifting, such as top-piece eviction during full-column inserts and simultaneous multi-player win evaluation.
Hint 3
Explain the operational differences between an in-process library model and a distributed network API, focusing on state management and concurrency controls.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Evaluation Objectives
This question tests a candidate's ability to transition rapid prototype code into maintainable software. Converting single-script implementations into reusable systems requires moving beyond simple correctness and addressing:
- Boundary & Interface Design: Hiding internal mechanics behind clean domain interfaces.
- Domain Edge-Case Resolution: Resolving game-specific ambiguities (such as piece eviction and simultaneous wins).
- Distribution & Quality Assurance: Setting up packaging, versioning, property testing, and typing.
- Network Microservice Architecture: Managing stateless wrap patterns, persistence, and optimistic concurrency control for REST/gRPC interfaces.
Step 1: Clarifying Questions & Scope Definition
Before proposing structural refactoring steps, clarify key operating constraints:
- Target Consumer Base: Is this library intended strictly for internal service integration, or is it a public-facing SDK? (Internal tools allow faster iteration, whereas public SDKs require strict backward compatibility and semantic versioning guarantees).
- Execution Target: Is the primary goal an in-memory embedded library, a stateless computational engine, or a stateful HTTP/gRPC game server?
- Domain Flexibility: Should the core engine strictly support two-player grid games, or should it accommodate custom rule sets (e.g., diagonal win conditions, variable player counts, or custom board geometries)?
- Concurrency Controls: Will single game instances be accessed concurrently across different worker threads or network nodes?
Step 2: In-Process Library Design
Transforming prototype code into an in-process software library requires organizing functionality into clear, isolated layers.
+-------------------------------------------------------------+
| Public API Contract |
| (GameEngine, GameConfig, MoveResult, GameStatus) |
+------------------------------+------------------------------+
|
v
+-------------------------------------------------------------+
| Domain Rules Engine |
| (Win Evaluator, Column Shifter, Validations) |
+------------------------------+------------------------------+
|
v
+-------------------------------------------------------------+
| Internal State Store |
| (2D Matrix / Bitboards / Immutable Snapshots) |
+-------------------------------------------------------------+
Layer A: Domain Modeling and Encapsulation
- Eliminate Script Globals: Move all global variables into explicit instance variables encapsulated within a core engine class.
- Hide Internal Data Representations: Callers should never inspect or mutate raw arrays directly. Internal structures (e.g., bitboards or flat 1D arrays) must remain private. State reads should occur via read-only accessors or snapshot objects (e.g.,
get_cell(row, col)). - Extract Rule Configurations: Replace fixed dimensions and thresholds ($R, C, K$) with a dedicated config value object.
from dataclasses import dataclass
from enum import Enum, auto
from typing import Optional, FrozenSet
class PlayerColor(Enum):
RED = "RED"
BLUE = "BLUE"
class GameStatus(Enum):
IN_PROGRESS = auto()
WON = auto()
DRAW = auto()
@dataclass(frozen=True)
class GameConfig:
rows: int = 6
cols: int = 7
k_consecutive: int = 4
enforce_alternating_turns: bool = True
@dataclass(frozen=True)
class MoveResult:
status: GameStatus
evicted_piece: Optional[PlayerColor]
winners: FrozenSet[PlayerColor]
Layer B: Edge Case Specifications
Under tight time limits, prototype code often leaves edge-case handling to implicit execution. A production library must establish explicit contracts for these edge cases:
- Top-Piece Eviction Mechanics: When dropping a piece into a full column shifts the contents upward, the topmost piece drops off the board.
- Engine Rule: The move shifts the column, records any evicted piece, places the new piece at row
0, and then evaluates win conditions on the resulting state.
- Engine Rule: The move shifts the column, records any evicted piece, places the new piece at row
- Simultaneous Multi-Player Wins: Because a column shift alters multiple row positions across the board simultaneously, a single turn can complete a line of $K$ pieces for both players at once.
- Engine Rule: The engine returns
winnersas aFrozenSet[PlayerColor]. If both players reach $K$ consecutive pieces simultaneously, thewinnersset contains both players and thestatustransitions toGameStatus.DRAW(or dual victory, depending on rules).
- Engine Rule: The engine returns
- Turn Order Violations: If
enforce_alternating_turnsis active, attempting to move out of sequence throws an explicitInvalidTurnError. - Moves on Terminated Games: Making a move after reaching a outcome must throw a domain-specific
GameOverError, preventing invalid state mutations.
Layer C: Typed Exceptions and Primary API Interface
class GameError(Exception):
"""Base exception class for all domain errors."""
class InvalidMoveError(GameError):
"""Raised when selecting invalid columns or breaking turn rules."""
class GameOverError(GameError):
"""Raised when attempting moves after game completion."""
class GameEngine:
def __init__(self, config: GameConfig = GameConfig()) -> None:
self._config = config
self._validate_config()
self._board: list[list[Optional[PlayerColor]]] = [
[None for _ in range(config.cols)] for _ in range(config.rows)
]
self._active_player: PlayerColor = PlayerColor.RED
self._status: GameStatus = GameStatus.IN_PROGRESS
self._winners: set[PlayerColor] = set()
def apply_move(self, player: PlayerColor, column: int) -> MoveResult:
if self._status != GameStatus.IN_PROGRESS:
raise GameOverError("Game is already finished.")
if self._config.enforce_alternating_turns and player != self._active_player:
raise InvalidMoveError(f"It is {self._active_player.value}'s turn.")
if not (0 <= column < self._config.cols):
raise InvalidMoveError(f"Column index {column} is out of bounds.")
# Execute shift logic and capture top evicted piece
evicted = self._shift_column_up(column, player)
# Evaluate row and column lines for K consecutive pieces
detected_winners = self._evaluate_winners()
if detected_winners:
self._winners.update(detected_winners)
self._status = GameStatus.DRAW if len(self._winners) > 1 else GameStatus.WON
# Advance turn if game continues
if self._status == GameStatus.IN_PROGRESS:
self._active_player = (
PlayerColor.BLUE if self._active_player == PlayerColor.RED else PlayerColor.RED
)
return MoveResult(
status=self._status,
evicted_piece=evicted,
winners=frozenset(self._winners)
)
def get_cell(self, row: int, col: int) -> Optional[PlayerColor]:
return self._board[row][col]
def _shift_column_up(self, col: int, new_piece: PlayerColor) -> Optional[PlayerColor]:
evicted_piece = self._board[self._config.rows - 1][col]
for r in range(self._config.rows - 1, 0, -1):
self._board[r][col] = self._board[r - 1][col]
self._board[0][col] = new_piece
return evicted_piece
Step 3: Packaging, Quality Assurance, and Testing
- Packaging & Distribution:
- Explicitly export public symbols using
__all__in top-level package modules. - Include type marker files (e.g.,
py.typedunder PEP 561) to support downstream static type checkers likemypy. - Adhere strictly to Semantic Versioning (
MAJOR.MINOR.PATCH). Behavioral changes to piece eviction or win evaluations constitute breaking changes requiring major version updates.
- Explicitly export public symbols using
- Comprehensive Test Suite:
- Unit Verification: Validate boundary checks, win-detection sweeps, and column shifts.
- Property-Based Testing: Use property testing frameworks (such as Hypothesis) to verify domain invariants:
- Invariant A: Total active pieces across the grid can never exceed $R \times C$.
- Invariant B: Post-game execution attempts must consistently raise
GameOverError. - Invariant C: Win detection results must be deterministic for identical sequence inputs.
Step 4: Exposing as a Network API Service
Wrapping the core engine behind a distributed HTTP/REST or gRPC network service introduces network, scale, and state considerations:
[ HTTP / REST Client ]
|
v
[ API Router Layer ] ---> Validate schema & map network errors
|
v
[ Application Service ] ---> Coordinate transactions & state locks
|
+---> [ Persistent Store ] (Redis / PostgreSQL)
|
v
[ Core Game Engine ] ---> Pure in-memory execution unit
Network Endpoints & Mapping
| Endpoint | Method | Payload / Params | Description |
|---|---|---|---|
/v1/games | POST | { "rows": 6, "cols": 7, "k": 4 } | Instantiates a new game session |
/v1/games/{id} | GET | None | Returns current board state & status |
/v1/games/{id}/moves | POST | { "player": "RED", "column": 3 } | Executes a turn on the specified game |
Exception to HTTP Status Mapping
InvalidMoveError$\rightarrow$400 Bad Requestor422 Unprocessable EntityGameOverError$\rightarrow$409 Conflict- Target resource not found $\rightarrow$
404 Not Found
State Management & Concurrency Control
- Persistence Layer: Store game instances in persistent key-value databases (e.g., Redis) or relational databases (e.g., PostgreSQL). Store game state alongside a monotonically increasing
versionsequence number. - Optimistic Concurrency Control: To prevent race conditions from concurrent network requests attempting to apply moves to the same game simultaneously, enforce version tracking:
UPDATE games
SET board_state = :new_state, version = version + 1
WHERE id = :game_id AND version = :expected_version;
If zero rows update, the application catches the mismatch and returns an HTTP 409 Conflict, prompting the caller to fetch the updated state and retry.
- Idempotency Support: Accept an
Idempotency-Keyheader on move creation endpoints. This prevents duplicate column shifts if a network client retries a request following a timeout.
Common Pitfalls to Avoid
- Generic Architectural Statements: Offering generic advice (e.g., "add logs and unit tests") without framing it around the specific game rules (e.g., column shifting and top-piece eviction).
- Leaking Domain Implementation Details: Exposing internal 2D list structures directly to callers, preventing future internal optimizations (such as switching to bitboard implementations).
- Coupling Service Protocol to Core Logic: Embedding HTTP handler abstractions directly into the core game engine instead of keeping the engine clean and protocol-agnostic.