Object-Oriented Design of a Minesweeper Game with Per-Cell Mine Probabilities
System DesignModel answerLast updated
Design an OO Minesweeper where each cell carries an independent mine probability, covering initialization, class model, click/print APIs, state transitions, and testability.
You are asked to design (in object-oriented terms, with code-level APIs) a single-player Minesweeper game played on a rectangular grid of cells.
The twist: at construction time the caller supplies, for every cell, a probability prob in [0, 1] representing the independent chance that the cell is a mine. Your design must explain:
- How those per-cell probabilities drive generation of the actual mine layout and the initial cell states.
- The core classes (game, board, cell, plus any collaborators), each one's responsibilities, the relationships between them, and the public APIs for:
- (a) printing the current visible board state, and
- (b) handling a user click.
- The high-level state transitions for a click: losing when a mine is hit, otherwise the reveal behavior (flood reveal for zero-adjacent-mine cells) delegated to the board's algorithm.
- How invalid clicks (out of bounds) and duplicate clicks (already revealed or flagged) are handled.
- How the design stays maintainable and testable despite the randomness.
Assume in-memory, single-player operation; boards can be large (up to roughly 10^6 cells), so reveal logic must not be naive recursion. You may add flagging as a cheap extension.
Hints
Hint 1
Separate the decision of *where the mines are* from the board itself — an injected layout strategy lets you swap random generation for a fixed mask in tests.
Hint 2
Precompute each cell's adjacent-mine count once at construction so clicks are pure state transitions, not repeated scans.
Hint 3
Model the game as an explicit status enum (in progress / won / lost) and return a result enum from click rather than printing or throwing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements I would confirm first
- Grid
R x C; aprobsmatrix of the same shape, each value in[0, 1], rectangle-valued. - One action to start with:
click(r, c). Flagging is a cheap add-on I would include. - Losing: clicking a mine. Winning: every non-mine cell revealed. Zero-adjacent-mine cell triggers a flood reveal.
- Display: hidden cells, flags, revealed numbers, and mines after a loss.
- Scale: ~10^6 cells max, so reveal must be iterative and cost O(cells actually revealed).
- I would raise, but default to "no," guaranteeing the first click is safe: resampling after the first click silently changes the caller's specified distribution.
2. Class model
| Class | Responsibility |
|---|---|
Cell | Data only: is_mine, adjacent_mines, state (HIDDEN / REVEALED / FLAGGED). Knows nothing about the board or game outcome. |
Board | Owns the Cell grid. Bounds checks, neighbor iteration, adjacency precomputation, flood reveal, count of unrevealed safe cells. |
MineLayoutStrategy | Decides mine placement. BernoulliLayout(rng) samples independently; FixedLayout(mask) returns a fixed mask for tests. |
Game | Facade + state machine (IN_PROGRESS / WON / LOST). Validates input, converts board outcomes into a ClickResult. |
BoardRenderer | Turns a board into text so rendering can change without touching model logic. |
Relationships: Game has-a Board; Board has-many Cell; Board is constructed with a layout strategy; BoardRenderer reads a Board. Dependencies point one way only. The RNG is injected, never a global, so a fixed seed makes everything reproducible.
3. Turning probabilities into a layout
- Validate the matrix: non-empty, rectangular, every value in
[0, 1]. Raise on malformed input (that is a caller bug). - For each cell, draw
u = rng.random()and setis_mine = u < prob[r][c]. This is an independent Bernoulli trial per cell; expected mine count issum(probs);0means never a mine and1means always. - In one O(R·C) pass, compute each cell's
adjacent_minesover its eight neighbors. - Initialize all cells to HIDDEN.
- Count unrevealed safe cells. If zero (all mines), the game cannot be won — I would either reject the board or define any click as an immediate loss, and I would say which.
4. Public APIs
class Game:
def __init__(self, probs, layout=None): ...
def click(self, r, c) -> ClickResult: ...
def toggle_flag(self, r, c) -> ClickResult: ...
def print_board(self) -> None: ...
@property
def status(self) -> GameStatus: ...
ClickResult ∈ {INVALID, NO_OP, GAME_OVER, REVEALED, LOST, WON}. Returning a result beats printing or raising for ordinary play, because the caller (UI or test) decides the reaction. Exceptions are reserved for programmer errors like a ragged probs matrix.
5. Click state machine
click(r, c):
if status != IN_PROGRESS -> GAME_OVER (no change)
if out of bounds -> INVALID
if cell REVEALED or FLAGGED -> NO_OP (idempotent duplicate)
if cell.is_mine -> reveal, status = LOST -> LOST
else k = board.reveal_from(r, c)
if safe_remaining - k == 0 -> status = WON -> WON
else -> REVEALED
reveal_from runs an iterative BFS: reveal the start cell; if its adjacent_mines == 0, enqueue hidden, non-flagged neighbors; each cell is revealed at most once, so a click costs O(cells revealed) and the whole game is O(R·C) total. It returns the count of newly revealed cells so the win check in Game is O(1).
6. Testability and maintainability
- Determinism: inject
FixedLayoutor a seeded RNG; no flaky tests. - Isolation:
CellandBoardcan be tested withoutGame;Game's transitions can be tested with a scripted board. - Invariants:
safe_remainingalways equals the number of hidden non-mine cells — assert it in tests after random click sequences. - Renderer separation: snapshot-test
print_board()output independently of click logic. - Edge cases to test: out-of-bounds, re-click of a revealed cell, click after game over, all-mines board, 1×1 board,
probof 0 and 1, a flood reveal spanning an entire empty board (stack safety).
7. Trade-offs and pitfalls
- Recursive flood fill is the classic mistake: it blows the stack on a large empty board.
- Recomputing adjacency on every click is wasteful; precompute once.
- Raising exceptions for duplicate clicks fights normal UI behavior; use NO_OP.
- Silently guaranteeing a safe first click changes the caller's distribution — make it an explicit option, not a default.
- Global RNG makes bugs invisible and tests flaky — inject it.
That gives clean boundaries, an explicit state machine, and deterministic tests for a game that is otherwise random by nature.