commit d4262f1c5fbc50b362bed742a0ab56d984ff9418
Author: William Lindholm <william@skovde.combitech.se>
Date: Wed, 17 Dec 2025 13:44:08 +0100
First functioning bot
Diffstat:
7 files changed, 879 insertions(+), 0 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,33 @@
+# Python
+__pycache__/
+*.py[cod]
+*$py.class
+.pytest_cache/
+.mypy_cache/
+.ruff_cache/
+
+# Virtual environments
+venv/
+.venv/
+ENV/
+env/
+
+# Playwright
+playwright-report/
+test-results/
+
+# Bot persistent browser profile (cookies/storage)
+.ms_bot_profile/
+
+# Node (if used)
+node_modules/
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+
+# OS / editor
+.DS_Store
+Thumbs.db
+.idea/
+.vscode/
+
diff --git a/ms_bot/README.md b/ms_bot/README.md
@@ -0,0 +1,15 @@
+MinesweeperOnline bot (Playwright + Python)
+
+Run:
+1. Install deps: `pip install -r ms_bot/requirements.txt`
+2. Install browsers: `python -m playwright install`
+3. Start: `python -m ms_bot.bot --headful`
+
+Notes:
+- Defaults to beginner (9x9, 10 mines). Use `--width/--height/--mines` for other sizes.
+- The bot reads DOM square ids like `2_3` and automatically detects the board's coordinate origin (0-based vs 1-based).
+- Squares have ids that begin with digits (e.g. `5_5`), so the bot uses an attribute selector (`[id="5_5"]`) rather than `#5_5`.
+- The bot also attempts to auto-dismiss common cookie/consent popups (and injects CSS to hide known consent containers).
+- Cookie persistence: by default the bot uses a persistent Chromium profile in `.ms_bot_profile` so cookies/localStorage are retained across runs. Disable with `--profile-dir ""`.
+- Stuck guessing: if the board state doesn't change for a few loops, the bot forces a guess (`--stuck-threshold 5`, disable with `--stuck-threshold 0`).
+- Board detection: the bot only uses *visible* `.square` elements to avoid hidden template/ad elements with `square` classes and out-of-range ids.
diff --git a/ms_bot/__init__.py b/ms_bot/__init__.py
@@ -0,0 +1,2 @@
+__all__ = []
+
diff --git a/ms_bot/board.py b/ms_bot/board.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+import re
+from typing import Iterable, Iterator
+
+
+_OPEN_RE = re.compile(r"\bopen(\d)\b")
+
+
+@dataclass(frozen=True)
+class Cell:
+ x: int
+ y: int
+
+
+@dataclass(frozen=True)
+class BoardSnapshot:
+ origin_x: int
+ origin_y: int
+ width: int
+ height: int
+ cells: dict[Cell, object]
+
+ def in_bounds(self, cell: Cell) -> bool:
+ return (
+ self.origin_x <= cell.x < self.origin_x + self.width
+ and self.origin_y <= cell.y < self.origin_y + self.height
+ )
+
+ @property
+ def min_x(self) -> int:
+ return self.origin_x
+
+ @property
+ def min_y(self) -> int:
+ return self.origin_y
+
+ @property
+ def max_x(self) -> int:
+ return self.origin_x + self.width - 1
+
+ @property
+ def max_y(self) -> int:
+ return self.origin_y + self.height - 1
+
+ def neighbors(self, cell: Cell) -> Iterator[Cell]:
+ for dy in (-1, 0, 1):
+ for dx in (-1, 0, 1):
+ if dx == 0 and dy == 0:
+ continue
+ n = Cell(cell.x + dx, cell.y + dy)
+ if self.in_bounds(n):
+ yield n
+
+ def get(self, cell: Cell) -> object:
+ return self.cells.get(cell, "unknown")
+
+ def iter_cells(self) -> Iterable[Cell]:
+ for y in range(self.origin_y, self.origin_y + self.height):
+ for x in range(self.origin_x, self.origin_x + self.width):
+ yield Cell(x, y)
+
+ def covered_cells(self) -> set[Cell]:
+ return {c for c, v in self.cells.items() if v == "covered"}
+
+ def flagged_cells(self) -> set[Cell]:
+ return {c for c, v in self.cells.items() if v == "flagged"}
+
+ def number_cells(self) -> dict[Cell, int]:
+ out: dict[Cell, int] = {}
+ for c, v in self.cells.items():
+ if isinstance(v, int) and 0 <= v <= 8:
+ out[c] = v
+ return out
+
+
+def parse_square_class(class_name: str) -> object:
+ class_name = class_name or ""
+ if "bombflagged" in class_name or "flag" in class_name:
+ return "flagged"
+ m = _OPEN_RE.search(class_name)
+ if m:
+ return int(m.group(1))
+ if "blank" in class_name:
+ return "covered"
+ if "square" in class_name:
+ # Default tile state on minesweeperonline is usually "square blank", but
+ # treat any unrecognized square as covered to stay robust to class changes.
+ return "covered"
+ if "open" in class_name:
+ return 0
+ if "bomb" in class_name:
+ return "mine"
+ return "unknown"
diff --git a/ms_bot/bot.py b/ms_bot/bot.py
@@ -0,0 +1,342 @@
+from __future__ import annotations
+
+import argparse
+import asyncio
+import re
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from playwright.async_api import Page
+
+from .board import BoardSnapshot, Cell, parse_square_class
+from .solver import best_guess, choose_first_click, iter_in_order, solve_step
+
+
+DEFAULT_URL = "https://minesweeperonline.com/#beginner"
+
+_COOKIE_BUTTON_RE = re.compile(
+ r"^(accept|accept all|agree|i agree|ok|okay|got it|consent|allow all)$",
+ re.IGNORECASE,
+)
+
+
+def _parse_cell_id(cell_id: str) -> Cell | None:
+ if not cell_id:
+ return None
+ m = re.match(r"^(\d+)_(\d+)$", cell_id)
+ if not m:
+ return None
+ return Cell(int(m.group(1)), int(m.group(2)))
+
+
+async def read_board(page: "Page", width: int, height: int) -> BoardSnapshot:
+ data: list[dict[str, Any]] = await page.evaluate(
+ """
+ () => Array.from(document.querySelectorAll('div.square[id]'))
+ .map(e => {
+ const r = e.getBoundingClientRect();
+ const s = window.getComputedStyle(e);
+ const visible =
+ r.width > 0 && r.height > 0 &&
+ r.bottom > 0 && r.right > 0 &&
+ r.top < window.innerHeight && r.left < window.innerWidth &&
+ s && s.display !== 'none' && s.visibility !== 'hidden' && s.opacity !== '0';
+ return { id: e.id, className: e.className || '', visible };
+ })
+ .filter(x => x.visible)
+ """
+ )
+ cells: dict[Cell, object] = {}
+ coords: list[Cell] = []
+ for item in data:
+ c = _parse_cell_id(item.get("id", ""))
+ if not c:
+ continue
+ coords.append(c)
+ cells[c] = parse_square_class(item.get("className", ""))
+
+ if coords:
+ origin_x = min(c.x for c in coords)
+ origin_y = min(c.y for c in coords)
+ inferred_w = max(c.x for c in coords) - origin_x + 1
+ inferred_h = max(c.y for c in coords) - origin_y + 1
+ else:
+ origin_x = 0
+ origin_y = 0
+ inferred_w = 0
+ inferred_h = 0
+
+ # Prefer the size inferred from *visible* squares. Passing --width/--height is
+ # still useful for mine counts / difficulty presets, but DOM may contain
+ # hidden "square" nodes (ads/templates) with out-of-range ids.
+ board_w = inferred_w if inferred_w > 0 else width
+ board_h = inferred_h if inferred_h > 0 else height
+ if board_w <= 0 or board_h <= 0:
+ board_w, board_h = (width or 9), (height or 9)
+
+ # Fill missing entries as covered. DOM can omit elements briefly during transitions.
+ for y in range(origin_y, origin_y + board_h):
+ for x in range(origin_x, origin_x + board_w):
+ cells.setdefault(Cell(x, y), "covered")
+
+ return BoardSnapshot(origin_x=origin_x, origin_y=origin_y, width=board_w, height=board_h, cells=cells)
+
+
+async def game_state(page: "Page") -> str:
+ # minesweeperonline uses #face with classes like facesmile/facewin/facedead.
+ face = await page.locator("#face").get_attribute("class")
+ face = face or ""
+ if "facewin" in face:
+ return "win"
+ if "facedead" in face:
+ return "dead"
+ return "playing"
+
+async def _dismiss_common_popups(page: "Page") -> None:
+ # Cookie/consent banners vary by region and provider (Quantcast/OneTrust/etc).
+ # We try (1) clicking common accept/close buttons (also inside iframes) and
+ # (2) injecting CSS to hide known containers.
+ try:
+ await page.add_style_tag(
+ content="""
+ #qc-cmp2-container, .qc-cmp2-container, .qc-cmp2-ui,
+ #onetrust-consent-sdk, .onetrust-pc-dark-filter, .ot-sdk-container,
+ [id*="cookie"][style*="position: fixed"], [class*="cookie"][style*="position: fixed"],
+ [id*="consent"][style*="position: fixed"], [class*="consent"][style*="position: fixed"] {
+ display: none !important;
+ visibility: hidden !important;
+ pointer-events: none !important;
+ }
+ """
+ )
+ except Exception:
+ pass
+
+ async def try_click_accept(root: Any) -> None:
+ candidates = [
+ root.locator('button:has-text("Accept")'),
+ root.locator('button:has-text("I agree")'),
+ root.locator('button:has-text("Agree")'),
+ root.locator('button:has-text("OK")'),
+ root.locator('button:has-text("Got it")'),
+ root.locator('[role="button"]:has-text("Accept")'),
+ root.locator('[aria-label*="close" i]'),
+ root.locator('button[aria-label*="close" i]'),
+ ]
+ for loc in candidates:
+ try:
+ if await loc.first.is_visible(timeout=150):
+ await loc.first.click(timeout=500)
+ return
+ except Exception:
+ continue
+
+ # If roles are wired up, this is often the most reliable.
+ try:
+ btn = root.get_by_role("button").filter(has_text=_COOKIE_BUTTON_RE)
+ if await btn.first.is_visible(timeout=150):
+ await btn.first.click(timeout=500)
+ except Exception:
+ pass
+
+ try:
+ await try_click_accept(page)
+ for frame in page.frames:
+ try:
+ await try_click_accept(frame)
+ except Exception:
+ continue
+ except Exception:
+ pass
+
+
+async def click_cell(page: "Page", cell: Cell, button: str = "left") -> None:
+ # IDs like "5_5" start with a digit which is not a valid CSS id selector
+ # without escaping; use an attribute selector instead.
+ locator = page.locator(f'div.square[id="{cell.x}_{cell.y}"]')
+
+ async def pick_visible(loc: Any) -> Any:
+ try:
+ count = await loc.count()
+ except Exception:
+ return loc.first
+ for i in range(count):
+ item = loc.nth(i)
+ try:
+ if await item.is_visible(timeout=100):
+ return item
+ except Exception:
+ continue
+ return loc.first
+
+ locator = await pick_visible(locator)
+ try:
+ await locator.scroll_into_view_if_needed(timeout=3000)
+ await locator.click(button=button, timeout=3000)
+ except Exception:
+ # Often a cookie banner blocks the first action; dismiss and retry once.
+ await _dismiss_common_popups(page)
+ try:
+ await locator.scroll_into_view_if_needed(timeout=3000)
+ except Exception:
+ pass
+ try:
+ await locator.click(button=button, timeout=3000)
+ except Exception:
+ # Last resort: bypass actionability checks (helpful for overlays/animations).
+ await locator.click(button=button, timeout=3000, force=True)
+
+
+async def run_bot(
+ url: str,
+ width: int,
+ height: int,
+ total_mines: int,
+ headful: bool,
+ slowmo_ms: int,
+ think_ms: int,
+ max_steps: int,
+ profile_dir: str | None,
+ stuck_threshold: int,
+) -> None:
+ from playwright.async_api import async_playwright
+
+ async with async_playwright() as p:
+ if profile_dir:
+ context = await p.chromium.launch_persistent_context(
+ user_data_dir=profile_dir,
+ headless=not headful,
+ slow_mo=slowmo_ms,
+ viewport={"width": 1100, "height": 900},
+ )
+ page = context.pages[0] if context.pages else await context.new_page()
+ else:
+ browser = await p.chromium.launch(headless=not headful, slow_mo=slowmo_ms)
+ context = await browser.new_context(viewport={"width": 1100, "height": 900})
+ page = await context.new_page()
+ page.set_default_timeout(3000)
+ page.set_default_navigation_timeout(3000)
+ await page.add_init_script(
+ "document.addEventListener('contextmenu', e => e.preventDefault());"
+ )
+ await page.goto(url, wait_until="domcontentloaded")
+ await page.wait_for_timeout(500)
+ await _dismiss_common_popups(page)
+
+ steps = 0
+ same_state_steps = 0
+ last_sig: tuple[tuple[tuple[int, int, int], ...], tuple[tuple[int, int], ...]] | None = None
+ while steps < max_steps:
+ steps += 1
+ state = await game_state(page)
+ if state != "playing":
+ break
+
+ board = await read_board(page, width=width, height=height)
+ opened_sig = tuple(
+ sorted(
+ (c.x, c.y, v)
+ for c, v in board.cells.items()
+ if isinstance(v, int) and 0 <= v <= 8
+ )
+ )
+ flagged_sig = tuple(sorted((c.x, c.y) for c, v in board.cells.items() if v == "flagged"))
+ sig = (opened_sig, flagged_sig)
+ if last_sig is not None and sig == last_sig:
+ same_state_steps += 1
+ else:
+ same_state_steps = 0
+ last_sig = sig
+
+ opened = any(isinstance(v, int) for v in board.cells.values())
+
+ if not opened:
+ first = choose_first_click(board)
+ await click_cell(page, first, button="left")
+ await page.wait_for_timeout(think_ms)
+ continue
+
+ res = solve_step(board, total_mines=total_mines)
+ if res.to_flag or res.to_click:
+ for c in iter_in_order(res.to_flag):
+ if board.get(c) == "covered":
+ await click_cell(page, c, button="right")
+ await page.wait_for_timeout(think_ms)
+ for c in iter_in_order(res.to_click):
+ if board.get(c) == "covered":
+ await click_cell(page, c, button="left")
+ await page.wait_for_timeout(think_ms)
+ continue
+
+ if res.guess:
+ await click_cell(page, res.guess, button="left")
+ await page.wait_for_timeout(think_ms)
+ continue
+
+ # If we observe no board changes for several iterations, force a guess.
+ if stuck_threshold > 0 and same_state_steps >= stuck_threshold:
+ guess, _prob = best_guess(board, total_mines=total_mines)
+ if guess:
+ await click_cell(page, guess, button="left")
+ await page.wait_for_timeout(think_ms)
+ same_state_steps = 0
+ continue
+
+ # No moves found; click a random covered cell (should be rare).
+ covered = [c for c in board.iter_cells() if board.get(c) == "covered"]
+ if not covered:
+ break
+ await click_cell(page, covered[0], button="left")
+ await page.wait_for_timeout(think_ms)
+
+ await page.wait_for_timeout(500)
+ state = await game_state(page)
+ print(f"Finished after {steps} steps: {state}")
+ if headful:
+ await page.wait_for_timeout(10_000)
+ await context.close()
+ if not profile_dir:
+ await browser.close()
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description="Play minesweeperonline.com using heuristics.")
+ ap.add_argument("--url", default=DEFAULT_URL)
+ ap.add_argument("--width", type=int, default=9)
+ ap.add_argument("--height", type=int, default=9)
+ ap.add_argument("--mines", type=int, default=10)
+ ap.add_argument("--headful", action="store_true")
+ ap.add_argument("--slowmo-ms", type=int, default=0)
+ ap.add_argument("--think-ms", type=int, default=30)
+ ap.add_argument("--max-steps", type=int, default=5000)
+ ap.add_argument(
+ "--stuck-threshold",
+ type=int,
+ default=5,
+ help="If the board state doesn't change for N loops, force a guess (0 disables).",
+ )
+ ap.add_argument(
+ "--profile-dir",
+ default=".ms_bot_profile",
+ help="Chromium user data dir for persistent cookies/storage; set to empty to disable.",
+ )
+ args = ap.parse_args()
+ profile_dir = args.profile_dir if str(args.profile_dir).strip() else None
+ asyncio.run(
+ run_bot(
+ url=args.url,
+ width=args.width,
+ height=args.height,
+ total_mines=args.mines,
+ headful=args.headful,
+ slowmo_ms=args.slowmo_ms,
+ think_ms=args.think_ms,
+ max_steps=args.max_steps,
+ profile_dir=profile_dir,
+ stuck_threshold=args.stuck_threshold,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ms_bot/requirements.txt b/ms_bot/requirements.txt
@@ -0,0 +1,2 @@
+playwright>=1.41.0
+
diff --git a/ms_bot/solver.py b/ms_bot/solver.py
@@ -0,0 +1,390 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Iterable
+
+from .board import BoardSnapshot, Cell
+
+
+@dataclass
+class SolveResult:
+ to_click: set[Cell]
+ to_flag: set[Cell]
+ guess: Cell | None
+ guess_prob: float | None
+
+
+def _adjacent_sets(board: BoardSnapshot, cell: Cell) -> tuple[set[Cell], set[Cell], int]:
+ covered: set[Cell] = set()
+ flagged: set[Cell] = set()
+ for n in board.neighbors(cell):
+ v = board.get(n)
+ if v == "covered":
+ covered.add(n)
+ elif v == "flagged":
+ flagged.add(n)
+ return covered, flagged, len(flagged)
+
+
+def _basic_deductions(board: BoardSnapshot) -> tuple[set[Cell], set[Cell]]:
+ safe: set[Cell] = set()
+ mines: set[Cell] = set()
+
+ for cell, number in board.number_cells().items():
+ if number <= 0:
+ continue
+ covered, flagged, flagged_count = _adjacent_sets(board, cell)
+ if not covered:
+ continue
+ if number == flagged_count:
+ safe |= covered
+ if number == flagged_count + len(covered):
+ mines |= covered
+ safe -= board.flagged_cells()
+ mines -= board.flagged_cells()
+ return safe, mines
+
+
+def _subset_deductions(board: BoardSnapshot) -> tuple[set[Cell], set[Cell]]:
+ safe: set[Cell] = set()
+ mines: set[Cell] = set()
+
+ numbered = [(c, n) for c, n in board.number_cells().items() if n > 0]
+ per_cell: dict[Cell, tuple[set[Cell], int]] = {}
+ for c, n in numbered:
+ covered, _flagged, flagged_count = _adjacent_sets(board, c)
+ need = n - flagged_count
+ if need < 0 or not covered:
+ continue
+ per_cell[c] = (covered, need)
+
+ items = list(per_cell.items())
+ for i in range(len(items)):
+ a_cell, (a_set, a_need) = items[i]
+ for j in range(i + 1, len(items)):
+ b_cell, (b_set, b_need) = items[j]
+ if a_set == b_set or not a_set or not b_set:
+ continue
+ if a_set.issubset(b_set):
+ diff = b_set - a_set
+ mines_in_diff = b_need - a_need
+ elif b_set.issubset(a_set):
+ diff = a_set - b_set
+ mines_in_diff = a_need - b_need
+ else:
+ continue
+
+ if mines_in_diff == 0:
+ safe |= diff
+ elif mines_in_diff == len(diff):
+ mines |= diff
+
+ safe -= board.flagged_cells()
+ mines -= board.flagged_cells()
+ return safe, mines
+
+
+def _pattern_121_1221(board: BoardSnapshot) -> tuple[set[Cell], set[Cell]]:
+ safe: set[Cell] = set()
+ mines: set[Cell] = set()
+ nums = board.number_cells()
+
+ def is_open_or_oob(c: Cell) -> bool:
+ if not board.in_bounds(c):
+ return True
+ v = board.get(c)
+ return v != "covered" and v != "unknown"
+
+ def is_covered(c: Cell) -> bool:
+ return board.in_bounds(c) and board.get(c) == "covered"
+
+ # Horizontal and vertical orientations; we only apply when the pattern borders
+ # a single strip of covered cells (edge-like situation).
+ for y in range(board.min_y, board.max_y + 1):
+ for x in range(board.min_x, board.max_x + 1):
+ c0 = Cell(x, y)
+ if nums.get(c0) != 1:
+ continue
+
+ # 1-2-1 horizontal
+ c1 = Cell(x + 1, y)
+ c2 = Cell(x + 2, y)
+ if board.in_bounds(c2) and nums.get(c1) == 2 and nums.get(c2) == 1:
+ for dy in (-1, 1):
+ strip = [Cell(x + k, y + dy) for k in range(3)]
+ other = [Cell(x + k, y - dy) for k in range(3)]
+ if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other):
+ mines.add(strip[0])
+ mines.add(strip[2])
+ safe.add(strip[1])
+
+ # 1-2-2-1 horizontal
+ c3 = Cell(x + 3, y)
+ if board.in_bounds(c3) and nums.get(c1) == 2 and nums.get(c2) == 2 and nums.get(c3) == 1:
+ for dy in (-1, 1):
+ strip = [Cell(x + k, y + dy) for k in range(4)]
+ other = [Cell(x + k, y - dy) for k in range(4)]
+ if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other):
+ safe.add(strip[0])
+ safe.add(strip[3])
+ mines.add(strip[1])
+ mines.add(strip[2])
+
+ for x in range(board.min_x, board.max_x + 1):
+ for y in range(board.min_y, board.max_y + 1):
+ c0 = Cell(x, y)
+ if nums.get(c0) != 1:
+ continue
+
+ # 1-2-1 vertical
+ c1 = Cell(x, y + 1)
+ c2 = Cell(x, y + 2)
+ if board.in_bounds(c2) and nums.get(c1) == 2 and nums.get(c2) == 1:
+ for dx in (-1, 1):
+ strip = [Cell(x + dx, y + k) for k in range(3)]
+ other = [Cell(x - dx, y + k) for k in range(3)]
+ if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other):
+ mines.add(strip[0])
+ mines.add(strip[2])
+ safe.add(strip[1])
+
+ # 1-2-2-1 vertical
+ c3 = Cell(x, y + 3)
+ if board.in_bounds(c3) and nums.get(c1) == 2 and nums.get(c2) == 2 and nums.get(c3) == 1:
+ for dx in (-1, 1):
+ strip = [Cell(x + dx, y + k) for k in range(4)]
+ other = [Cell(x - dx, y + k) for k in range(4)]
+ if all(is_covered(s) for s in strip) and all(is_open_or_oob(o) for o in other):
+ safe.add(strip[0])
+ safe.add(strip[3])
+ mines.add(strip[1])
+ mines.add(strip[2])
+
+ safe -= board.flagged_cells()
+ mines -= board.flagged_cells()
+ return safe, mines
+
+
+@dataclass(frozen=True)
+class Constraint:
+ cells: frozenset[Cell]
+ mines: int
+
+
+def _frontier_constraints(board: BoardSnapshot) -> tuple[set[Cell], list[Constraint]]:
+ frontier: set[Cell] = set()
+ constraints: list[Constraint] = []
+ for cell, number in board.number_cells().items():
+ if number <= 0:
+ continue
+ covered, _flagged, flagged_count = _adjacent_sets(board, cell)
+ if not covered:
+ continue
+ needed = number - flagged_count
+ if needed < 0:
+ continue
+ frontier |= covered
+ constraints.append(Constraint(frozenset(covered), needed))
+ return frontier, constraints
+
+
+def _components(frontier: set[Cell], constraints: list[Constraint]) -> list[tuple[list[Cell], list[Constraint]]]:
+ parent: dict[Cell, Cell] = {c: c for c in frontier}
+
+ def find(c: Cell) -> Cell:
+ while parent[c] != c:
+ parent[c] = parent[parent[c]]
+ c = parent[c]
+ return c
+
+ def union(a: Cell, b: Cell) -> None:
+ ra, rb = find(a), find(b)
+ if ra != rb:
+ parent[rb] = ra
+
+ for con in constraints:
+ cells = list(con.cells)
+ for i in range(1, len(cells)):
+ union(cells[0], cells[i])
+
+ groups: dict[Cell, set[Cell]] = {}
+ for c in frontier:
+ groups.setdefault(find(c), set()).add(c)
+
+ out: list[tuple[list[Cell], list[Constraint]]] = []
+ for root, cells in groups.items():
+ cell_set = set(cells)
+ cons = [con for con in constraints if con.cells & cell_set]
+ out.append((sorted(cells, key=lambda z: (z.y, z.x)), cons))
+ return out
+
+
+def _enumerate_component(
+ variables: list[Cell],
+ constraints: list[Constraint],
+ max_solutions: int = 200_000,
+) -> tuple[int, dict[Cell, int]]:
+ idx = {c: i for i, c in enumerate(variables)}
+ cons_vars: list[list[int]] = [[idx[c] for c in con.cells if c in idx] for con in constraints]
+ cons_need: list[int] = [con.mines for con in constraints]
+
+ # Track current assigned mines count per constraint and remaining unassigned.
+ cons_assigned = [0] * len(constraints)
+ cons_remaining = [len(vs) for vs in cons_vars]
+ mines_per_cell = {c: 0 for c in variables}
+ total = 0
+
+ # Precompute which constraints each variable affects.
+ var_to_cons: list[list[int]] = [[] for _ in variables]
+ for ci, vs in enumerate(cons_vars):
+ for vi in vs:
+ var_to_cons[vi].append(ci)
+
+ assignment = [0] * len(variables)
+
+ def feasible() -> bool:
+ for ci in range(len(constraints)):
+ need = cons_need[ci]
+ assigned = cons_assigned[ci]
+ remaining = cons_remaining[ci]
+ if assigned > need:
+ return False
+ if assigned + remaining < need:
+ return False
+ return True
+
+ def backtrack(i: int) -> None:
+ nonlocal total
+ if total >= max_solutions:
+ return
+ if i == len(variables):
+ if all(cons_assigned[ci] == cons_need[ci] for ci in range(len(constraints))):
+ total += 1
+ for vi, val in enumerate(assignment):
+ if val:
+ mines_per_cell[variables[vi]] += 1
+ return
+
+ # Try safe then mine to bias towards fewer mines for early pruning.
+ for val in (0, 1):
+ assignment[i] = val
+ touched = var_to_cons[i]
+ for ci in touched:
+ cons_remaining[ci] -= 1
+ cons_assigned[ci] += val
+ if feasible():
+ backtrack(i + 1)
+ for ci in touched:
+ cons_assigned[ci] -= val
+ cons_remaining[ci] += 1
+ assignment[i] = 0
+
+ backtrack(0)
+ return total, mines_per_cell
+
+
+def _probability_guess(
+ board: BoardSnapshot,
+ total_mines: int,
+ component_limit: int = 18,
+) -> tuple[Cell | None, float | None, set[Cell], set[Cell]]:
+ covered_all = {c for c in board.iter_cells() if board.get(c) == "covered"}
+ flagged = board.flagged_cells()
+ mines_left = max(0, total_mines - len(flagged))
+
+ frontier, constraints = _frontier_constraints(board)
+ safe: set[Cell] = set()
+ mines: set[Cell] = set()
+
+ probs: dict[Cell, float] = {}
+ unconstrained = covered_all - frontier - flagged
+
+ for variables, cons in _components(frontier, constraints):
+ if len(variables) == 0:
+ continue
+ if len(variables) > component_limit:
+ continue
+ total, mines_per_cell = _enumerate_component(variables, cons)
+ if total == 0:
+ continue
+ for c in variables:
+ m = mines_per_cell[c]
+ if m == 0:
+ safe.add(c)
+ elif m == total:
+ mines.add(c)
+ probs[c] = m / total
+
+ # Unconstrained cells: simple global estimate.
+ remaining_covered = len(covered_all - flagged)
+ base_prob = (mines_left / remaining_covered) if remaining_covered else 1.0
+ for c in unconstrained:
+ probs[c] = base_prob
+
+ candidates = [c for c in covered_all if c not in flagged]
+ if not candidates:
+ return None, None, safe, mines
+
+ def edge_corner_bonus(c: Cell) -> float:
+ is_edge = c.x in (board.min_x, board.max_x) or c.y in (board.min_y, board.max_y)
+ is_corner = (c.x, c.y) in (
+ (board.min_x, board.min_y),
+ (board.min_x, board.max_y),
+ (board.max_x, board.min_y),
+ (board.max_x, board.max_y),
+ )
+ if is_corner:
+ return -0.02
+ if is_edge:
+ return -0.01
+ return 0.0
+
+ def score(c: Cell) -> tuple[float, float, int, int]:
+ p = probs.get(c, base_prob)
+ return (p, p + edge_corner_bonus(c), c.y, c.x)
+
+ best = min(candidates, key=score)
+ return best, probs.get(best, base_prob), safe, mines
+
+
+def solve_step(board: BoardSnapshot, total_mines: int) -> SolveResult:
+ to_click: set[Cell] = set()
+ to_flag: set[Cell] = set()
+
+ safe, mines = _basic_deductions(board)
+ to_click |= safe
+ to_flag |= mines
+
+ safe, mines = _subset_deductions(board)
+ to_click |= safe
+ to_flag |= mines
+
+ safe, mines = _pattern_121_1221(board)
+ to_click |= safe
+ to_flag |= mines
+
+ guess, prob, enum_safe, enum_mines = _probability_guess(board, total_mines=total_mines)
+ to_click |= enum_safe
+ to_flag |= enum_mines
+
+ # Prefer deterministic actions over guessing.
+ if to_click or to_flag:
+ guess = None
+ prob = None
+
+ to_click -= board.flagged_cells()
+ to_flag -= board.flagged_cells()
+ return SolveResult(to_click=to_click, to_flag=to_flag, guess=guess, guess_prob=prob)
+
+
+def best_guess(board: BoardSnapshot, total_mines: int) -> tuple[Cell | None, float | None]:
+ guess, prob, _safe, _mines = _probability_guess(board, total_mines=total_mines)
+ return guess, prob
+
+
+def choose_first_click(board: BoardSnapshot) -> Cell:
+ return Cell(board.min_x + board.width // 2, board.min_y + board.height // 2)
+
+
+def iter_in_order(cells: Iterable[Cell]) -> list[Cell]:
+ return sorted(cells, key=lambda c: (c.y, c.x))