Object-Oriented Probabilistic Minesweeper Engine
Medium · System Design · Software Engineer · Technical Screen
Prompt
Architect an object-oriented engine for a Minesweeper variant played on a 2D rectangular grid. At match startup, every tile coordinate receives a floating-point parameter prob (0.0 <= prob <= 1.0) specifying the independent likelihood that a mine occupies that tile. Walk through how those per-tile likelihoods produce the concrete mine placement, neighbor clue counts, and initial tile visibility states during initialization.
Define the primary domain classes (such as Game, Board, and Cell), the single responsibility owned by each class, how they compose together, and the public interface needed to:
- Render or print the player-visible board at any point in a session, and
- Process a player click at a given
(row, col)coordinate.
Specify the state transitions triggered by a click—ending in defeat when uncovering a mine, cascading across zero-clue regions and uncovering safe tiles otherwise, and transitioning to victory once every safe tile is uncovered—alongside safe handling of out-of-range coordinates, duplicate clicks on uncovered or flagged tiles, and inputs after the match has concluded. Explain how your class boundaries keep the codebase maintainable and deterministically unit-testable despite probabilistic setup.
Scope & Expectations
- Class boundaries & dependencies: Separate match rules, grid topology/flood-fill mechanics, mine-placement randomness, and board formatting so dependencies point cleanly in one direction.
- Probabilistic setup & determinism: Show how per-tile
probvalues are validated and sampled at initialization while still allowing deterministic unit tests and reproducible replays via dependency injection. - State transitions & edge cases: Trace tile and match state machines across mine hits, iterative zero-clue cascades, win detection, flag protection, out-of-bounds inputs, duplicate clicks, and post-game calls.
- Extensibility & testing: Demonstrate how the public return types and Collaborator interfaces make unit testing and future gameplay extensions straightforward.
Step-by-step walkthrough
Clarify requirements and scope
Unlike a distributed backend question, an Object-Oriented Design (OOD) interview runs entirely inside one process. The interviewer is evaluating three core engineering skills:
- Clean class boundaries: Does each class have one clear job, or is everything tangled inside one giant
Minesweeperclass? - Testability of randomness and I/O: How do you turn per-cell probabilities into a concrete mine layout while still allowing deterministic unit tests that never flake?
- Bulletproof state transitions: Does
click(r, c)handle mines, zero-mine cascades, wins, out-of-bounds coordinates, duplicate clicks, and clicks after game-over without corrupting state or crashing?
Functional requirements
- Construct an
R x Cmatch from a 2D gridprobswhose entries lie in[0.0, 1.0], each specifying the likelihood of a mine occupying(r, c). - At startup, sample once per tile whether it holds a mine, precompute its 8-neighbor mine count (
0..8), and initialize every tile in a hidden state. - Render / display the active board from the player's viewpoint without leaking unrevealed mines mid-match.
- Handle a player click at
(r, c):- Uncovering a mine reveals that tile and moves the match to lost.
- Uncovering a safe tile reveals it; when its neighbor mine count is
0, expand iteratively (flood fill) across connected zero-clue tiles and their numbered perimeter. - Uncovering the final remaining safe tile moves the match to won.
- Treat out-of-range inputs (negative, oversized, or non-integer coordinates), repeated clicks (already revealed tiles), and clicks after win/loss as clean no-ops that never corrupt board state.
- Provide
toggle_flag(r, c)so players can mark suspected mines and shield flagged tiles from accidental clicks.
Non-functional requirements
- Deterministic testability via dependency injection (passing collaborators like the mine-placement generator and display renderer into
Gamefrom the outside rather than hard-coding globalrandomorprintinside core logic). - Predictable runtime and stack safety: Processing a click takes
O(cells newly revealed)time using an iterative queue—never recursion, which crashes on large empty boards—and win detection takesO(1)time per click. - Extensibility: Adding a new UI format (JSON/GUI), a safe-first-click rule, or "chording" requires adding a small class or method rather than rewriting
BoardorCell.
Clarifying assumptions
- Independent per-cell probabilities: Each cell
(r, c)conducts an independent Bernoulli trial—a single weighted coin flip that landsTrue(mine) with probabilityprobs[r][c]andFalse(safe) with probability1 - probs[r][c]. Because flips are independent, the total mine count varies from game to game;Board.mine_countrecords the exact count generated. - Eager layout generation: As requested in the prompt, mines and neighbor counts are generated during initialization. (Supporting guaranteed first-click safety via lazy generation is shown as a plug-in policy in Deep Dive 1.)
- Coordinate convention: 0-indexed
(row, col)with(0, 0)at the top-left corner.
- Clean class boundaries: Does each class have one clear job, or is everything tangled inside one giant
Back-of-the-envelope numbers
Even for an in-memory object model, quick math reveals two subtle bugs waiting to happen (mine-count variance and Python's recursion limit):
Standard Minesweeper board sizes Beginner 9 x 9 = 81 cells, ~10 mines (~12% density) Intermediate 16 x 16 = 256 cells, ~40 mines (~16% density) Expert 16 x 30 = 480 cells, ~99 mines (~20.6% density) Why probabilistic mine counts vary (sum of independent coin flips p_i) Expected mines = sum(p_i) Variance = sum(p_i * (1 - p_i)) Expert example 480 cells each with p = 99 / 480 ≈ 0.206: mean = 99 mines std = sqrt(480 * 0.206 * 0.794) ≈ 8.9 mines -> ~28% of games have < 90 or > 108 mines! -> UI "mines remaining" MUST use actual `board.mine_count`, never `sum(probs)`. Memory footprint (64-bit CPython) Cell with __slots__ ~64-72 bytes per Cell object (vs ~112+ bytes with a per-object __dict__) Expert (480 cells) ~35 KB -> tiny 1000 x 1000 (1M) ~70 MB -> fits in RAM, or shrinks to ~3 MB using 3 bytearrays Time & call-stack limits Initialization O(R * C) — 1 random draw per cell + <= 8 neighbor increments per mine All clicks combined O(R * C) — each safe cell transitions HIDDEN -> REVEALED at most once Win check O(1) per click via `safe_left` counter (scanning the grid would be O(R * C) per click) Recursion trap! CPython's default recursion limit is 1,000 stack frames. A recursive flood fill on an empty 40 x 40 (1,600 cells) or 1 x 5,000 board raises `RecursionError`! -> Always use an iterative queue.Public API and display format
Gameacts as a Facade—the single front-door class that callers (a CLI loop, a web controller, or unit tests) interact with, keepingBoardandCellprotected from direct outside mutation.We deliberately handle programmer errors and player actions differently:
- Invalid board setup (empty grid, ragged row lengths,
prob < 0,prob > 1, orNaN) is a bug in caller code, soGame(...)raisesValueErrorimmediately at construction. - Invalid or duplicate clicks (
click(-1, 0), clicking a revealed or flagged cell, clicking after game-over) are normal user events during play, soclick()returns a structuredClickResultvalue and leaves the board untouched rather than forcing callers to wrap every click intry / except.
from dataclasses import dataclass, field from enum import Enum class Outcome(Enum): REVEALED = "revealed" # 1 or more safe cells uncovered; game continues HIT_MINE = "hit_mine" # clicked an unflagged mine; game is now LOST WON = "won" # uncovered the final safe cell; game is now WON FLAGGED = "flagged" # hidden cell marked with a flag UNFLAGGED = "unflagged" # flag removed; cell returns to hidden NO_CHANGE = "no_change" # duplicate click on revealed cell, or click on flagged cell INVALID = "invalid" # out-of-bounds or non-integer coordinates GAME_OVER = "game_over" # click or flag attempted after WON or LOST @dataclass class ClickResult: outcome: Outcome # Exact list of (row, col) coordinates newly uncovered by this call (great for UI diffs & tests). revealed: list = field(default_factory=list) message: str = ""Separating
render() -> strfromprint_board() -> Nonekeeps formatting pure and lets unit tests compare board snapshots with a plain==assertion instead of capturingsys.stdout:class TextRenderer: """Formats a Board into a human-readable ASCII grid without mutating any game state.""" HIDDEN, FLAG, MINE, EMPTY = "#", "F", "*", "." def render(self, board, show_mines=False): lines = [] for r in range(board.rows): row_symbols = [ self._symbol(board.cell(r, c), show_mines) for c in range(board.cols) ] lines.append(" ".join(row_symbols)) return "\n".join(lines) def _symbol(self, cell, show_mines): # Once the game is lost (`show_mines=True`), reveal every mine on the grid. if show_mines and cell.is_mine: return self.MINE if cell.state == CellState.FLAGGED: return self.FLAG if cell.state == CellState.HIDDEN: return self.HIDDEN if cell.is_mine: return self.MINE if cell.adjacent_mines == 0: return self.EMPTY return str(cell.adjacent_mines)For example, on a
4 x 4board whose sole mine sits at(2, 1), callinggame.click(0, 3)cascades across the zero-clue region and stops cleanly along the numbered perimeter:Before click(0, 3): After click(0, 3): If player clicks (2, 1): # # # # . . . . . . . . # # # # 1 1 1 . 1 1 1 . # # # # # # 1 . # * 1 . # # # # # # 1 . # # 1 .- Invalid board setup (empty grid, ragged row lengths,
Data model: enums, Cell, and class responsibilities
A common OOD mistake is combining "what the cell secretly contains" and "what the player has done to it" into one big enum (
HIDDEN_MINE,HIDDEN_SAFE,FLAGGED_MINE,FLAGGED_SAFE, ...), which doubles the cases every method has to check. Instead, we keep the immutable ground truth (is_mine: bool) separate from the mutable visibility state (CellState):class CellState(Enum): HIDDEN = "hidden" REVEALED = "revealed" FLAGGED = "flagged" class GameStatus(Enum): IN_PROGRESS = "in_progress" WON = "won" LOST = "lost" class Cell: # `__slots__` replaces each instance's dynamic dict with fixed memory slots, saving ~40% RAM on big grids. __slots__ = ("prob", "is_mine", "adjacent_mines", "state") def __init__(self, prob, is_mine): self.prob = prob # original mine probability in [0.0, 1.0], kept for inspection/analytics self.is_mine = is_mine # fixed boolean decided once during initialization self.adjacent_mines = 0 # 0..8, populated by Board right after all cells are created self.state = CellState.HIDDEN # every cell begins hiddenEach class has a single, well-defined responsibility:
Class Responsibility Collaborators it knows about CellStores one cell's prob,is_mine,adjacent_mines, andstateCellStateonly (knows nothing about coordinates or neighbors)BoardOwns the R x Cgrid, bounds checks, 8-direction neighbor lookup, initial neighbor counts, and BFS flood-fillCellMinePlacer(Strategy)Converts probs(R x Cfloats) intomine_layout(R x Cbooleans)Pure numbers / injected random.RandomGame(Facade)Enforces turn rules, GameStatus,safe_leftwin counter,click(),toggle_flag(), and delegates renderingBoard,MinePlacer,TextRendererTextRendererTurns Boardread-only state into a printable stringBoard,Cell(read-only)High-level architecture: class diagram and dependencies
All dependencies point strictly one way (
Game -> Board -> Cell), so lower-level data classes never reach back up into game rules or UI printing:Caller (CLI, Web Controller, Unit Tests) | v +-------------------------------------------------------------------+ | Game (Facade) | | - status: GameStatus | | - safe_left: int | | + click(r, c) -> ClickResult | | + toggle_flag(r, c) -> ClickResult | | + render() -> str / print_board() -> None | +----------+-----------------------+------------------------+-------+ | owns 1 | uses 1 (Strategy) | uses 1 v v v +----------------------+ +------------------------+ +-------------------+ | Board | | MinePlacer | | TextRenderer | | - rows, cols | | + place(probs) | | + render(board, | | - mine_count | | -> list[list[bool]] | | show_mines) | | + in_bounds(r, c) | +-----------+------------+ +-------------------+ | + neighbors(r, c) | ^ | + reveal_from(r, c) | +------+---------------+ +----------+-----------+ | | | owns R x C BernoulliMinePlacer FixedMinePlacer v (injected RNG) (deterministic tests) +----------------------+ | Cell | | - prob, is_mine | | - adjacent_mines | | - state: CellState | +----------------------+Here is how
Game.__init__wires everything together in four clear steps:import random class Game: def __init__(self, probs, placer=None, renderer=None): # 1. Fail fast on malformed grid dimensions or invalid probabilities. validate_probs(probs) # 2. Generate concrete boolean mine layout using the injected Strategy (defaults to independent coin flips). if placer is None: placer = BernoulliMinePlacer(random.Random()) mine_layout = placer.place(probs) # 3. Build the Board (creates Cells and precomputes 8-neighbor mine counts). self.board = Board(probs, mine_layout) self.renderer = renderer if renderer is not None else TextRenderer() # 4. Initialize game status and O(1) remaining-safe-cells win counter. self.status = GameStatus.IN_PROGRESS self.safe_left = (self.board.rows * self.board.cols) - self.board.mine_count def render(self): show_all_mines = (self.status == GameStatus.LOST) return self.renderer.render(self.board, show_mines=show_all_mines) def print_board(self): print(self.render())Deep dive 1: generating the initial mine layout from probabilities
How each cell's
probbecomes a boolean mine decision. For each cell with probabilityp, we draw a uniform floating-point numberuin[0.0, 1.0)(including0.0, strictly excluding1.0) and place a mine whenu < p. Notice why strict<(never<=) is essential at the two boundaries:- When
p = 0.0, no draw in[0.0, 1.0)satisfiesu < 0.0, so a0.0cell is never a mine. (Writingu <= pwould wrongly place a mine ifrandom()returned0.0!) - When
p = 1.0, every draw in[0.0, 1.0)satisfiesu < 1.0, so a1.0cell is always a mine.
Why
MinePlacerrolls the dice instead ofCell.__init__. IfCell(prob)called globalrandom.random()inside its own constructor, every unit test would get a random board, bug reports could not be replayed, and board-wide rules (like keeping the first click safe) would have nowhere to live. ExtractingMinePlacerapplies the Strategy pattern (encapsulating an interchangeable algorithm behind a tiny interface):class BernoulliMinePlacer: """Flips an independent weighted coin `rng.random() < p` for each cell.""" def __init__(self, rng): self.rng = rng def place(self, probs): return [ [self.rng.random() < p for p in row] for row in probs ] class FixedMinePlacer: """Returns an explicit boolean grid for deterministic unit tests and saved replays.""" def __init__(self, layout): self.layout = layout def place(self, probs): return [list(row) for row in self.layout]Defensive input validation. Before touching the placer,
validate_probsrejects empty grids, jagged rows, booleans (isinstance(True, int)isTruein Python!), strings, out-of-range numbers, andfloat('nan'). Writing the range check asnot (0.0 <= p <= 1.0)automatically catchesNaNbecause every comparison involvingNaNevaluates toFalse:def validate_probs(probs): if not probs or not probs[0]: raise ValueError("Probability grid must be non-empty.") cols = len(probs[0]) for row in probs: if len(row) != cols: raise ValueError("All rows in probability grid must have the same length.") for p in row: if isinstance(p, bool) or not isinstance(p, (int, float)): raise ValueError(f"Probability must be a real number, got {p!r}.") if not (0.0 <= p <= 1.0): raise ValueError(f"Probability must be in [0.0, 1.0], got {p}.")Initializing
Cellstates and precomputing neighbor counts. Oncemine_layoutis chosen,Board.__init__creates allR x ChiddenCellobjects and computesadjacent_minesin a singleO(R * C)pass: whenever(r, c)is a mine, it adds+1to each of its valid neighbors (3 at corners, 5 along edges, 8 in the interior):from collections import deque class Board: def __init__(self, probs, mine_layout): self.rows = len(probs) self.cols = len(probs[0]) if len(mine_layout) != self.rows or any(len(row) != self.cols for row in mine_layout): raise ValueError("Mine layout dimensions must match probability grid.") # 1. Create every Cell in HIDDEN state with its assigned (prob, is_mine). self.cells = [ [Cell(probs[r][c], bool(mine_layout[r][c])) for c in range(self.cols)] for r in range(self.rows) ] # 2. Precompute adjacent_mines once by incrementing neighbors around each mine. self.mine_count = 0 for r in range(self.rows): for c in range(self.cols): if self.cells[r][c].is_mine: self.mine_count += 1 for nr, nc in self.neighbors(r, c): self.cells[nr][nc].adjacent_mines += 1 def in_bounds(self, r, c): return 0 <= r < self.rows and 0 <= c < self.cols def cell(self, r, c): return self.cells[r][c] def neighbors(self, r, c): result = [] for dr in (-1, 0, 1): for dc in (-1, 0, 1): if dr == 0 and dc == 0: continue nr, nc = r + dr, c + dc if self.in_bounds(nr, nc): result.append((nr, nc)) return resultOptional policy extension: If an interviewer asks for guaranteed first-click safety,
Gamesimply defers callingplacer.place(probs)until the firstclick(r0, c0)arrives, passingsafe_cells={(r0, c0)}solayout[r0][c0]is forced toFalsewhile every other cell still flips independently with its originalprob.- When
Deep dive 2: click state transitions, flood fill, and edge cases
Every user action moves
GameStatusandCellStatealong strict one-way or reversible transitions:GameStatus transitions: IN_PROGRESS -- click unflagged mine --------------------> LOST (terminal) IN_PROGRESS -- reveal safe cell & safe_left hits 0 -----> WON (terminal) IN_PROGRESS -- reveal safe cell (safe_left > 0) / flag -> IN_PROGRESS WON / LOST -- any click or toggle_flag ----------------> unchanged (returns GAME_OVER) CellState transitions: HIDDEN <-- toggle_flag --> FLAGGED (clicking a FLAGGED cell returns NO_CHANGE) HIDDEN -- click / BFS ---> REVEALED (terminal; duplicate clicks return NO_CHANGE)Why the guard order in
Game.click(r, c)matters. Each check protects the steps beneath it:status != IN_PROGRESS->GAME_OVER: Freezes the board once won or lost.- Coordinate validation ->
INVALID: Must checktype(r) is int(rejecting floats like1.5and booleans likeTrue) and0 <= r < rowsexplicitly—because in Python,self.cells[-1][0]would otherwise silently index the bottom row! state == REVEALED->NO_CHANGE: Makes duplicate clicks idempotent no-ops.state == FLAGGED->NO_CHANGE: Protects flagged cells against misclicks until explicitly unflagged.cell.is_mine->HIT_MINE: Reveals the clicked mine and setsstatus = LOST.- Safe cell ->
board.reveal_from(r, c): Runs iterative breadth-first search (BFS) (exploring neighbors layer by layer through a first-in, first-out queue), subtractslen(revealed)fromself.safe_left, and transitions toWONifsafe_left == 0.
Tracing BFS flood-fill (
reveal_from) carefully. Two subtle rules keep flood-fill both correct and fast:- Stop expanding at numbered cells (
adjacent_mines > 0): Numbered border cells are revealed, so the player sees the boundary clues, but their neighbors are not pushed onto the queue (otherwise expansion would leap across numbers into mines!). - Mark
state = REVEALEDat enqueue time, not dequeue time: If we waited until popping from the queue to mark a cell revealed, up to 8 neighboring0-cells could push the exact same hidden coordinate onto the queue before it was popped, causing duplicate entries inrevealedand corruptingsafe_left!
Mini-trace on a 1 x 4 row with layout -> [*, 1, 0, 0] (mine at col 0): 1. click(0, 3): mark (0,3) REVEALED immediately, queue = [(0,3)], revealed = [(0,3)] 2. pop (0,3): adjacent_mines == 0 -> inspect neighbor (0,2): HIDDEN -> mark REVEALED, push (0,2) 3. pop (0,2): adjacent_mines == 0 -> inspect neighbors (0,1) [HIDDEN -> mark REVEALED, push (0,1)] and (0,3) [already REVEALED, skip] 4. pop (0,1): adjacent_mines == 1 (> 0!) -> STOP expansion here; mine at (0,0) is never touched! 5. Result: revealed = [(0,3), (0,2), (0,1)], safe_left drops from 3 to 0 -> Outcome.WON!Here are the complete click, flag, and flood-fill methods:
class GameActionsMixin: """Click and flag handlers on Game (shown standalone so every code block parses cleanly).""" def click(self, r, c): if self.status != GameStatus.IN_PROGRESS: return ClickResult(Outcome.GAME_OVER, message="Game is already over.") if not self._valid_coords(r, c): return ClickResult(Outcome.INVALID, message=f"Coordinates ({r!r}, {c!r}) are out of bounds.") cell = self.board.cell(r, c) if cell.state == CellState.REVEALED: return ClickResult(Outcome.NO_CHANGE, message="Cell is already revealed.") if cell.state == CellState.FLAGGED: return ClickResult(Outcome.NO_CHANGE, message="Cell is flagged; unflag before clicking.") if cell.is_mine: cell.state = CellState.REVEALED self.status = GameStatus.LOST return ClickResult(Outcome.HIT_MINE, revealed=[(r, c)]) newly_revealed = self.board.reveal_from(r, c) self.safe_left -= len(newly_revealed) if self.safe_left == 0: self.status = GameStatus.WON return ClickResult(Outcome.WON, revealed=newly_revealed) return ClickResult(Outcome.REVEALED, revealed=newly_revealed) def toggle_flag(self, r, c): if self.status != GameStatus.IN_PROGRESS: return ClickResult(Outcome.GAME_OVER, message="Game is already over.") if not self._valid_coords(r, c): return ClickResult(Outcome.INVALID, message=f"Coordinates ({r!r}, {c!r}) are out of bounds.") cell = self.board.cell(r, c) if cell.state == CellState.REVEALED: return ClickResult(Outcome.NO_CHANGE, message="Cannot flag an already revealed cell.") if cell.state == CellState.HIDDEN: cell.state = CellState.FLAGGED return ClickResult(Outcome.FLAGGED) cell.state = CellState.HIDDEN return ClickResult(Outcome.UNFLAGGED) def _valid_coords(self, r, c): # Use exact `type(x) is int` because `isinstance(True, int)` is True in Python! if type(r) is not int or type(c) is not int: return False return self.board.in_bounds(r, c)And
Board.reveal_from:from collections import deque def reveal_from(board, start_r, start_c): """Iterative BFS flood-fill on `Board`: reveals safe cells and stops expanding at numbers > 0.""" start_cell = board.cell(start_r, start_c) start_cell.state = CellState.REVEALED revealed = [(start_r, start_c)] queue = deque([(start_r, start_c)]) while queue: cr, cc = queue.popleft() # Numbered cells form the visible boundary—do not expand past them. if board.cell(cr, cc).adjacent_mines > 0: continue for nr, nc in board.neighbors(cr, cc): neighbor = board.cell(nr, nc) # Respect player flags (skip FLAGGED cells); mark REVEALED on enqueue so each cell enters once. if neighbor.state == CellState.HIDDEN and not neighbor.is_mine: neighbor.state = CellState.REVEALED revealed.append((nr, nc)) queue.append((nr, nc)) return revealedDeep dive 3: testing and maintainability
Because randomness and rendering are injected, every piece of the design can be unit-tested in milliseconds without mocking globals or capturing terminal output:
def test_zero_cascade_duplicate_and_invalid_clicks(): # Deterministic 4x4 board with exactly 1 mine at (2, 1); probabilities don't cause flakiness. layout = [ [False, False, False, False], [False, False, False, False], [False, True, False, False], [False, False, False, False], ] probs = [[0.20] * 4 for _ in range(4)] game = Game(probs, placer=FixedMinePlacer(layout)) res = game.click(0, 3) assert res.outcome == Outcome.REVEALED assert len(res.revealed) == 12 assert game.safe_left == 3 assert game.render() == ". . . .\n1 1 1 .\n# # 1 .\n# # 1 ." # Duplicate and negative-index clicks change nothing. assert game.click(0, 3).outcome == Outcome.NO_CHANGE assert game.click(-1, 3).outcome == Outcome.INVALID assert game.safe_left == 3Layered test plan:
Boardunit tests: Verify neighbor counts at corners (3), edges (5), and interior (8); verify1 x 1boards; runreveal_fromon an empty1 x 5,000strip to prove zeroRecursionError.Gametransition table tests: One assertion per branch (GAME_OVER,INVALIDnegative/float/bool,REVEALEDduplicate,FLAGGEDprotection,HIT_MINE, partialREVEALED,WONon all-zero board, andall p == 1.0board wheresafe_left == 0and any click loses).BernoulliMinePlacerstatistical test: Verifyp = 0.0produces 0 mines across 1,000 trials,p = 1.0produces 1,000 mines, identical seeds (random.Random(42)) produce identical layouts, andp = 0.5overN = 10,000seeded trials lands within 4 standard deviations (4 * sqrt(0.5 * 0.5 / 10000) = ±0.02, which has a false-failure rate of ~0.006%).
Scaling, invalid-input summary, and trade-offs
If an interviewer pushes the design toward larger boards or a multi-user web service:
- Huge boards (
1,000 x 1,000+): Keep the exact sameBoardpublic methods, but replace the 2D list ofCellobjects (~70 MB) with three flatbytearraybuffers (is_mine,adjacent_mines,state) totaling 3 bytes per cell (~3 MB), and addrender_viewport(r0, r1, c0, c1)so the UI renders only visible tiles. - Hosting 1 million active games on a web server: Packing
is_mine(1 bit) +CellState(2 bits) = 3 bits per cell stores an entire 480-cell expert board in 180 bytes (adjacent_minesis recomputed on load), so 1M active sessions fit under 200 MB of RAM. Never sendis_minefor hidden cells to the browser (anti-cheat), and guard concurrent clicks from two open tabs using a per-game lock or optimisticversioncounter.
Edge-case and invalid-input summary:
Input / Scenario Behavior Why Empty grid, ragged rows, p < 0,p > 1,NaN,boolValueErroratGame(...)constructionFail fast on programmer bugs before an invalid game can exist All cells p = 0.0(0 mines)First valid click reveals entire board and returns WONsafe_leftdrops fromR * Cto0in one BFS passAll cells p = 1.0(all mines)safe_leftstarts at0; any click hits a mine and returnsHIT_MINE(LOST)cell.is_mineis checked beforesafe_left == 0Negative (r, c), out-of-bounds,float,bool,strReturns ClickResult(Outcome.INVALID), state unchangedPrevents Python negative-index wraparound ( cells[-1])Click on revealed or flagged cell Returns ClickResult(Outcome.NO_CHANGE), state unchangedSafe idempotency for double-clicks and misclick protection Any click or flag after WON/LOSTReturns ClickResult(Outcome.GAME_OVER), state unchangedTerminal game states are immutable - Huge boards (
Intuition & how it works
Think of object-oriented Minesweeper like running a stage play with three distinct roles: the stage crew (MinePlacer and Board) secretly sets the trapdoors before the curtain goes up and knows which floorboards touch each other, the referee (Game) checks every step the player takes against the rules and announces when they have won or lost, and the spotlight operator (TextRenderer) shows the audience only the tiles uncovered so far without giving away hidden mines.
A naive beginner design puts everything into one Minesweeper class where each Cell(prob) calls global random.random() inside its own constructor, click() prints directly to the console, and blank regions expand via recursion. That design breaks down quickly: unit tests become flaky because every run generates a random board, swapping terminal text for a web JSON response requires editing game rules, and clicking an empty 40 x 40 or 1 x 5,000 grid crashes Python with RecursionError once nested calls exceed ~1,000 frames.
Here is how our separated design walks through a tiny 3 x 3 board where initialization places a single mine at the bottom-left corner (2, 0):
- Initialization:
Gamevalidatesprobs, asks the injectedMinePlacerto flip a weighted coin (rng.random() < prob) for each cell, and buildsBoard.Boardsetsmine_count = 1, precomputesadjacent_mines(1on(1, 0),(1, 1), and(2, 1), and0everywhere else), starts all 9 cells asHIDDEN, and setsGame.safe_left = 9 - 1 = 8. - Clicking a numbered cell
(1, 1):Game.click(1, 1)verifies the game isIN_PROGRESSand(1, 1)is in-bounds andHIDDEN. Becauseadjacent_mines == 1 > 0,Board.reveal_from(1, 1)reveals only(1, 1)and stops immediately;safe_leftdrops from8to7, and clicking(1, 1)a second time safely returnsOutcome.NO_CHANGE. - Clicking a zero cell
(0, 2):Board.reveal_from(0, 2)runs an iterative queue-based breadth-first search (BFS) (visiting neighbors layer by layer through a FIFO queue), uncovering all five0cells plus the remaining two1border cells ((1, 0)and(2, 1)) while stopping before the mine at(2, 0).safe_leftdrops from7to0, transitioningGame.statustoWONinO(1)time without scanning the board.
Key trade-offs
- Independent per-cell coin flips (
BernoulliMinePlacer) vs. a fixed mine countK. Flippingrng.random() < probindependently per cell honors each cell's exactprobvalue as stated, at the cost of a variable total mine count (e.g., standard deviation ~8.9 mines on a 480-cell expert board), so the UI must readboard.mine_countrather thansum(probs). Enforcing an exact total ofKmines forces the per-cell probabilities to sum toK, turningprobinto a relative weight rather than a true probability. - Injecting
MinePlacer(Strategy pattern) vs. rolling randomness insideCell.__init__. Passing aMinePlaceradds one tiny interface, but unlocks deterministicFixedMinePlacerunit tests, seeded bug replays, and whole-board rules like safe-first-click without changingCellorBoard. - Eager layout generation at init vs. lazy generation on first click. Generating mines in
__init__matches the prompt and makesmine_countknown immediately; deferring generation until the firstclick(r, c)adds an "uninitialized" state, which is the trade-off required if a product wants the player's first click guaranteed safe. - Structured
ClickResultreturn values for bad clicks vs. raising exceptions. RaisingValueErrorinGame.__init__catches broken probability grids immediately, whereas returningOutcome.INVALID/NO_CHANGE/GAME_OVERon misclicks lets UI event loops handle everyday user clicks cleanly withouttry / exceptblocks. - Iterative queue BFS +
safe_leftcounter vs. recursive DFS + full-board win scan. An explicitdequeavoids Python's 1,000-frame recursion crash on large empty regions, and decrementingsafe_leftchecks for victory inO(1)time per click instead of re-scanning allR x Ccells after every move. Cellobjects with__slots__vs. flat byte arrays. Per-cellCellinstances (~64–72 bytes each) make object-oriented logic clean and readable for normal boards, while three flatbytearraybuffers (3 bytes per cell) can sit behind the exact sameBoardmethods if scaling to million-cell grids.
Common mistakes
- Calling
random.random()directly insideCell.__init__. Hard-coding global randomness inside constructors makes deterministic unit tests and replay logs impossible without monkey-patching Python'srandommodule. - Using
random.random() <= probinstead of< prob. Becauserandom.random()generates[0.0, 1.0)(which includes0.0),<=has a tiny chance of placing a mine on a cell whose probability was explicitly0.0! - Forgetting Python's negative-index wraparound and
bool-is-intquirk. Without explicit0 <= r < rowsandtype(r) is intchecks,click(-1, 0)silently reveals the bottom-left cell viaself.cells[-1][0]andclick(True, 0)clicks row1. - Marking cells revealed on dequeue instead of enqueue during flood-fill. Waiting until
queue.popleft()lets multiple adjacent zero-cells push the same hidden neighbor into the queue repeatedly, inflatinglen(revealed)and corruptingsafe_left. - Continuing flood-fill expansion past numbered cells (
adjacent_mines > 0). Numbered cells must be revealed as the visible border of an empty region, but their neighbors must never be auto-expanded or the cascade will detonate adjacent mines. - Coupling
print()directly insideclick()or storing ASCII symbols insideCell. Mixing presentation into domain state forces rule changes whenever you add a GUI, JSON API, or unit assertions.
Follow-up questions
- How would your class design support chording—clicking a revealed clue number to uncover all unflagged neighbors once enough flags are placed? Add a
chord(r, c)method onGame: verify the match isIN_PROGRESS,(r, c)isREVEALEDwithadjacent_mines > 0, and the count ofFLAGGEDneighbors around(r, c)equalscell.adjacent_mines(otherwise returnOutcome.NO_CHANGE). Then iterate over everyHIDDENneighbor: if any of them holds a mine (meaning the player flagged the wrong square!), reveal that mine and transition toLOST; otherwise invokeboard.reveal_fromon each still-HIDDENneighbor, collect all newly uncovered coordinates, and decrementsafe_leftfor the victory check. NeitherCell,Board, norTextRendererneeds a single line of change. - How could you add a hint service that computes each unrevealed tile's updated mine probability conditioned on the clue numbers currently visible? Introduce a read-only
ProbabilityAdvisorcollaborator that calculates each hidden tile's posterior probability (its updated odds after conditioning on every revealed clue number). Hidden tiles that touch zero revealed clues keep their initial priorcell.probbecause startup coin flips were independent, whereas hidden tiles bordering revealed clues split into connected frontier components where valid boolean mine assignments satisfying every clue are weighted byproduct(p for mines) * product(1 - p for safe)and normalized. When a frontier component grows past ~25 tiles, the advisor switches from exact enumeration to Monte Carlo sampling so latency stays bounded. - What changes are needed to support move-by-move undo and deterministic replay of an entire session? Because
ClickResult.revealedalready records the exact list of(r, c)coordinates uncovered on each move, pushing command entries onto ahistorystack makesundo()clean: reset every tile inresult.revealedback toHIDDEN, restorestatus = IN_PROGRESS, and addlen(result.revealed)back tosafe_leftonly when the reverted outcome wasREVEALEDorWON(never onHIT_MINE, since detonating a mine did not decrementsafe_left!). For full deterministic replays, persist(probs, rng_seed, action_log)at match start—re-creatingBernoulliMinePlacer(random.Random(rng_seed))and replaying the recorded(click/flag, r, c)calls reproduces the identical board at every step.
Follow-up questions
- How would your class design support chording—clicking a revealed clue number to uncover all unflagged neighbors once enough flags are placed?
- How could you add a hint service that computes each unrevealed tile's updated mine probability conditioned on the clue numbers currently visible?
- What changes are needed to support move-by-move undo and deterministic replay of an entire session?
Similar questions
- Asynchronous Courier Location Tracking Backend
- Minesweeper Click Resolution and Board Rendering
- Grid State Update for a Minesweeper Click
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform