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:

  1. Render or print the player-visible board at any point in a session, and
  2. 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 prob values 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

  1. 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:

    1. Clean class boundaries: Does each class have one clear job, or is everything tangled inside one giant Minesweeper class?
    2. 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?
    3. 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 C match from a 2D grid probs whose 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 Game from the outside rather than hard-coding global random or print inside 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 takes O(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 Board or Cell.

    Clarifying assumptions

    • Independent per-cell probabilities: Each cell (r, c) conducts an independent Bernoulli trial—a single weighted coin flip that lands True (mine) with probability probs[r][c] and False (safe) with probability 1 - probs[r][c]. Because flips are independent, the total mine count varies from game to game; Board.mine_count records 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.
  2. 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.
    
  3. Public API and display format

    Game acts as a Facade—the single front-door class that callers (a CLI loop, a web controller, or unit tests) interact with, keeping Board and Cell protected 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, or NaN) is a bug in caller code, so Game(...) raises ValueError immediately 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, so click() returns a structured ClickResult value and leaves the board untouched rather than forcing callers to wrap every click in try / 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() -> str from print_board() -> None keeps formatting pure and lets unit tests compare board snapshots with a plain == assertion instead of capturing sys.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 4 board whose sole mine sits at (2, 1), calling game.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 .
    
  4. 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 hidden
    

    Each class has a single, well-defined responsibility:

    Class Responsibility Collaborators it knows about
    Cell Stores one cell's prob, is_mine, adjacent_mines, and state CellState only (knows nothing about coordinates or neighbors)
    Board Owns the R x C grid, bounds checks, 8-direction neighbor lookup, initial neighbor counts, and BFS flood-fill Cell
    MinePlacer (Strategy) Converts probs (R x C floats) into mine_layout (R x C booleans) Pure numbers / injected random.Random
    Game (Facade) Enforces turn rules, GameStatus, safe_left win counter, click(), toggle_flag(), and delegates rendering Board, MinePlacer, TextRenderer
    TextRenderer Turns Board read-only state into a printable string Board, Cell (read-only)
  5. 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())
    
  6. Deep dive 1: generating the initial mine layout from probabilities

    How each cell's prob becomes a boolean mine decision. For each cell with probability p, we draw a uniform floating-point number u in [0.0, 1.0) (including 0.0, strictly excluding 1.0) and place a mine when u < p. Notice why strict < (never <=) is essential at the two boundaries:

    • When p = 0.0, no draw in [0.0, 1.0) satisfies u < 0.0, so a 0.0 cell is never a mine. (Writing u <= p would wrongly place a mine if random() returned 0.0!)
    • When p = 1.0, every draw in [0.0, 1.0) satisfies u < 1.0, so a 1.0 cell is always a mine.

    Why MinePlacer rolls the dice instead of Cell.__init__. If Cell(prob) called global random.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. Extracting MinePlacer applies 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_probs rejects empty grids, jagged rows, booleans (isinstance(True, int) is True in Python!), strings, out-of-range numbers, and float('nan'). Writing the range check as not (0.0 <= p <= 1.0) automatically catches NaN because every comparison involving NaN evaluates to False:

    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 Cell states and precomputing neighbor counts. Once mine_layout is chosen, Board.__init__ creates all R x C hidden Cell objects and computes adjacent_mines in a single O(R * C) pass: whenever (r, c) is a mine, it adds +1 to 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 result
    

    Optional policy extension: If an interviewer asks for guaranteed first-click safety, Game simply defers calling placer.place(probs) until the first click(r0, c0) arrives, passing safe_cells={(r0, c0)} so layout[r0][c0] is forced to False while every other cell still flips independently with its original prob.

  7. Deep dive 2: click state transitions, flood fill, and edge cases

    Every user action moves GameStatus and CellState along 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:

    1. status != IN_PROGRESS -> GAME_OVER: Freezes the board once won or lost.
    2. Coordinate validation -> INVALID: Must check type(r) is int (rejecting floats like 1.5 and booleans like True) and 0 <= r < rows explicitly—because in Python, self.cells[-1][0] would otherwise silently index the bottom row!
    3. state == REVEALED -> NO_CHANGE: Makes duplicate clicks idempotent no-ops.
    4. state == FLAGGED -> NO_CHANGE: Protects flagged cells against misclicks until explicitly unflagged.
    5. cell.is_mine -> HIT_MINE: Reveals the clicked mine and sets status = LOST.
    6. 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), subtracts len(revealed) from self.safe_left, and transitions to WON if safe_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 = REVEALED at enqueue time, not dequeue time: If we waited until popping from the queue to mark a cell revealed, up to 8 neighboring 0-cells could push the exact same hidden coordinate onto the queue before it was popped, causing duplicate entries in revealed and corrupting safe_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 revealed
    
  8. Deep 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 == 3
    

    Layered test plan:

    • Board unit tests: Verify neighbor counts at corners (3), edges (5), and interior (8); verify 1 x 1 boards; run reveal_from on an empty 1 x 5,000 strip to prove zero RecursionError.
    • Game transition table tests: One assertion per branch (GAME_OVER, INVALID negative/float/bool, REVEALED duplicate, FLAGGED protection, HIT_MINE, partial REVEALED, WON on all-zero board, and all p == 1.0 board where safe_left == 0 and any click loses).
    • BernoulliMinePlacer statistical test: Verify p = 0.0 produces 0 mines across 1,000 trials, p = 1.0 produces 1,000 mines, identical seeds (random.Random(42)) produce identical layouts, and p = 0.5 over N = 10,000 seeded trials lands within 4 standard deviations (4 * sqrt(0.5 * 0.5 / 10000) = ±0.02, which has a false-failure rate of ~0.006%).
  9. 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 same Board public methods, but replace the 2D list of Cell objects (~70 MB) with three flat bytearray buffers (is_mine, adjacent_mines, state) totaling 3 bytes per cell (~3 MB), and add render_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_mines is recomputed on load), so 1M active sessions fit under 200 MB of RAM. Never send is_mine for hidden cells to the browser (anti-cheat), and guard concurrent clicks from two open tabs using a per-game lock or optimistic version counter.

    Edge-case and invalid-input summary:

    Input / Scenario Behavior Why
    Empty grid, ragged rows, p < 0, p > 1, NaN, bool ValueError at Game(...) construction Fail 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 WON safe_left drops from R * C to 0 in one BFS pass
    All cells p = 1.0 (all mines) safe_left starts at 0; any click hits a mine and returns HIT_MINE (LOST) cell.is_mine is checked before safe_left == 0
    Negative (r, c), out-of-bounds, float, bool, str Returns ClickResult(Outcome.INVALID), state unchanged Prevents Python negative-index wraparound (cells[-1])
    Click on revealed or flagged cell Returns ClickResult(Outcome.NO_CHANGE), state unchanged Safe idempotency for double-clicks and misclick protection
    Any click or flag after WON / LOST Returns ClickResult(Outcome.GAME_OVER), state unchanged Terminal game states are immutable

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):

  1. Initialization: Game validates probs, asks the injected MinePlacer to flip a weighted coin (rng.random() < prob) for each cell, and builds Board. Board sets mine_count = 1, precomputes adjacent_mines (1 on (1, 0), (1, 1), and (2, 1), and 0 everywhere else), starts all 9 cells as HIDDEN, and sets Game.safe_left = 9 - 1 = 8.
  2. Clicking a numbered cell (1, 1): Game.click(1, 1) verifies the game is IN_PROGRESS and (1, 1) is in-bounds and HIDDEN. Because adjacent_mines == 1 > 0, Board.reveal_from(1, 1) reveals only (1, 1) and stops immediately; safe_left drops from 8 to 7, and clicking (1, 1) a second time safely returns Outcome.NO_CHANGE.
  3. 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 five 0 cells plus the remaining two 1 border cells ((1, 0) and (2, 1)) while stopping before the mine at (2, 0). safe_left drops from 7 to 0, transitioning Game.status to WON in O(1) time without scanning the board.

Key trade-offs

  • Independent per-cell coin flips (BernoulliMinePlacer) vs. a fixed mine count K. Flipping rng.random() < prob independently per cell honors each cell's exact prob value 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 read board.mine_count rather than sum(probs). Enforcing an exact total of K mines forces the per-cell probabilities to sum to K, turning prob into a relative weight rather than a true probability.
  • Injecting MinePlacer (Strategy pattern) vs. rolling randomness inside Cell.__init__. Passing a MinePlacer adds one tiny interface, but unlocks deterministic FixedMinePlacer unit tests, seeded bug replays, and whole-board rules like safe-first-click without changing Cell or Board.
  • Eager layout generation at init vs. lazy generation on first click. Generating mines in __init__ matches the prompt and makes mine_count known immediately; deferring generation until the first click(r, c) adds an "uninitialized" state, which is the trade-off required if a product wants the player's first click guaranteed safe.
  • Structured ClickResult return values for bad clicks vs. raising exceptions. Raising ValueError in Game.__init__ catches broken probability grids immediately, whereas returning Outcome.INVALID / NO_CHANGE / GAME_OVER on misclicks lets UI event loops handle everyday user clicks cleanly without try / except blocks.
  • Iterative queue BFS + safe_left counter vs. recursive DFS + full-board win scan. An explicit deque avoids Python's 1,000-frame recursion crash on large empty regions, and decrementing safe_left checks for victory in O(1) time per click instead of re-scanning all R x C cells after every move.
  • Cell objects with __slots__ vs. flat byte arrays. Per-cell Cell instances (~64–72 bytes each) make object-oriented logic clean and readable for normal boards, while three flat bytearray buffers (3 bytes per cell) can sit behind the exact same Board methods if scaling to million-cell grids.

Common mistakes

  • Calling random.random() directly inside Cell.__init__. Hard-coding global randomness inside constructors makes deterministic unit tests and replay logs impossible without monkey-patching Python's random module.
  • Using random.random() <= prob instead of < prob. Because random.random() generates [0.0, 1.0) (which includes 0.0), <= has a tiny chance of placing a mine on a cell whose probability was explicitly 0.0!
  • Forgetting Python's negative-index wraparound and bool-is-int quirk. Without explicit 0 <= r < rows and type(r) is int checks, click(-1, 0) silently reveals the bottom-left cell via self.cells[-1][0] and click(True, 0) clicks row 1.
  • 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, inflating len(revealed) and corrupting safe_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 inside click() or storing ASCII symbols inside Cell. 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 on Game: verify the match is IN_PROGRESS, (r, c) is REVEALED with adjacent_mines > 0, and the count of FLAGGED neighbors around (r, c) equals cell.adjacent_mines (otherwise return Outcome.NO_CHANGE). Then iterate over every HIDDEN neighbor: if any of them holds a mine (meaning the player flagged the wrong square!), reveal that mine and transition to LOST; otherwise invoke board.reveal_from on each still-HIDDEN neighbor, collect all newly uncovered coordinates, and decrement safe_left for the victory check. Neither Cell, Board, nor TextRenderer needs 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 ProbabilityAdvisor collaborator 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 prior cell.prob because 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 by product(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.revealed already records the exact list of (r, c) coordinates uncovered on each move, pushing command entries onto a history stack makes undo() clean: reset every tile in result.revealed back to HIDDEN, restore status = IN_PROGRESS, and add len(result.revealed) back to safe_left only when the reverted outcome was REVEALED or WON (never on HIT_MINE, since detonating a mine did not decrement safe_left!). For full deterministic replays, persist (probs, rng_seed, action_log) at match start—re-creating BernoulliMinePlacer(random.Random(rng_seed)) and replaying the recorded (click/flag, r, c) calls reproduces the identical board at every step.

Follow-up questions

Similar questions

More Nash AI interview questions

All 4 Nash AI questions →