bot.py (27245B)
1 from __future__ import annotations 2 3 import argparse 4 import asyncio 5 import re 6 import time 7 from typing import TYPE_CHECKING, Any 8 9 if TYPE_CHECKING: 10 from playwright.async_api import Page 11 12 from .board import BoardSnapshot, Cell, parse_square_class, render_board_for_llm 13 from .solver import best_guess, choose_first_click, iter_in_order, solve_step 14 15 16 DEFAULT_URL = "https://minesweeperonline.com/#beginner" 17 BASE_URL = "https://minesweeperonline.com/" 18 19 DIFFICULTY_PRESETS: dict[str, dict[str, object]] = { 20 "beginner": {"fragment": "beginner", "width": 9, "height": 9, "mines": 10}, 21 "intermediate": {"fragment": "intermediate", "width": 16, "height": 16, "mines": 40}, 22 "expert": {"fragment": "expert", "width": 16, "height": 30, "mines": 99}, 23 } 24 25 _COOKIE_BUTTON_RE = re.compile( 26 r"^(accept|accept all|agree|i agree|ok|okay|got it|consent|allow all)$", 27 re.IGNORECASE, 28 ) 29 30 def _parse_cell_id(cell_id: str) -> Cell | None: 31 if not cell_id: 32 return None 33 m = re.match(r"^(\d+)_(\d+)$", cell_id) 34 if not m: 35 return None 36 return Cell(int(m.group(1)), int(m.group(2))) 37 38 async def detect_board_origin(page: "Page") -> tuple[int, int]: 39 data: dict[str, Any] = await page.evaluate( 40 """ 41 () => { 42 if (document.getElementById('1_1')) return { ox: 1, oy: 1 }; 43 if (document.getElementById('0_0')) return { ox: 0, oy: 0 }; 44 const any = document.querySelector('div.square[id]'); 45 if (!any || !any.id) return { ox: 0, oy: 0 }; 46 const m = /^(\\d+)_(\\d+)$/.exec(any.id); 47 if (!m) return { ox: 0, oy: 0 }; 48 return { ox: parseInt(m[1], 10), oy: parseInt(m[2], 10) }; 49 } 50 """ 51 ) 52 return int(data.get("ox", 0)), int(data.get("oy", 0)) 53 54 55 async def read_board(page: "Page", origin_x: int, origin_y: int, width: int, height: int) -> BoardSnapshot: 56 raw: list[list[str]] = await page.evaluate( 57 """ 58 ({ox, oy, w, h}) => { 59 const out = []; 60 for (let y = oy; y < oy + h; y++) { 61 for (let x = ox; x < ox + w; x++) { 62 const id = `${x}_${y}`; 63 const e = document.getElementById(id); 64 out.push([id, e ? (e.className || '') : '']); 65 } 66 } 67 return out; 68 } 69 """, 70 {"ox": origin_x, "oy": origin_y, "w": width, "h": height}, 71 ) 72 data: list[dict[str, Any]] = [{"id": pair[0], "className": pair[1]} for pair in raw] 73 cells: dict[Cell, object] = {} 74 coords: list[Cell] = [] 75 for item in data: 76 c = _parse_cell_id(item.get("id", "")) 77 if not c: 78 continue 79 coords.append(c) 80 cells[c] = parse_square_class(item.get("className", "")) 81 82 for y in range(origin_y, origin_y + height): 83 for x in range(origin_x, origin_x + width): 84 cells.setdefault(Cell(x, y), "covered") 85 86 return BoardSnapshot(origin_x=origin_x, origin_y=origin_y, width=width, height=height, cells=cells) 87 88 89 async def game_state(page: "Page") -> str: 90 # Avoid Playwright auto-wait (which can add multi-second pauses); read directly. 91 face = await page.evaluate("() => document.getElementById('face')?.className || ''") 92 face = face or "" 93 if "facewin" in face: 94 return "win" 95 if "facedead" in face: 96 return "dead" 97 return "playing" 98 99 async def _dispatch_actions(page: "Page", actions: list[dict[str, Any]]) -> int: 100 # Faster than N separate Playwright clicks; also bypasses strict actionability checks. 101 return await page.evaluate( 102 """ 103 (actions) => { 104 let done = 0; 105 for (const a of actions) { 106 const id = a.id; 107 const buttonName = a.button; 108 const e = document.getElementById(id); 109 if (!e) continue; 110 const isRight = buttonName === 'right'; 111 const isMiddle = buttonName === 'middle'; 112 const button = isRight ? 2 : (isMiddle ? 1 : 0); 113 const buttons = isRight ? 2 : (isMiddle ? 4 : 1); 114 const common = { 115 bubbles: true, 116 cancelable: true, 117 composed: true, 118 view: window, 119 button, 120 buttons 121 }; 122 e.dispatchEvent(new MouseEvent('mousedown', common)); 123 e.dispatchEvent(new MouseEvent('mouseup', common)); 124 const ev = isRight ? 'contextmenu' : (isMiddle ? 'auxclick' : 'click'); 125 e.dispatchEvent(new MouseEvent(ev, common)); 126 done += 1; 127 } 128 return done; 129 } 130 """, 131 actions, 132 ) 133 134 async def _dismiss_common_popups(page: "Page") -> None: 135 # Cookie/consent banners vary by region and provider (Quantcast/OneTrust/etc). 136 # We try (1) clicking common accept/close buttons (also inside iframes) and 137 # (2) injecting CSS to hide known containers. 138 try: 139 await page.add_style_tag( 140 content=""" 141 #qc-cmp2-container, .qc-cmp2-container, .qc-cmp2-ui, 142 #onetrust-consent-sdk, .onetrust-pc-dark-filter, .ot-sdk-container, 143 [id*="cookie"][style*="position: fixed"], [class*="cookie"][style*="position: fixed"], 144 [id*="consent"][style*="position: fixed"], [class*="consent"][style*="position: fixed"] { 145 display: none !important; 146 visibility: hidden !important; 147 pointer-events: none !important; 148 } 149 """ 150 ) 151 except Exception: 152 pass 153 154 async def try_click_accept(root: Any) -> None: 155 candidates = [ 156 root.locator('button:has-text("Accept")'), 157 root.locator('button:has-text("I agree")'), 158 root.locator('button:has-text("Agree")'), 159 root.locator('button:has-text("OK")'), 160 root.locator('button:has-text("Got it")'), 161 root.locator('[role="button"]:has-text("Accept")'), 162 root.locator('[aria-label*="close" i]'), 163 root.locator('button[aria-label*="close" i]'), 164 ] 165 for loc in candidates: 166 try: 167 if await loc.first.is_visible(timeout=150): 168 await loc.first.click(timeout=500) 169 return 170 except Exception: 171 continue 172 173 # If roles are wired up, this is often the most reliable. 174 try: 175 btn = root.get_by_role("button").filter(has_text=_COOKIE_BUTTON_RE) 176 if await btn.first.is_visible(timeout=150): 177 await btn.first.click(timeout=500) 178 except Exception: 179 pass 180 181 try: 182 await try_click_accept(page) 183 for frame in page.frames: 184 try: 185 await try_click_accept(frame) 186 except Exception: 187 continue 188 except Exception: 189 pass 190 191 192 async def click_cell(page: "Page", cell: Cell, button: str = "left") -> None: 193 cell_id = f"{cell.x}_{cell.y}" 194 try: 195 done = await _dispatch_actions(page, [{"id": cell_id, "button": button}]) 196 if done: 197 return 198 except Exception: 199 pass 200 201 locator = page.locator(f'div.square[id="{cell_id}"]').first 202 try: 203 await locator.click(button=button, timeout=3000) 204 except Exception: 205 # Often a cookie banner blocks the first action; dismiss and retry once. 206 await _dismiss_common_popups(page) 207 await locator.click(button=button, timeout=3000, force=True) 208 209 async def reset_game(page: "Page") -> None: 210 # Start a fresh game on the current difficulty. MinesweeperOnline resets via the face button. 211 try: 212 await page.evaluate( 213 """ 214 () => { 215 const face = document.getElementById('face'); 216 if (face) face.click(); 217 } 218 """ 219 ) 220 except Exception: 221 try: 222 await page.locator("#face").click(timeout=1000) 223 except Exception: 224 pass 225 226 # Wait until face is not in a terminal state and the board looks reset (blank squares exist). 227 try: 228 await page.wait_for_function( 229 """ 230 () => { 231 const face = document.getElementById('face'); 232 const cls = face ? (face.className || '') : ''; 233 if (cls.includes('facewin') || cls.includes('facedead')) return false; 234 const anyBlank = !!document.querySelector('div.square.blank'); 235 return anyBlank; 236 } 237 """, 238 timeout=3000, 239 ) 240 except Exception: 241 pass 242 243 def _parse_timer_digit(text: str, class_name: str) -> int | None: 244 text = (text or "").strip() 245 if len(text) == 1 and text.isdigit(): 246 return int(text) 247 m = re.search(r"\btime(\d)\b", class_name or "") 248 if m: 249 return int(m.group(1)) 250 return None 251 252 253 async def read_website_seconds(page: "Page") -> int | None: 254 data: dict[str, str] = await page.evaluate( 255 """ 256 () => { 257 const ids = ['seconds_hundreds', 'seconds_tens', 'seconds_ones']; 258 const out = {}; 259 for (const id of ids) { 260 const el = document.getElementById(id); 261 out[id + '_text'] = el ? (el.textContent || '').trim() : ''; 262 out[id + '_class'] = el ? (el.className || '') : ''; 263 } 264 return out; 265 } 266 """ 267 ) 268 h = _parse_timer_digit(data.get("seconds_hundreds_text", ""), data.get("seconds_hundreds_class", "")) 269 t = _parse_timer_digit(data.get("seconds_tens_text", ""), data.get("seconds_tens_class", "")) 270 o = _parse_timer_digit(data.get("seconds_ones_text", ""), data.get("seconds_ones_class", "")) 271 if h is None or t is None or o is None: 272 return None 273 return h * 100 + t * 10 + o 274 275 276 async def play_one_game( 277 page: "Page", 278 url: str, 279 width: int, 280 height: int, 281 total_mines: int, 282 think_ms: int, 283 max_steps: int, 284 stuck_threshold: int, 285 dump_history: bool, 286 dump_board_on_dead: bool, 287 use_chord: bool, 288 ) -> tuple[str, int, float, int | None]: 289 start = time.perf_counter() 290 291 await page.goto(url, wait_until="domcontentloaded") 292 await page.wait_for_timeout(200) 293 await _dismiss_common_popups(page) 294 await reset_game(page) 295 origin_x, origin_y = await detect_board_origin(page) 296 297 steps = 0 298 same_state_steps = 0 299 last_sig: tuple[tuple[tuple[int, int, int], ...], tuple[tuple[int, int], ...]] | None = None 300 history: list[str] = [] 301 302 def fmt_cell(c: Cell) -> str: 303 return f"{c.x}_{c.y}" 304 305 async def record_and_wait(note: str) -> None: 306 history.append(f"{steps:04d} {note}") 307 if think_ms > 0: 308 await page.wait_for_timeout(think_ms) 309 310 while steps < max_steps: 311 steps += 1 312 state = await game_state(page) 313 if state != "playing": 314 break 315 316 board = await read_board(page, origin_x=origin_x, origin_y=origin_y, width=width, height=height) 317 opened_sig = tuple( 318 sorted( 319 (c.x, c.y, v) 320 for c, v in board.cells.items() 321 if isinstance(v, int) and 0 <= v <= 8 322 ) 323 ) 324 flagged_sig = tuple(sorted((c.x, c.y) for c, v in board.cells.items() if v == "flagged")) 325 sig = (opened_sig, flagged_sig) 326 if last_sig is not None and sig == last_sig: 327 same_state_steps += 1 328 else: 329 same_state_steps = 0 330 last_sig = sig 331 332 opened = any(isinstance(v, int) for v in board.cells.values()) 333 if not opened: 334 first = choose_first_click(board) 335 await click_cell(page, first, button="left") 336 await record_and_wait(f"first_click {fmt_cell(first)}") 337 continue 338 339 res = solve_step(board, total_mines=total_mines) 340 if res.to_flag or res.to_click: 341 flags = [c for c in iter_in_order(res.to_flag) if board.get(c) == "covered"] 342 clicks = [c for c in iter_in_order(res.to_click) if board.get(c) == "covered"] 343 344 chord_cells: list[Cell] = [] 345 if use_chord: 346 planned_flags = set(flags) | {c for c, v in board.cells.items() if v == "flagged"} 347 planned_flags |= set(res.to_flag) 348 click_set = set(clicks) 349 removed: set[Cell] = set() 350 for num_cell, number in board.number_cells().items(): 351 flagged_adj = 0 352 covered_neighbors: set[Cell] = set() 353 for n in board.neighbors(num_cell): 354 if n in planned_flags: 355 flagged_adj += 1 356 else: 357 if board.get(n) == "covered": 358 covered_neighbors.add(n) 359 if covered_neighbors and number == flagged_adj: 360 chord_cells.append(num_cell) 361 removed |= (covered_neighbors & click_set) 362 if removed: 363 clicks = [c for c in clicks if c not in removed] 364 365 if flags: 366 await _dispatch_actions( 367 page, 368 [{"id": f"{c.x}_{c.y}", "button": "right"} for c in flags], 369 ) 370 for c in flags: 371 history.append(f"{steps:04d} flag {fmt_cell(c)}") 372 373 if chord_cells or clicks: 374 actions: list[dict[str, str]] = [] 375 for c in chord_cells: 376 actions.append({"id": f"{c.x}_{c.y}", "button": "middle"}) 377 for c in clicks: 378 actions.append({"id": f"{c.x}_{c.y}", "button": "left"}) 379 await _dispatch_actions( 380 page, 381 actions, 382 ) 383 for c in chord_cells: 384 history.append(f"{steps:04d} chord {fmt_cell(c)}") 385 for c in clicks: 386 history.append(f"{steps:04d} click {fmt_cell(c)}") 387 388 if think_ms > 0: 389 await page.wait_for_timeout(think_ms) 390 continue 391 392 if res.guess: 393 await click_cell(page, res.guess, button="left") 394 p = "?" if res.guess_prob is None else f"{res.guess_prob:.3f}" 395 await record_and_wait(f"guess {fmt_cell(res.guess)} p={p}") 396 continue 397 398 if stuck_threshold > 0 and same_state_steps >= stuck_threshold: 399 guess, prob = best_guess(board, total_mines=total_mines) 400 if guess: 401 await click_cell(page, guess, button="left") 402 p = "?" if prob is None else f"{prob:.3f}" 403 await record_and_wait(f"stuck_guess {fmt_cell(guess)} p={p}") 404 same_state_steps = 0 405 continue 406 407 covered = [c for c in board.iter_cells() if board.get(c) == "covered"] 408 if not covered: 409 break 410 await click_cell(page, covered[0], button="left") 411 await record_and_wait(f"fallback_click {fmt_cell(covered[0])}") 412 413 if think_ms > 0: 414 await page.wait_for_timeout(200) 415 state = await game_state(page) 416 website_seconds = None 417 try: 418 website_seconds = await read_website_seconds(page) 419 except Exception: 420 website_seconds = None 421 elapsed = time.perf_counter() - start 422 423 timer_note = "" if website_seconds is None else f" (site: {website_seconds}s)" 424 print(f"Finished after {steps} steps: {state}{timer_note}") 425 if dump_history and state in ("dead", "win"): 426 print("---- move history ----") 427 for line in history: 428 print(line) 429 print("---- end history ----") 430 if dump_board_on_dead and state == "dead": 431 try: 432 final_board = await read_board( 433 page, origin_x=origin_x, origin_y=origin_y, width=width, height=height 434 ) 435 print("---- final board ----") 436 print(render_board_for_llm(final_board)) 437 print("---- end final board ----") 438 except Exception as e: 439 print(f"Failed to dump final board: {e}") 440 441 return state, steps, elapsed, website_seconds 442 443 444 async def run_bot( 445 url: str, 446 width: int, 447 height: int, 448 total_mines: int, 449 headful: bool, 450 slowmo_ms: int, 451 think_ms: int, 452 max_steps: int, 453 profile_dir: str | None, 454 stuck_threshold: int, 455 leave_open: bool, 456 dump_history: bool, 457 dump_board_on_dead: bool, 458 use_chord: bool, 459 ) -> None: 460 from playwright.async_api import async_playwright 461 462 async with async_playwright() as p: 463 if profile_dir: 464 context = await p.chromium.launch_persistent_context( 465 user_data_dir=profile_dir, 466 headless=not headful, 467 slow_mo=slowmo_ms, 468 viewport={"width": 1100, "height": 900}, 469 ) 470 page = context.pages[0] if context.pages else await context.new_page() 471 else: 472 browser = await p.chromium.launch(headless=not headful, slow_mo=slowmo_ms) 473 context = await browser.new_context(viewport={"width": 1100, "height": 900}) 474 page = await context.new_page() 475 page.set_default_timeout(3000) 476 page.set_default_navigation_timeout(3000) 477 478 async def _dismiss_dialog(dialog: Any) -> None: 479 try: 480 await dialog.dismiss() 481 except Exception: 482 # Dialog can auto-close/race; ignore. 483 pass 484 485 page.on("dialog", lambda d: asyncio.create_task(_dismiss_dialog(d))) 486 await page.add_init_script( 487 """ 488 document.addEventListener('contextmenu', e => e.preventDefault()); 489 // Prevent JS dialogs from interrupting fast event dispatch (or crashing the driver). 490 window.alert = () => {}; 491 window.confirm = () => true; 492 window.prompt = () => null; 493 """ 494 ) 495 await play_one_game( 496 page=page, 497 url=url, 498 width=width, 499 height=height, 500 total_mines=total_mines, 501 think_ms=think_ms, 502 max_steps=max_steps, 503 stuck_threshold=stuck_threshold, 504 dump_history=dump_history, 505 dump_board_on_dead=dump_board_on_dead, 506 use_chord=use_chord, 507 ) 508 if leave_open and headful: 509 print("Leaving browser open. Close the browser window to exit.") 510 # Wait until the user closes the window; Ctrl+C should exit cleanly. 511 try: 512 await page.wait_for_event("close") 513 except asyncio.CancelledError: 514 return 515 except Exception: 516 try: 517 await asyncio.Event().wait() 518 except asyncio.CancelledError: 519 return 520 521 await context.close() 522 if not profile_dir: 523 await browser.close() 524 525 async def run_n_times( 526 runs: int, 527 url: str, 528 width: int, 529 height: int, 530 total_mines: int, 531 headful: bool, 532 slowmo_ms: int, 533 think_ms: int, 534 max_steps: int, 535 profile_dir: str | None, 536 stuck_threshold: int, 537 leave_open: bool, 538 dump_history: bool, 539 dump_board_on_dead: bool, 540 use_chord: bool, 541 ) -> None: 542 from playwright.async_api import async_playwright 543 544 durations: list[float] = [] 545 site_seconds: list[int | None] = [] 546 losses = 0 547 wins = 0 548 549 async with async_playwright() as p: 550 for i in range(1, runs + 1): 551 # Important: start a fresh browser/context each run so we never carry 552 # over a win/dead state or stale DOM. 553 browser = None 554 if profile_dir: 555 context = await p.chromium.launch_persistent_context( 556 user_data_dir=profile_dir, 557 headless=not headful, 558 slow_mo=slowmo_ms, 559 viewport={"width": 1100, "height": 900}, 560 ) 561 page = context.pages[0] if context.pages else await context.new_page() 562 else: 563 browser = await p.chromium.launch(headless=not headful, slow_mo=slowmo_ms) 564 context = await browser.new_context(viewport={"width": 1100, "height": 900}) 565 page = await context.new_page() 566 567 page.set_default_timeout(3000) 568 page.set_default_navigation_timeout(3000) 569 570 async def _dismiss_dialog(dialog: Any) -> None: 571 try: 572 await dialog.dismiss() 573 except Exception: 574 pass 575 576 page.on("dialog", lambda d: asyncio.create_task(_dismiss_dialog(d))) 577 await page.add_init_script( 578 """ 579 document.addEventListener('contextmenu', e => e.preventDefault()); 580 window.alert = () => {}; 581 window.confirm = () => true; 582 window.prompt = () => null; 583 """ 584 ) 585 586 print(f"=== Run {i}/{runs} ===") 587 state, _steps, elapsed, website_seconds = await play_one_game( 588 page=page, 589 url=url, 590 width=width, 591 height=height, 592 total_mines=total_mines, 593 think_ms=think_ms, 594 max_steps=max_steps, 595 stuck_threshold=stuck_threshold, 596 dump_history=dump_history, 597 dump_board_on_dead=dump_board_on_dead, 598 use_chord=use_chord, 599 ) 600 durations.append(elapsed) 601 site_seconds.append(website_seconds) 602 if state == "dead": 603 losses += 1 604 elif state == "win": 605 wins += 1 606 607 await context.close() 608 if browser is not None: 609 await browser.close() 610 611 print("=== Summary ===") 612 for i, d in enumerate(durations, start=1): 613 ws = site_seconds[i - 1] 614 ws_note = "" if ws is None else f" site={ws}s" 615 print(f"Run {i}: {d:.3f}s{ws_note}") 616 print(f"Wins: {wins} Losses: {losses} Total: {runs}") 617 win_pct = (wins / runs * 100.0) if runs else 0.0 618 win_times = [s for s in site_seconds if s is not None] 619 avg_site = (sum(win_times) / len(win_times)) if win_times else None 620 if avg_site is None: 621 print(f"Win%: {win_pct:.1f}% Avg site time: n/a") 622 else: 623 print(f"Win%: {win_pct:.1f}% Avg site time: {avg_site:.2f}s") 624 625 626 def main() -> None: 627 ap = argparse.ArgumentParser(description="Play minesweeperonline.com using heuristics.") 628 diff = ap.add_mutually_exclusive_group() 629 diff.add_argument("--beginner", action="store_true", help="Play beginner (default).") 630 diff.add_argument("--intermediate", action="store_true", help="Play intermediate.") 631 diff.add_argument("--expert", action="store_true", help="Play expert.") 632 ap.add_argument("--url", default=None, help="Override game URL (defaults to chosen difficulty).") 633 ap.add_argument("--width", type=int, default=None, help="Override inferred/preset width.") 634 ap.add_argument("--height", type=int, default=None, help="Override inferred/preset height.") 635 ap.add_argument("--mines", type=int, default=None, help="Override preset mine count.") 636 ap.add_argument("--headful", action="store_true") 637 ap.add_argument( 638 "--leave-open", 639 action="store_true", 640 help="After finishing, leave the browser open (headful only).", 641 ) 642 ap.add_argument( 643 "--close", 644 action="store_true", 645 help="Force closing the browser after finishing (overrides --leave-open).", 646 ) 647 ap.add_argument("--slowmo-ms", type=int, default=0) 648 ap.add_argument("--think-ms", type=int, default=30) 649 ap.add_argument("--max-steps", type=int, default=5000) 650 ap.add_argument( 651 "--no-chord", 652 action="store_true", 653 help="Disable chord/middle-click opening around satisfied numbers.", 654 ) 655 ap.add_argument("--runs", type=int, default=1, help="Play N games back-to-back.") 656 ap.add_argument( 657 "--dump-history", 658 action="store_true", 659 help="Print move history when a game ends (useful with --runs).", 660 ) 661 ap.add_argument( 662 "--dump-board", 663 action="store_true", 664 help="Print final board when dead (useful with --runs).", 665 ) 666 ap.add_argument( 667 "--stuck-threshold", 668 type=int, 669 default=5, 670 help="If the board state doesn't change for N loops, force a guess (0 disables).", 671 ) 672 ap.add_argument( 673 "--profile-dir", 674 default=".ms_bot_profile", 675 help="Chromium user data dir for persistent cookies/storage; set to empty to disable.", 676 ) 677 args = ap.parse_args() 678 679 difficulty = "beginner" 680 if args.intermediate: 681 difficulty = "intermediate" 682 elif args.expert: 683 difficulty = "expert" 684 685 preset = DIFFICULTY_PRESETS[difficulty] 686 url = args.url or f"{BASE_URL}#{preset['fragment']}" 687 width = args.width if args.width is not None else int(preset["width"]) 688 height = args.height if args.height is not None else int(preset["height"]) 689 mines = args.mines if args.mines is not None else int(preset["mines"]) 690 691 profile_dir = args.profile_dir if str(args.profile_dir).strip() else None 692 # Default behavior: in headful mode, keep the browser open after finishing. 693 # Use --close to force shutdown (useful for automation). 694 # For multi-run mode, always close between runs and exit after printing stats. 695 leave_open = (args.headful and not args.close) and (not args.runs or int(args.runs) <= 1) 696 try: 697 if args.runs and args.runs > 1: 698 asyncio.run( 699 run_n_times( 700 runs=int(args.runs), 701 url=url, 702 width=width, 703 height=height, 704 total_mines=mines, 705 headful=args.headful, 706 slowmo_ms=args.slowmo_ms, 707 think_ms=args.think_ms, 708 max_steps=args.max_steps, 709 profile_dir=profile_dir, 710 stuck_threshold=args.stuck_threshold, 711 leave_open=False, 712 dump_history=bool(args.dump_history), 713 dump_board_on_dead=bool(args.dump_board), 714 use_chord=not bool(args.no_chord), 715 ) 716 ) 717 else: 718 asyncio.run( 719 run_bot( 720 url=url, 721 width=width, 722 height=height, 723 total_mines=mines, 724 headful=args.headful, 725 leave_open=leave_open, 726 slowmo_ms=args.slowmo_ms, 727 think_ms=args.think_ms, 728 max_steps=args.max_steps, 729 profile_dir=profile_dir, 730 stuck_threshold=args.stuck_threshold, 731 dump_history=True, 732 dump_board_on_dead=True, 733 use_chord=not bool(args.no_chord), 734 ) 735 ) 736 except KeyboardInterrupt: 737 # Exit quietly on Ctrl+C (do not print a full traceback). 738 return 739 740 741 if __name__ == "__main__": 742 main()