"""A fixed difficulty ladder on a FIXED 13x13 grid. The point: hold the grid size constant so prompt length and visual scale never vary, and let difficulty come only from the route itself -- how long it is, and how many places along it the solver can take a wrong turn. Two measured properties define a level: moves length of the (unique) S->E route decision_pts cells ON the route with 3+ open neighbours, i.e. places where the solver must actually choose. A corridor cell with two exits is not a decision; it's bookkeeping. Both are read off the finished maze by `analyse`, never assumed from the generator's arguments -- `n_traps=6` does not mean six wrong turns landed on the route (see generate_graded_maze's docstring for how far apart those two numbers can be). Why 13x13 is exactly rooms=6: the room-grid construction always yields an odd 2*rooms+1 size, and 2*6+1 == 13 lands on it with no padding, so the whole grid is usable (no inert wall margin eating difficulty). The seeds in LEVELS were found by `python -m maze_lab.difficulty --search` and pasted back here, so the suite is fixed: same mazes on every run, every machine. Re-running --search reproduces them exactly. """ from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path from .maze_generator import generate_graded_maze, open_fraction ROOMS = 6 # -> exactly 13x13, no padding GRID_SIZE = 2 * ROOMS + 1 _DIRS = ((-1, 0), (1, 0), (0, -1), (0, 1)) @dataclass(frozen=True) class Level: """A difficulty rung. `moves` and `decision_pts` are INCLUSIVE ranges a candidate maze must land in to qualify; the generator arguments below them are only what the search feeds in while hunting for such a maze.""" name: str moves: tuple # (min, max) route length decision_pts: tuple # (min, max) real choices on the route target_moves: int # generator: route-length cap n_traps: int # generator: traps to attempt max_trap_depth: int # generator: how deep each may run LEVEL_SPECS = { 1: Level("easy", moves=(12, 18), decision_pts=(0, 1), target_moves=18, n_traps=1, max_trap_depth=1), 2: Level("medium", moves=(20, 28), decision_pts=(2, 3), target_moves=28, n_traps=3, max_trap_depth=2), 3: Level("hard", moves=(30, 36), decision_pts=(3, 4), target_moves=36, n_traps=5, max_trap_depth=3), 4: Level("very_hard", moves=(38, 44), decision_pts=(5, 9), target_moves=44, n_traps=8, max_trap_depth=4), } # Verified seeds, 3 per level -- filled in by --search, see module docstring. LEVELS: dict[int, list[int]] = { 1: [0, 1, 2], # easy: 18mv/0dp, 18mv/0dp, 18mv/0dp 2: [3, 4, 5], # medium: 28mv/3dp, 28mv/2dp, 24mv/2dp 3: [8, 9, 10], # hard: 36mv/3dp, 32mv/3dp, 36mv/3dp 4: [83, 565, 754], # very_hard: 44mv/5dp, 44mv/5dp, 44mv/5dp } def build(level: int, seed: int): """The one place generator arguments get applied, so a level's mazes can never drift apart between the search and the benchmark run.""" spec = LEVEL_SPECS[level] return generate_graded_maze(seed, rooms=ROOMS, target_moves=spec.target_moves, n_traps=spec.n_traps, max_trap_depth=spec.max_trap_depth) def _exits(m, pos) -> int: return sum(1 for dr, dc in _DIRS if m.is_open((pos[0] + dr, pos[1] + dc))) def analyse(m) -> dict: """Measure a finished maze: route length, real decision points, how far the deepest wrong turn runs, and open-floor density.""" solution = m.bfs_path_to_goal(m.start) path, pos = [m.start], m.start for mv in solution: pos, _ = m.step(pos, mv) path.append(pos) path_set = set(path) decision_pts = sum(1 for p in path if _exits(m, p) >= 3) deepest = 0 for p in path: for dr, dc in _DIRS: nbr = (p[0] + dr, p[1] + dc) if not m.is_open(nbr) or nbr in path_set: continue # flood the wrong turn, staying off the route, to see how many # cells the solver would burn before the dead end is obvious seen, stack, depth = {p, nbr}, [(nbr, 1)], 0 while stack: cur, d = stack.pop() depth = max(depth, d) for ddr, ddc in _DIRS: nxt = (cur[0] + ddr, cur[1] + ddc) if m.is_open(nxt) and nxt not in seen and nxt not in path_set: seen.add(nxt) stack.append((nxt, d + 1)) deepest = max(deepest, depth) return {"moves": len(solution), "decision_pts": decision_pts, "deepest_wrong_turn": deepest, "open": open_fraction(m), "solution": solution} def qualifies(level: int, m) -> bool: spec = LEVEL_SPECS[level] st = analyse(m) return (spec.moves[0] <= st["moves"] <= spec.moves[1] and spec.decision_pts[0] <= st["decision_pts"] <= spec.decision_pts[1]) def search_seeds(level: int, want: int = 3, limit: int = 4000, exclude=()) -> list: """First `want` seeds whose maze actually measures up to the level. Deterministic: same seeds every run. `exclude` keeps a seed from being reused on another level. The carved tree depends only on (seed, rooms), so the same seed at two levels gives two routes through the SAME tree -- related layouts, which would make levels look alike for no good reason.""" found = [] for seed in range(limit): if seed in exclude: continue if qualifies(level, build(level, seed)): found.append(seed) if len(found) == want: break return found def suite(): """The full fixed benchmark: [(level, seed, maze, stats), ...].""" out = [] for level in sorted(LEVELS): for seed in LEVELS[level]: m = build(level, seed) out.append((level, seed, m, analyse(m))) return out PROJECT_ROOT = Path(__file__).resolve().parents[2] VIEWER = PROJECT_ROOT / "web" / "viewer.html" _BEGIN, _END = "/* SUITE:BEGIN */", "/* SUITE:END */" def export_viewer(path: Path = VIEWER) -> int: """Write the suite into viewer.html between its SUITE markers. The mazes are EXPORTED rather than regenerated in the page because the viewer's JS uses its own PRNG -- same algorithm, different random stream -- so a JS rebuild would produce plausible lookalikes, not the mazes benchmark.py actually runs. Re-run this after changing LEVEL_SPECS, LEVELS, or the generator. """ rows = [] for level, seed, m, st in suite(): rows.append({"level": level, "level_name": LEVEL_SPECS[level].name, "seed": seed, "grid": list(m.grid), "start": list(m.start), "goal": list(m.goal), "moves": st["moves"], "decision_pts": st["decision_pts"], "deepest_wrong_turn": st["deepest_wrong_turn"], "open": round(st["open"], 4), "solution": st["solution"]}) html = path.read_text() if _BEGIN not in html or _END not in html: raise SystemExit(f"{path} has no {_BEGIN} ... {_END} block to write into") head, rest = html.split(_BEGIN, 1) _stale, tail = rest.split(_END, 1) body = "\nconst SUITE = " + json.dumps(rows, indent=2) + ";\n" path.write_text(head + _BEGIN + body + _END + tail) return len(rows) def _main(): import argparse ap = argparse.ArgumentParser(description="Inspect or rebuild the difficulty ladder.") ap.add_argument("--search", action="store_true", help="hunt for qualifying seeds and print a LEVELS dict to paste back") ap.add_argument("--show", action="store_true", help="print every maze in the suite") ap.add_argument("--export-viewer", action="store_true", help="write the suite into viewer.html so the browser shows these exact mazes") args = ap.parse_args() if args.export_viewer: n = export_viewer() print(f"wrote {n} mazes into {VIEWER}") return if args.search: print("LEVELS = {") used = set() for level in sorted(LEVEL_SPECS): seeds = search_seeds(level, exclude=used) used.update(seeds) stats = [analyse(build(level, s)) for s in seeds] desc = ", ".join(f"{s['moves']}mv/{s['decision_pts']}dp" for s in stats) print(f" {level}: {seeds}, # {LEVEL_SPECS[level].name}: {desc}") print("}") return print(f"{'lvl':>3} {'name':<10} {'seed':>5} {'grid':>7} {'moves':>6} {'decisions':>10} " f"{'deepest':>8} {'open':>6}") for level, seed, m, st in suite(): print(f"{level:>3} {LEVEL_SPECS[level].name:<10} {seed:>5} " f"{len(m.grid)}x{len(m.grid[0]):<4} {st['moves']:>6} {st['decision_pts']:>10} " f"{st['deepest_wrong_turn']:>8} {st['open']*100:>5.0f}%") if args.show: print(m.render(), "\n") if __name__ == "__main__": _main()