commit a83960d7e60176be8a6620b39c96814837e8accb
parent 61655eeeb10d438ca863ad9d432fce29aa214695
Author: William Lindholm <william@skovde.combitech.se>
Date: Wed, 17 Dec 2025 14:00:16 +0100
History tracking
Diffstat:
3 files changed, 64 insertions(+), 6 deletions(-)
diff --git a/ms_bot/README.md b/ms_bot/README.md
@@ -16,3 +16,4 @@ Notes:
- 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.
- Browser lifecycle: in `--headful` mode, the bot leaves the browser open after the game ends (close it manually). Use `--close` to force it to exit.
+- Flag safety: before placing multiple flags, the bot filters them to avoid over-flagging around any revealed number (e.g. never places 2 flags adjacent to a `1`).
diff --git a/ms_bot/bot.py b/ms_bot/bot.py
@@ -237,6 +237,15 @@ async def run_bot(
steps = 0
same_state_steps = 0
last_sig: tuple[tuple[tuple[int, int, int], ...], tuple[tuple[int, int], ...]] | None = None
+ history: list[str] = []
+
+ def fmt_cell(c: Cell) -> str:
+ return f"{c.x}_{c.y}"
+
+ async def record_and_wait(note: str) -> None:
+ history.append(f"{steps:04d} {note}")
+ await page.wait_for_timeout(think_ms)
+
while steps < max_steps:
steps += 1
state = await game_state(page)
@@ -264,7 +273,7 @@ async def run_bot(
if not opened:
first = choose_first_click(board)
await click_cell(page, first, button="left")
- await page.wait_for_timeout(think_ms)
+ await record_and_wait(f"first_click {fmt_cell(first)}")
continue
res = solve_step(board, total_mines=total_mines)
@@ -272,16 +281,17 @@ async def run_bot(
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)
+ await record_and_wait(f"flag {fmt_cell(c)}")
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)
+ await record_and_wait(f"click {fmt_cell(c)}")
continue
if res.guess:
await click_cell(page, res.guess, button="left")
- await page.wait_for_timeout(think_ms)
+ p = "?" if res.guess_prob is None else f"{res.guess_prob:.3f}"
+ await record_and_wait(f"guess {fmt_cell(res.guess)} p={p}")
continue
# If we observe no board changes for several iterations, force a guess.
@@ -289,7 +299,8 @@ async def run_bot(
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)
+ p = "?" if _prob is None else f"{_prob:.3f}"
+ await record_and_wait(f"stuck_guess {fmt_cell(guess)} p={p}")
same_state_steps = 0
continue
@@ -298,11 +309,16 @@ async def run_bot(
if not covered:
break
await click_cell(page, covered[0], button="left")
- await page.wait_for_timeout(think_ms)
+ await record_and_wait(f"fallback_click {fmt_cell(covered[0])}")
await page.wait_for_timeout(500)
state = await game_state(page)
print(f"Finished after {steps} steps: {state}")
+ if state in ("dead", "win"):
+ print("---- move history ----")
+ for line in history:
+ print(line)
+ print("---- end history ----")
if leave_open and headful:
print("Leaving browser open. Close the browser window to exit.")
if browser_for_wait is not None:
diff --git a/ms_bot/solver.py b/ms_bot/solver.py
@@ -374,6 +374,7 @@ def solve_step(board: BoardSnapshot, total_mines: int) -> SolveResult:
to_click -= board.flagged_cells()
to_flag -= board.flagged_cells()
+ to_flag = filter_flag_moves(board, to_flag)
return SolveResult(to_click=to_click, to_flag=to_flag, guess=guess, guess_prob=prob)
@@ -382,6 +383,46 @@ def best_guess(board: BoardSnapshot, total_mines: int) -> tuple[Cell | None, flo
return guess, prob
+def filter_flag_moves(board: BoardSnapshot, candidates: Iterable[Cell]) -> set[Cell]:
+ """
+ Defensive filter to avoid over-flagging around a revealed number.
+
+ This mainly protects against situations where multiple candidate mines touch a
+ single "1" (or any number), which would immediately contradict the visible
+ constraint and cause a false flag.
+ """
+ nums = board.number_cells()
+ accepted: set[Cell] = set()
+ sim_flags: set[Cell] = set(board.flagged_cells())
+
+ for c in iter_in_order(candidates):
+ if board.get(c) != "covered":
+ continue
+ violates = False
+ # Only check revealed number cells adjacent to the candidate.
+ for n in board.neighbors(c):
+ number = nums.get(n)
+ if number is None:
+ continue
+ flagged_after = 0
+ for nn in board.neighbors(n):
+ if nn == c or nn in sim_flags:
+ flagged_after += 1
+ else:
+ v = board.get(nn)
+ if v == "flagged":
+ flagged_after += 1
+ if flagged_after > number:
+ violates = True
+ break
+ if violates:
+ continue
+ accepted.add(c)
+ sim_flags.add(c)
+
+ return accepted
+
+
def choose_first_click(board: BoardSnapshot) -> Cell:
return Cell(board.min_x + board.width // 2, board.min_y + board.height // 2)