The goal is to reveal every cell that does not hold a mine. A revealed number counts the mines among its eight neighbouring cells.
Click a covered cell to reveal it. The first click is always safe. Right-click, or use FLAG MODE, to flag a cell that is suspected of holding a mine. Flags are notes and do not change the rules.
Press AI STEP to let the agent reveal every cell it can prove safe, or one guess when nothing is certain. AI PLAY repeats those steps until the board is decided.
The agent treats each revealed number as a constraint: a statement that a fixed number of mines lie among the covered cells next to it. It makes every move that counting proves safe. When nothing is proven, it guesses the covered cell with the lowest exact chance of being a mine, counted over every layout of mines that fits the numbers and the mine count.
Each cell has up to eight neighbours, the cells that touch it sideways, up, down or diagonally. A mine is a cell that holds one. A covered cell that is opened shows its number, the count of mines among its neighbours.12
Here N(c) is the set of neighbours of cell c, and m_n is 1 when cell n holds a mine and 0 otherwise. A number of 0 means that no neighbour is a mine.
The mines are placed after the first click, not before it. The clicked cell and its neighbours are kept clear, so the first reveal always opens an area. The other mines are placed uniformly at random on the remaining cells.4
function PLACE-MINES(first):
pool ← the cells that are not first and not neighbours of first
choose the mine cells uniformly at random from pool
function PLACE-MINES(first):
clear ← {first} together with the neighbours of first
pool ← the cells that are not in clear, in row-major order
k ← 0
repeat mines times:
j ← k + a random integer from 0 to |pool| − k − 1 # partial Fisher-Yates shuffle
swap pool[k] and pool[j]
k ← k + 1
mine-cells ← the first mines cells of pool
The full version is a partial Fisher–Yates shuffle. After k swaps, the first k cells of the pool are a uniform random choice, so each set of mine cells is equally likely. Stopping after mines swaps saves the work of shuffling the rest.
Flood fill. A cell whose number is 0 has no mines around it, so opening it opens all of its neighbours. A neighbour that is also 0 opens its own neighbours in turn. The opening spreads breadth first: cells are opened in the order they were queued, using a first-in, first-out list. A mine ends the game. The game is won when every cell that is not a mine is open.5
function REVEAL(cell):
if cell is covered and not flagged:
if no mines are placed yet: PLACE-MINES(cell) # the first click is always safe
if cell holds a mine: the game is lost
otherwise:
open cell with its number
queue ← [cell]
while queue is not empty: # breadth first
here ← the first item of queue, removed
if here shows 0: open each covered, unflagged neighbour of here and queue it
function REVEAL(cell):
if the game is over, or cell is not covered, or cell is flagged: return nothing
if no mines are placed yet: PLACE-MINES(cell)
if cell holds a mine:
the game is lost on cell
return [cell]
value[cell] ← the number of mines among the neighbours of cell
opened ← [cell]
queue ← [cell]
while queue is not empty:
here ← the first item of queue, removed # breadth first
if value[here] ≠ 0: continue # only zeros spread the opening
for each neighbour n of here:
if n is covered and n is not flagged:
value[n] ← the number of mines among the neighbours of n
opened ← opened + [n]
queue ← queue + [n]
if the number of open cells = rows × cols − mines:
the game is won
return opened
The full version queues each cell when it is opened, and checks value[here] when the cell leaves the queue. A cell is therefore expanded only if it is still zero at that moment. A flagged cell is never opened by a reveal, which is why a flag protects a cell from an accidental click.
The random agent chooses one covered cell uniformly at random, with no reasoning. It is the floor that the other agents are measured against.6 On beginner boards it wins 0.0% of 1,000 seeded games (0 wins) and needs 3.36 guesses per game.7
The agent works at one of three levels. Level 1 uses single cells. Level 2 adds the constraint groups and the mine count. Level 3 adds exact probabilities. The page's AI STEP and AI PLAY run at level 3.8
For a revealed number at cell i, the need is the number of mines still missing around it. A known mine is a covered cell that has been proven to hold a mine, and a known-safe cell is one that has been proven clear. The open neighbours of i are its covered neighbours that are neither.9
Here v_i is the number shown at i, N(i) is the set of its neighbours, K is the set of known mines, S is the set of known-safe cells, and |\cdot| is the size of a set. If a number needs 0 more mines, its open neighbours are safe. If it needs as many mines as it has open neighbours, they are all mines. Each new fact can change the need of another number, so the rules repeat until nothing changes, which is a fixpoint.10
Example. A 1 with two open neighbours and no known mine needs 1 and has 2 open cells, so neither rule applies. If one of those two is later proven a mine, the need drops to 0, and the other neighbour is proven safe.
function RULE-PASS(view):
repeat until nothing changes:
for each revealed number v at cell i:
need ← v − the known mines among its neighbours
if need = 0:
mark its open neighbours safe # its mines are all placed
otherwise if need = the number of open neighbours:
mark its open neighbours as mines # every open neighbour is a mine
function RULE-PASS(view):
KNOWN-MINES ← empty
KNOWN-SAFE ← empty
repeat until nothing changes:
for each revealed number v at cell i:
covered ← the covered neighbours of i
open ← the cells of covered that are in neither KNOWN-MINES nor KNOWN-SAFE
if open is empty: continue # nothing left to decide here
hits ← the number of cells of covered that are in KNOWN-MINES
need ← v − hits
if need = 0: # every mine i wants is placed
add every cell of open to KNOWN-SAFE
otherwise if need = the number of cells in open: # every open cell is a mine
add every cell of open to KNOWN-MINES
return KNOWN-MINES, KNOWN-SAFE
The full version recomputes open and hits for every number on every pass. Each pass that adds a fact sets the flag that drives the next pass, and the loop stops on the first pass that adds nothing. The loop always stops, because each pass that continues adds at least one cell to KNOWN-MINES or KNOWN-SAFE, and there are only so many covered cells.
If no cell is proven, the rules agent guesses uniformly among the covered cells that are not proven mines.12
Each revealed number that still has open neighbours gives one constraint: exactly \text{need}_i of its open cells are mines. Write x_n = 1 when covered cell n is a mine and x_n = 0 when it is safe. The constraint is then a linear equation in those values.13
Here O_i is the set of open cells of number i. Two constraints that share an open cell are linked, and a set of linked constraints forms a component, a group that has to be solved together. Components with no shared cell are independent. Once the total number of mines is fixed, each component can be counted on its own.14
A component is counted by backtracking, a depth-first search that assigns one cell at a time and abandons a branch as soon as a constraint cannot be met. The cells are visited in row-major order. Each search state is the index of the next cell together with the residual need of every open constraint, the number of mines it still requires. Two partial layouts that reach the same state have the same future, so the count is stored under that state and reused. This is memoization.15
The count is kept by mine total. A[k] is the number of layouts that use exactly k mines. Independent components are combined by convolution, a sum of products over all ways of splitting the total:
Here A and B are layout-count tables of two independent components, and (A \ast B)[k] is the number of layouts of both together that use k mines.
function COUNT(i, needs): # cells i onward; needs = mines each open constraint still wants
if i is past the last cell: return [1]
if (i, needs) was seen: return its stored counts
counts ← zeros
for x in 0 and 1: # cell i is safe, or a mine
if every constraint on cell i still fits x:
counts ← counts + COUNT(i + 1, updated needs), shifted by x
store counts for (i, needs)
return counts
function COUNT-LAYOUTS(order, constraints, fixed): # order: the cells, row-major
m ← the number of cells in order
for each constraint j:
members[j] ← the positions in order of its cells, sorted
needs[j] ← its need
for each position i from 0 to m:
open-at[i] ← the constraints j with first member < i ≤ last member
for each position i:
touch[i] ← (j, the number of members of j after i) for each constraint j that has cell i
memo ← empty
return SOLVE(0, empty state)
function SOLVE(i, state): # state: the residual need of each constraint in open-at[i]
if i = m: return [1] # every cell is assigned, and every constraint is closed at 0
if (i, state) is in memo: return memo[(i, state)]
spend (m − i) + |open-at[i]| + |touch[i]| units of work # raises budget exceeded
cur ← the residual need of each constraint in open-at[i], taken from state
values ← [0, 1]
if fixed is set on cell i: values ← [its forced value]
out ← zeros, one for each count from 0 to m − i
for each x in values:
nxt ← empty
for each (j, after) in touch[i]:
r ← (cur[j] if j is open, otherwise needs[j]) − x
if r < 0 or r > after: skip x # too many mines, or too few cells left to supply them
nxt[j] ← r
child ← for each j in open-at[i + 1]: nxt[j] if set, otherwise cur[j]
for each k with value v in SOLVE(i + 1, child):
out[k + x] ← out[k + x] + v
memo[(i, state)] ← out
return out
The full version has the same states as the simple one, with the bookkeeping spelled out. A constraint that has not started yet still has its full need. The check r > after prunes a branch early, when the cells left in the constraint cannot supply the mines it still wants. The fixed argument forces one cell to a value, which gives the layouts in which that cell is a mine. The work is charged to the budget in the next section.
Example. Take three cells in row-major order, a, b, c, with the constraints x_a + x_b = 1 and x_b + x_c = 1. If b is a mine, then a and c are safe, giving one mine in total. If b is safe, then a and c are mines, giving two. So the component's table is [0, 1, 1].
A layout is a full assignment of mines to the covered cells that satisfies every constraint and uses the board's mine count. Every layout is treated as equally likely, so a cell's probability is the share of layouts that put a mine on it. The weight of a set of layouts is simply how many there are. All weights are integers, so comparisons are exact, and the one division is done at the end.
The frontier is the set of cells that appear in some constraint. The interior is the rest of the covered cells, which touch no number. Let R be the mines not yet proven, and let t be the number of mines on the frontier. The other R - t mines fall among the interior's cells in \binom{|I|}{R-t} ways. \binom{n}{k} is the binomial coefficient, the number of ways to choose k of n cells. It is 0 when k is negative or larger than n.17
Here W is the weight of all layouts, A_1 \ldots A_c are the layout-count tables of the c components, G[t] is the number of ways the frontier can hold t mines, and I is the interior.
For a cell c on the frontier of component K, the weight of the layouts in which c is a mine is built from that component's with-mine counts and from the other components, combined:
Here A^{(c)}_K[j] is the number of layouts of K that have c as a mine and j mines in total. B_K is the convolution of the layout tables of all the other components. R_K[j] is the weight of the full layouts in which K uses j mines.
Interior cells are interchangeable, so each has the same weight. For a fixed count k of interior mines, a given interior cell is a mine in \binom{|I|-1}{k-1} of the \binom{|I|}{k} placements. Summing over the possible values of k, weighted by G[t], gives:
Finally, the probability of a covered cell c is its weight divided by the total weight:
Here N_c is the weight of the layouts in which c is a mine, and W is the weight of all layouts. If N_c = 0, no layout puts a mine on c, so c is proven safe. If N_c = W, every layout does, so c is proven a mine. These are the proofs that AI STEP plays.22
Example. Suppose three interior cells remain and one mine is left among them. Then \binom{3}{1} = 3 layouts exist. Each cell is a mine in \binom{2}{0} = 1 of them, so its probability is 1/3.
function ANALYSE(view):
prove every cell that the single-cell rules settle
group the numbers into components that share covered cells
count the layouts of each component, by mine total
combine the components, the interior and the mine count
for each covered cell:
probability ← the layouts with a mine there ÷ all layouts
a cell that no layout fills with a mine is safe; one that every layout fills is a mine
function ANALYSE(view, level):
KNOWN-MINES, KNOWN-SAFE ← RULE-PASS(view)
if level = 1: return the proofs
try:
return EXACT(view, level, KNOWN-MINES, KNOWN-SAFE)
on budget exceeded:
return ESTIMATE(view, level, KNOWN-MINES, KNOWN-SAFE)
function EXACT(view, level, KNOWN-MINES, KNOWN-SAFE):
constraints ← one (open cells, need) for each revealed number with open cells
frontier ← the cells that appear in some constraint
interior ← the covered cells in neither frontier, KNOWN-MINES nor KNOWN-SAFE
remaining ← mines − |KNOWN-MINES|
components ← the constraints, grouped by shared cells
for each component K:
total[K] ← COUNT-LAYOUTS(cells of K, constraints of K)
for each cell c of K:
withmine[K][c] ← COUNT-LAYOUTS(cells of K, constraints of K, fixed = (c, mine))
G ← [1]
for each component K: G ← G ∗ total[K]
weight(t) ← C(|interior|, remaining − t)
total ← the sum over t of G[t] × weight(t)
if total = 0: raise ValueError("the numbers and the mine count cannot all be true")
for each component K:
others ← [1]
for each other component L: others ← others ∗ total[L]
R[j] ← the sum over s of others[s] × weight(j + s), for each j
for each cell c of K:
numerator[c] ← the sum over j of withmine[K][c][j] × R[j]
for each interior cell c:
numerator[c] ← the sum over t of G[t] × C(|interior| − 1, remaining − t − 1)
for each covered cell c:
if numerator[c] = 0: c is safe
otherwise if numerator[c] = total: c is a mine
return the analysis, with numerator and total
The full version is the exact count, step by step. Each component is counted twice: once with no restriction, and once for every frontier cell forced to a mine. The per-component results are cached on the component's cells and constraints, so an unchanged component costs nothing on the next move. The check total = 0 is the only place where contradictory numbers are reported as an error, since the counts are the only thing that can see that no layout fits.
The probability of a frontier cell uses the other components only through their combined table others. Since the components are independent once the total is fixed, the mines that the others take are summed over every split that is possible.
Ties. Ties are common on the interior, where every cell has the same weight. The agent guesses the covered cell with the lowest N_c. The tie-break prefers the cell with the most covered neighbours, because revealing it can open the most covered cells if it is a zero. The final tie-break is the lower cell number. Exact weights are compared as integers, so two cells never tie through rounding.25
function BEST-GUESS(analysis):
return the covered cell with the lowest mine probability
# ties: most covered neighbours first, then the lower cell number
function BEST-GUESS(analysis):
if analysis is exact:
candidates ← the covered cells that have a numerator
if candidates is empty: raise ValueError
return the c in candidates with the smallest (numerator[c], −unknown-neighbours(c), c)
candidates ← the covered cells that have an estimate
if candidates is empty: raise ValueError
return the c in candidates with the smallest (estimate[c], −unknown-neighbours(c), c)
The full version compares a tuple of three keys. Negating the neighbour count makes a larger count sort first, and the cell number at the end makes the choice deterministic. In estimate mode the same keys are used with the estimated probabilities.
The exact count can grow quickly on a wide frontier with long chains of numbers. Every new memo state and every convolution is charged to a work budget of 2,000,000 units, where a unit is roughly one Python operation. The budget is set by WORK_BUDGET.2627 When it runs out, the analysis keeps the single-cell proofs, which were found before counting, and reports estimated probabilities instead. The reply carries exact: false, and the page says so. An estimate never proves a cell.28
Here K_c is the set of constraints that contain frontier cell c, O_k is the open cells of constraint k, and \hat{p}_c is the estimated mine probability of c. A frontier cell gets the average density, the need over the number of open cells, of the constraints it sits in. The interior cells share the mines that the frontier estimates do not account for, spread evenly.
function ESTIMATE(view, KNOWN-MINES, KNOWN-SAFE):
keep the single-cell proofs
for each covered cell next to a number:
estimate ← the average, over its constraints, of need ÷ number of open cells
share the mines not accounted for evenly among the interior cells
function ESTIMATE(view, KNOWN-MINES, KNOWN-SAFE):
constraints ← the constraints of EXACT
frontier ← the cells that appear in some constraint
interior ← the covered cells in neither frontier, KNOWN-MINES nor KNOWN-SAFE
remaining ← mines − |KNOWN-MINES|
density ← an empty map from cell to a list of numbers
for each constraint (cells, need):
for each cell c in cells: append need ÷ |cells| to density[c]
for each cell c in density:
estimate[c] ← min(1, the average of density[c])
if interior is not empty:
left ← remaining − the sum of estimate over the frontier
share ← min(1, max(0, left ÷ |interior|))
for each interior cell c: estimate[c] ← share
return the analysis, with exact false and the estimates
The full version builds the same constraints as the exact count, so both see the same frontier and interior. The min(1, …) keeps each estimate a probability. The estimates shade the heat map and rank guesses, and best_guess uses the same tie-break as the exact count. An estimate never proves a cell.
AI STEP asks the server for the level-3 analysis of the board as it stands, and then applies it. Each certain mine is marked as proven. Every cell proven safe is revealed, one beat at a time, and its reason is logged. If nothing is proven, the agent reveals its lowest-probability guess. A guess also clears any flag on its cell, as a certain move does.31
function AI-STEP():
a ← the analysis of the board from the server, at level 3
mark the certain mines in a as proven
if a has cells proven safe:
for each proven safe cell c, one beat at a time:
REVEAL(c) # a flood fill may open more cells
otherwise if a has a guess g:
REVEAL(g) # the lowest mine probability on the board
function AI-STEP():
if the game is over or a step is running: return false
gen ← the current board number
busy ← true
try:
a ← the analysis of the board from the server, at level 3
on error:
busy ← false
return false
if gen is not the current board number: return false # a new board started meanwhile
add every certain mine in a to proven
if a has cells proven safe:
rounds ← rounds + 1
beat ← max(20, min(110, round(900 ÷ number of safe cells))) # milliseconds
for each cell c in a.safe:
if the game is over or gen is not the current board number: stop
if c is open already: continue # opened by an earlier flood fill
remove any flag on c
REVEAL(c)
wait beat milliseconds
otherwise if a has a guess g:
guesses ← guesses + 1
remove any flag on g
REVEAL(g)
otherwise:
log "nothing left to decide"
busy ← false
return true
The full version has two guards and a pacing rule. The busy flag stops a second step from starting while one is running. The board number gen stops a reply, or a running round, from acting on a board that has since been replaced. The beat is shorter when there are more cells, so a long round reads as a sequence without taking long. AI PLAY repeats AI STEP until the board is decided, the player presses STOP, or a request fails, and it makes one server request per round.
| Constant or rule | What it sets | Value |
|---|---|---|
| Board sizes | Rows, columns and mines of each preset | 9×9 with 10 mines; 16×16 with 40; 16 rows × 30 columns with 99 |
| WORK_BUDGET | Units of work for one exact count | 2,000,000 |
| _CACHE_LIMIT | Component results kept; the cache is cleared when full | 4,096 |
| Tie-break 1 | Lowest weight (exact) or lowest estimate | Smallest value |
| Tie-break 2 | Covered neighbours, the most that a reveal could open | More neighbours wins |
| Tie-break 3 | Cell number | Lower number wins |
| First click | The clicked cell and its neighbours are never mines | Rule, no weight |
| BENCH_SEED_BASE | Seed of the first benchmark game; game i uses seed + i | 10,000 |
| GAMES | Benchmark games per size | 1,000; 500; 200 |
| Wilson z | Multiplier for the 95% interval on win rates | 1.96 |
Each of these values is fixed in the code. Nothing was tuned: the probabilities are exact counts, and the proof rules follow from the rules of the game. The tie-breaks were set by hand.323334
The benchmark plays every agent on the same seeded boards, so the comparison is paired. Win rates are shown with a 95% Wilson interval, which behaves better than the normal interval when the rate is near 0 or 1.357
| Agent | Beginner (1,000 games) | Intermediate (500) | Expert (200) |
|---|---|---|---|
| random | 0.0% (0.0–0.4) | 0.0% (0.0–0.8) | 0.0% (0.0–1.9) |
| rules (level 1) | 79.8% (77.2–82.2) | 49.2% (44.8–53.6) | 1.5% (0.5–4.3) |
| csp (level 2) | 96.1% (94.7–97.1) | 85.4% (82.0–88.2) | 39.0% (32.5–45.9) |
| probability (level 3) | 97.5% (96.3–98.3) | 87.8% (84.6–90.4) | 48.5% (41.7–55.4) |
On beginner boards the probability agent wins 97.5% of games, 902 of its wins without a guess. On expert boards it guesses more often than the constraint agent (2.88 per game against 2.29), and it also wins more of its games (48.5% against 39.0%).36