Build a Game-Agnostic Two-Player Match Runner
System DesignModel answerLast updated
Design a modular Python framework that can run any two-player turn-based game by swapping rule and agent implementations without touching the core loop.
Background
Turn-based games share a common skeleton: players alternate, moves change some state, and the game eventually ends. Yet every game has unique rules. A well-designed framework captures the skeleton once and lets game-specific logic plug in cleanly.
Your task is to design that framework in Python.
What to Build
Create a match runner that can execute a complete game between two agents. The runner must remain completely ignorant of the rules of any particular game. Rules, players, and the runner itself are separate components that communicate through narrow interfaces.
The design must satisfy four properties:
- State lifecycle — the runner tracks state from the initial position through each move to a terminal condition (one player wins, or the game is drawn).
- Turn management — the runner asks the rules which player acts next, collects a move from that player's agent, confirms the move is legal, and advances the state.
- Plug-in extensibility — adding a new game type (e.g. Connect Four) or a new kind of agent (e.g. a Minimax AI) must require zero changes to the runner.
- Match observability — the system records every move and every intermediate state so a match can be replayed step-by-step or inspected for debugging.
Required Design
Provide Python abstract base classes (or Protocol types) that define the contracts between three components: the runner, a rules provider, and an agent. Then implement the runner itself and demonstrate the interfaces work by plugging in a Tic-Tac-Toe rules implementation and a random-move agent.
Constraints
- The design must not assume any board shape, piece type, or fixed player count beyond "exactly two players."
- Running multiple matches concurrently must be safe. Identify how your design achieves this, not just that it does.
- If an agent submits an illegal move, the runner must handle it gracefully rather than crashing.
What a Good Answer Covers
- The interface definitions and the reasoning behind each design choice
- The complete runner loop
- Thread-safety argument
- A worked example (Tic-Tac-Toe rules + random agent) that exercises the interfaces
- Trade-offs and known limitations
Hints
Hint 1
Start by identifying what the runner strictly needs to know at each step of the loop — you'll find it only ever needs to ask three questions: whose turn is it, what moves are available, and is the game over. Everything else belongs in the rules provider.
Hint 2
Immutable state objects are the simplest path to both thread safety and free replay support — if apply_move returns a new state rather than mutating the existing one, no two concurrent matches can interfere and your history list is already a replay log.
Hint 3
Model an illegal move as a forfeit rather than an exception by default: the offending player loses immediately. This keeps the runner loop clean and lets you test agent correctness separately from game correctness.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core Insight: Separate What Changes from What Stays the Same
Every turn-based game shares the same loop: get the current player, collect a move, validate it, apply it, check for termination. Only the content of each step varies by game. The Strategy pattern captures this perfectly — define narrow interfaces for the parts that vary (rules, agents) and implement the invariant loop once in the runner.
Three roles, three interfaces:
GameRulesknows everything about one specific game: initial state, whose turn it is, what moves are legal, how a move transforms the state, and how to detect a terminal condition.Agentreceives the current state and legal moves and returns one move. Human input, random selection, and tree-search AI are all just differentAgentimplementations.Engineknows only the loop. It holds no game-specific knowledge.
Why Immutable State Is the Right Call
Making state objects immutable (frozen dataclasses or equivalent) solves three problems at once:
- Thread safety — each
Engine.run()call works entirely with local variables. Two concurrent matches never touch the same state object, so no locks are needed. - Free replay — the history is just a list of states. Stepping backward means indexing one position earlier in the list.
- Agent isolation — an agent can inspect the state freely without risking corruption of the engine's copy. This makes testing agents trivial.
The Design
from __future__ import annotations
import random
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from typing import Generic, Hashable, Optional, Sequence, TypeVar
S = TypeVar("S") # game state — must be immutable
M = TypeVar("M", bound=Hashable) # move — immutable value object
class Status(Enum):
ONGOING = "ongoing"
WIN = "win"
DRAW = "draw"
@dataclass(frozen=True)
class Outcome:
status: Status
winner: Optional[int] = None # player index; only meaningful when WIN
ONGOING = Outcome(Status.ONGOING)
# ── Interfaces ────────────────────────────────────────────────────────────────
class GameRules(ABC, Generic[S, M]):
num_players: int = 2
@abstractmethod
def initial_state(self) -> S: ...
@abstractmethod
def current_player(self, state: S) -> int: ...
@abstractmethod
def legal_moves(self, state: S) -> Sequence[M]: ...
@abstractmethod
def apply_move(self, state: S, move: M) -> S:
"""Return a NEW state. Must not mutate `state`."""
...
@abstractmethod
def outcome(self, state: S) -> Outcome: ...
class Agent(ABC, Generic[S, M]):
@abstractmethod
def choose_move(
self,
state: S,
legal: Sequence[M],
rules: GameRules[S, M],
player: int,
) -> M: ...
class Observer(ABC):
def on_start(self, state) -> None: ...
def on_move(self, turn: int, player: int, move, state) -> None: ...
def on_end(self, outcome: Outcome) -> None: ...
# ── Record types ──────────────────────────────────────────────────────────────
@dataclass(frozen=True)
class MoveRecord:
turn: int
player: int
move: Hashable
@dataclass
class MatchRecord:
states: list = field(default_factory=list)
moves: list[MoveRecord] = field(default_factory=list)
outcome: Outcome = ONGOING
def replay(self, rules: GameRules):
"""Yield each state in order by re-applying moves from scratch."""
s = rules.initial_state()
yield s
for r in self.moves:
s = rules.apply_move(s, r.move)
yield s
# ── Engine ────────────────────────────────────────────────────────────────────
class Engine(Generic[S, M]):
def __init__(
self,
rules: GameRules[S, M],
max_turns: int = 10_000,
forfeit_on_illegal: bool = True,
):
self.rules = rules # stateless; safe to share across threads
self.max_turns = max_turns
self.forfeit_on_illegal = forfeit_on_illegal
def run(
self,
agents: Sequence[Agent[S, M]],
observers: Sequence[Observer] = (),
) -> MatchRecord:
if len(agents) != self.rules.num_players:
raise ValueError("need exactly one agent per player")
# All mutable match state is local to this call — the source of thread safety.
state = self.rules.initial_state()
rec = MatchRecord(states=[state])
for obs in observers:
obs.on_start(state)
outcome = ONGOING
for turn in range(self.max_turns):
outcome = self.rules.outcome(state)
if outcome.status is not Status.ONGOING:
break
player = self.rules.current_player(state)
legal = list(self.rules.legal_moves(state))
if not legal:
# Rules say ONGOING but offer no moves — rules bug, surface it.
raise RuntimeError("no legal moves but game is not terminal")
move = agents[player].choose_move(state, tuple(legal), self.rules, player)
if move not in set(legal):
if not self.forfeit_on_illegal:
raise ValueError(f"player {player} submitted illegal move {move!r}")
# Illegal move → opponent wins by forfeit.
outcome = Outcome(Status.WIN, winner=1 - player)
break
state = self.rules.apply_move(state, move)
rec.moves.append(MoveRecord(turn, player, move))
rec.states.append(state)
for obs in observers:
obs.on_move(turn, player, move, state)
else:
outcome = Outcome(Status.DRAW) # turn cap reached
rec.outcome = outcome
for obs in observers:
obs.on_end(outcome)
return rec
Worked Example: Tic-Tac-Toe
@dataclass(frozen=True)
class TTTState:
board: tuple[Optional[int], ...] = (None,) * 9
to_move: int = 0
class TicTacToe(GameRules[TTTState, int]):
LINES = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
def initial_state(self) -> TTTState:
return TTTState()
def current_player(self, s: TTTState) -> int:
return s.to_move
def legal_moves(self, s: TTTState) -> list[int]:
if self.outcome(s).status is not Status.ONGOING:
return []
return [i for i, cell in enumerate(s.board) if cell is None]
def apply_move(self, s: TTTState, m: int) -> TTTState:
cells = list(s.board)
cells[m] = s.to_move
return TTTState(tuple(cells), 1 - s.to_move)
def outcome(self, s: TTTState) -> Outcome:
for a, b, c in self.LINES:
if s.board[a] is not None and s.board[a] == s.board[b] == s.board[c]:
return Outcome(Status.WIN, winner=s.board[a])
return Outcome(Status.DRAW) if None not in s.board else ONGOING
class RandomAgent(Agent):
def __init__(self, seed: Optional[int] = None):
self.rng = random.Random(seed) # per-agent RNG — no shared global state
def choose_move(self, state, legal, rules, player):
return self.rng.choice(legal)
# Run a match
engine = Engine(TicTacToe())
record = engine.run([RandomAgent(0), RandomAgent(1)])
print(record.outcome)
Trade-offs and Known Limitations
Immutability overhead — copying state on every move costs more memory and CPU than in-place mutation. For shallow states like Tic-Tac-Toe this is negligible. For games with large boards (Chess, Go), you'd want structural sharing (e.g. persistent data structures) or a copy-on-write scheme rather than naive full copies.
No timeout enforcement on agents — a Minimax agent searching deep can stall the loop. A production runner would wrap choose_move in a thread with a deadline and treat a timeout as a forfeit.
Stateless rules assumption — GameRules carries no per-match state, which is what makes it thread-safe to share. A game with hidden information (card hands, fog of war) would need the rules to accept an additional player-perspective parameter, or the state object would need to store hidden information that agents simply aren't shown.
Extensibility in practice — adding Connect Four means writing a ConnectFour(GameRules) class and nothing else. Adding a Minimax agent means writing MinimaxAgent(Agent) and nothing else. Neither change touches the engine, demonstrating that the open-closed principle holds.