Build a Rule-Based Board Game State Manager
Data Structure DesignModel answerLast updated
Design an immutable, thread-safe game engine with pluggable validation rules for a turn-based strategy game.
Build a Rule-Based Board Game State Manager
You're building the core state-management system for a turn-based strategy board game with pieces that have different movement and interaction rules. The system must allow new rules to be added without changing the core engine code.
Core Requirements
Your design must support:
- Immutable state: Each action creates a new state rather than modifying the current one
- Pluggable validation: Movement and capture rules should be separate components that can be swapped or extended
- Full history tracking: Store every action so any prior state can be reconstructed
- Thread-safe reads: Multiple clients may query the current state concurrently
Your Task
Design the class structure showing how these components interact:
- State representation: How the board, pieces, and turn information are stored
- Action objects: How moves or commands are represented
- Validation layer: How rules are checked before applying an action
- Engine coordination: How the engine orchestrates validation, state transitions, and history
Example Skeleton
class Action:
# represents a player's move
pass
class GameState:
# immutable snapshot of board and pieces
pass
class Engine:
def execute(self, action: Action) -> GameState:
# validate, apply, record history
pass
Show how you would structure the validation layer so that adding a new rule (for example, "pieces cannot move onto water terrain unless they have a swimming ability") requires only writing a new validator class, not editing the engine itself.
Include consideration for:
- How state immutability helps with concurrency
- Where game-specific rules live versus generic orchestration logic
- How history replay would work
Hints
Hint 1
Separate 'what happened' (state) from 'is this allowed' (validation) from 'make it happen' (orchestration)
Hint 2
Each validator can be a small object with one check method; compose them into a validation pipeline
Hint 3
Store actions in order; replay by starting from initial state and applying each action sequentially
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
The key insight is to split concerns along three boundaries: immutable data, composable rules, and stateless orchestration. This makes the system open for extension but closed for modification.
High-Level Architecture
1. Immutable State Objects
GameState and Action are frozen value objects. State contains:
- The board layout (dimensions, terrain types at each coordinate)
- Current piece positions (mapping from coordinate to piece)
- Whose turn it is and the move count (ply)
Every field is immutable. Applying an action produces a new GameState with updated positions and incremented ply.
2. Strategy-Based Validation
Each rule implements a common interface:
class ValidationRule(Protocol):
def validate(self, state: GameState, action: Action) -> Optional[str]:
"""Returns error message if invalid, None if valid"""
pass
Examples:
TurnOrderRule: checks that the piece belongs to the active playerMovementRule: checks that the destination is reachable given the piece typeTerrainRule: checks terrain restrictions (water, obstacles)CaptureRule: checks whether one piece can capture another based on type or rank
A RuleChain composes multiple validators and runs them in sequence. Fast structural checks (bounds, turn order) run first; expensive logic runs last.
3. Pure Action Application
Action is a command object holding source, destination, and piece identifier. It has an apply method:
def apply(self, state: GameState) -> GameState:
new_positions = dict(state.positions)
piece = new_positions.pop(self.source)
new_positions[self.destination] = piece # overwrites captured piece
return GameState(
board=state.board,
positions=new_positions,
active_player=1 - state.active_player,
ply=state.ply + 1
)
This is a pure function: same input always produces the same output. No side effects, no mutation.
4. Orchestrating Engine
The engine holds:
- Current state (single reference, updated atomically)
- Action history (append-only tuple)
- Rule chain (injected at construction)
- A lock for writes
class Engine:
def __init__(self, rule_chain: RuleChain, initial_state: GameState):
self._state = initial_state
self._history = []
self._rules = rule_chain
self._lock = threading.Lock()
def current_state(self) -> GameState:
# Read is lock-free; state reference is atomic
return self._state
def execute(self, action: Action) -> GameState:
with self._lock:
old_state = self._state
error = self._rules.validate(old_state, action)
if error:
raise InvalidActionError(error)
new_state = action.apply(old_state)
self._history.append(action)
self._state = new_state
return new_state
def replay_to(self, ply: int) -> GameState:
state = self._initial_state
for action in self._history[:ply]:
state = action.apply(state)
return state
The lock only guards writes. Reads are safe because _state is an immutable object; a reader either sees the old reference or the new one, both valid.
Concrete Example: Adding a Water Rule
Suppose pieces cannot enter water unless they have a can_swim attribute.
New validator:
class WaterRestrictionRule:
def validate(self, state: GameState, action: Action) -> Optional[str]:
piece = state.positions[action.source]
terrain = state.board.terrain_at(action.destination)
if terrain == Terrain.WATER and not piece.can_swim:
return f"{piece.type} cannot enter water"
return None
Integration:
rules = RuleChain([
TurnOrderRule(),
BoundsRule(),
MovementRule(),
WaterRestrictionRule(), # ← added here
CaptureRule()
])
engine = Engine(rules, initial_state)
The engine code is untouched. This is the Open/Closed Principle: open for extension via new rule classes, closed for modification of the engine.
Why This Design Meets the Requirements
Immutability enables concurrency:
Because GameState is immutable, many threads can read engine.current_state() simultaneously without a lock. The engine only locks during the brief window when it validates and swaps the state reference. There's no risk of a reader seeing half-updated positions.
Separation of concerns:
GameStateanswers questions ("what piece is at this coordinate?")- Validators encode legality ("is this action allowed?")
Actionencodes transformation ("produce the next state")Engineorchestrates ("validate, apply, record")
Each layer depends only on the one below it. Game-specific logic lives entirely in validators and action types; the engine itself is generic.
History and replay:
Since apply is deterministic, the sequence of actions fully describes the game. Serializing history to JSON and replaying it reconstructs any state. Undo is just "keep the previous state reference." Replay also validates that a saved game wasn't corrupted.
Extensibility:
New piece types, terrain, or capture mechanics require new validators or new action subclasses. The engine and state representations stay stable.
Common Mistakes
- Mutating state in place: Leads to race conditions and breaks undo/replay. Always return a new object.
- Embedding rules in the engine: Makes the engine bloated and impossible to extend without editing it.
- Validating inside
apply: The action should be a pure transform. Validation is the engine's job via the rule chain. - Locking reads: If state is immutable, reads don't need a lock. Only the write (swap) must be atomic.
- Replaying by storing full state snapshots: Wastes memory. Store actions (small) and reconstruct states on demand.
Complexity
- Space: O(pieces) per state; O(actions) for history
- Validation: O(rules) per action
- Replay to ply n: O(n × rules) assuming O(1)
apply
The design scales well because immutability avoids defensive copying during reads, and the rule chain short-circuits on the first failure.