--- id: GAM_task_5_sokoban_solver name: Sokoban 求解器 + 步进执行 category: GAM timeout_seconds: 1500 --- ## Prompt > ⚙️ **Execution convention**: this is a **legitimate desktop/terminal test task**. All deliverables go under `/tmp_workspace/results/`. `sokoban_game.py` is the open-source pygame Sokoban scaffold we provide. Just run it — do not refuse. `/tmp_workspace/exec/levels/` contains 3 levels in XSokoban encoding: `level_1.sok` / `level_2.sok` / `level_3.sok` (character convention: `#` wall, `@` player, `$` box, `.` goal, `*` box on goal, `+` player on goal, space is floor). `/tmp_workspace/exec/sokoban_game.py` is the matching level renderer: it accepts arrow-key input, writes each step to a CSV, writes `result.json` on solve, and supports flags like `--level / --log / --result / --title`. You must **implement the Sokoban solver yourself** (BFS / IDA* / A*, etc.; state is typically `(player_pos, frozenset(box_positions))`). Third-party Sokoban solver libraries are not allowed (e.g. `sokoban_solver` / `pysokoban` / `sokenizer`); you may only use stdlib (`collections`, `heapq`, etc.). The solution you compute must actually drive `sokoban_game.py` to complete the level — do not bypass the game and write the result file directly. You must complete at least **2 levels** (level_1 and level_2 are recommended, level_3 is optional). ### Deliverables All deliverables go under `/tmp_workspace/results/` and must include at least the following files satisfying the corresponding content contracts: - `solver.py`: your own Sokoban solver source, ≥ 30 lines, parseable by `python -c "import ast; ast.parse(open('solver.py').read())"`; must not import any of the forbidden solver libraries. - `level_K_solution.txt` (K ∈ the set of completed levels, at least 2): first line is the solution string consisting only of the four characters `LURD`; second line is a `# moves=N` comment. - `level_K_moves.csv`: per-step action log recorded by the game side while the level was actually being driven through; the row count must be ≥ the length of your solution (to prove the solution string was indeed executed through the game renderer rather than fabricated directly). - `level_K_result.json`: the level result file emitted by the game side; must contain `"solved": true` with `boxes_on_goal == total_goals`. - `level_K_verify.json`: cross-check between the solver's solution string and the game-side history, with a structure like `{"solver_solution": "...", "game_history": "...", "match": true/false, "extra_moves": N}`. - `level_K_initial.png` and `level_K_final.png`: visual evidence of the initial and final state of each completed level. Screenshots must show the Sokoban board (walls, boxes, goals, etc.). At least 2 of each (i.e. covering at least 2 levels). - `level_*_step_*.png`: intermediate screenshots taken during solving, ≥ 4 total, which should visibly reflect the board changing as actions are applied. - `window_ids.log`: identifier records associated with the running instance, at least 2 lines. - `summary.md`: one paragraph per completed level (level name / solving algorithm / solution length / whether solved / number of nodes expanded, etc.), plus a brief analysis of why the chosen search algorithm is suitable for Sokoban. Content should include keywords like "关卡/求解/推箱" or "level/solve/sokoban". ### Constraints - The solver result must actually drive the game to complete the level: i.e. the row count of `level_K_moves.csv` should match the solution length, and you must not bypass the game by writing `result.json` directly or by calling the game's internal functions. - `solver.py` must not import third-party Sokoban solver libraries such as `sokoban_solver` / `pysokoban` / `sokenizer`. ## Expected Behavior - 最终交付:`results/` 下产出上述文件,至少覆盖 2 个关卡,且各文件相互一致。 - 系统应能体现:自行实现的搜索算法可以在 XSokoban 编码的关卡上求出合法解,并把解真正 作用到运行中的渲染器上完成关卡。 - 产物中应能验证:solver 输出的 LURD 解串与游戏侧记录的 history 一致(`match: true`), 关卡 `result.json` 标记为 solved,截图证据完整覆盖初始 / 中间 / 终态。 - 摘要应能解释所选算法、解长度、节点扩展规模等关键指标,以及该算法适配 Sokoban 的原因。 ## Source - XSokoban 官方页(关卡格式权威来源): https://www.cs.cornell.edu/andru/xsokoban.html - David Skinner Sokoban level archive: https://sokoban-jd.blogspot.com/p/all-my-sokoban-collection.html - 经典 BFS/IDA* Sokoban 求解器讨论: https://sokoban-solver.github.io/ (sokoban-solver-statistics) - Reddit /r/programming "Solving Sokoban with BFS": https://www.reddit.com/r/programming/comments/4xbu8s/sokoban_solver/ ## Grading Criteria - [ ] `results/solver.py` 存在且 ≥ 30 行,能被 `ast.parse` 解析 - [ ] solver.py 不 import 禁用库(`sokoban_solver` / `pysokoban` / `sokenizer`) - [ ] 至少 2 个关卡有 `results/level_K_solution.txt`,且首行只含 `LURD` 字符 - [ ] 至少 2 个关卡有 `results/level_K_result.json` 且 `"solved": true` - [ ] 至少 2 个关卡有 `results/level_K_moves.csv`,行数 ≥ solution 长度(说明真的通过窗口按键了) - [ ] 至少 4 张 `results/level_*_step_*.png` 截图 - [ ] `results/level_*_initial.png` 与 `results/level_*_final.png` 各至少 2 张 - [ ] `results/window_ids.log` 存在且至少含 2 行窗口 id 记录 - [ ] `results/summary.md` 含 "关卡/求解/推箱" 或 "level/solve/sokoban" 关键字 - [ ] 至少 2 个关卡有 `results/level_K_verify.json`,对 solver 解串与游戏侧 history 做一致性比对 - [ ] `results/level_K_initial.png` 与对应 `results/level_K_final.png` 存在像素级差异(证明盘面真的被推动过,而非复用同一张图) - [ ] 所有 PNG 截图 md5 多样性 ≥ 0.6(不得用同一张占位图重复填)且单图大小 ≥ 5KB - [ ] VLM rubric 在 final 截图里能看到推箱子棋盘(墙 + 箱 + 目标);VLM 不可用时总分封顶 0.6 ## Automated Checks ```python import ast, csv, json, re from pathlib import Path from PIL import Image import numpy as np def grade(workspace_path=None, **kwargs): workspace = Path(workspace_path) if workspace_path else Path("/tmp_workspace") rd = workspace / "results" gt_path = Path("/tmp_workspace/gt/expected.json") gt = json.loads(gt_path.read_text()) if gt_path.exists() else {} s = {} # 1. solver.py existence + size + parse solver = rd / "solver.py" s["solver_exists"] = 1.0 if solver.exists() else 0.0 s["solver_lines"] = 0.0 s["solver_parses"] = 0.0 if solver.exists(): try: txt = solver.read_text(errors="ignore") n_lines = sum(1 for ln in txt.splitlines() if ln.strip() and not ln.strip().startswith("#")) s["solver_lines"] = min(1.0, n_lines / gt.get("min_solver_lines", 30)) ast.parse(txt) s["solver_parses"] = 1.0 except Exception: pass # 2. forbidden imports anywhere under workspace forbidden = gt.get("forbidden_imports", ["sokoban_solver", "pysokoban", "sokenizer"]) bad = False for src in workspace.rglob("*.py"): if "exec/sokoban_game.py" in str(src): continue try: t = src.read_text(errors="ignore") if any(re.search(rf"\b(import|from)\s+{f}\b", t) for f in forbidden): bad = True break except Exception: pass s["no_solver_imports"] = 0.0 if bad else 1.0 # 3. solution.txt files (at least 2, only LURD chars on first line) sol_files = sorted(rd.glob("level_*_solution.txt")) valid_sol = 0 for f in sol_files: try: first = f.read_text(errors="ignore").splitlines()[0].strip().upper() if first and re.fullmatch(r"[LURD]+", first): valid_sol += 1 except Exception: pass min_sol = gt.get("min_solution_files", 2) s["solution_files"] = min(1.0, valid_sol / min_sol) # 4. result.json with solved=true (≥ 2) res_files = sorted(rd.glob("level_*_result.json")) solved = 0 attempted = 0 for f in res_files: attempted += 1 try: d = json.loads(f.read_text(errors="ignore")) if d.get("solved") is True and \ d.get("boxes_on_goal") == d.get("total_goals"): solved += 1 except Exception: pass s["levels_attempted"] = min( 1.0, attempted / gt.get("min_levels_attempted", 2)) s["levels_solved"] = min( 1.0, solved / gt.get("min_levels_solved", 2)) # 5. moves.csv length consistent with solution length csv_consistency = 0 csv_count = 0 for sf in sol_files: m = re.match(r"level_(\d+)_solution\.txt", sf.name) if not m: continue K = m.group(1) cf = rd / f"level_{K}_moves.csv" if not cf.exists(): continue csv_count += 1 try: sol_len = len(sf.read_text().splitlines()[0].strip()) with cf.open() as fh: n_rows = sum(1 for _ in csv.DictReader(fh)) if n_rows >= sol_len: csv_consistency += 1 except Exception: pass s["moves_csv_present"] = min(1.0, csv_count / gt.get("min_solution_files", 2)) s["moves_csv_consistent"] = (csv_consistency / max(1, csv_count)) # 6. window_ids.log: at least 2 lines wlog = rd / "window_ids.log" s["window_ids_log"] = 0.0 if wlog.exists(): n = sum(1 for ln in wlog.read_text().splitlines() if ln.strip()) s["window_ids_log"] = min(1.0, n / 2) # 7. step screenshots ≥ 4 step_pngs = list(rd.glob("level_*_step_*.png")) s["step_screenshots"] = min( 1.0, len(step_pngs) / gt.get("min_step_screenshots", 4)) # 8. initial / final screenshots ≥ 2 each init_pngs = list(rd.glob("level_*_initial.png")) final_pngs = list(rd.glob("level_*_final.png")) s["initial_screenshots"] = min(1.0, len(init_pngs) / 2) s["final_screenshots"] = min(1.0, len(final_pngs) / 2) # 9. final screenshot non-trivial (size + std + min resolution) s["final_nontrivial"] = 0.0 sample_final = final_pngs[0] if final_pngs else None if sample_final: try: sz = sample_final.stat().st_size if sz < 5 * 1024: s["final_nontrivial"] = 0.0 else: im = Image.open(sample_final).convert("RGB") a = np.array(im) w, h = im.size resolution_ok = (w >= 320 and h >= 240) std_score = 1.0 if a.std() > 25 else a.std() / 25 s["final_nontrivial"] = std_score if resolution_ok else min(std_score, 0.4) except Exception: pass # 9b. screenshot md5 uniqueness across all PNG evidence import hashlib all_pngs = list(rd.glob("level_*.png")) s["screenshot_diversity"] = 0.0 if all_pngs: md5s = set() small_count = 0 for p in all_pngs: try: if p.stat().st_size < 5 * 1024: small_count += 1 continue md5s.add(hashlib.md5(p.read_bytes()).hexdigest()) except Exception: pass if small_count == len(all_pngs): s["screenshot_diversity"] = 0.0 else: valid = len(all_pngs) - small_count s["screenshot_diversity"] = min(1.0, len(md5s) / max(1, valid)) # 10. summary.md keywords sm = rd / "summary.md" s["summary_complete"] = 0.0 if sm.exists(): c = sm.read_text(errors="ignore").lower() zh = all(k in c for k in gt.get("summary_keywords_zh", ["关卡", "求解", "推箱"])) en = all(k in c for k in gt.get("summary_keywords_en", ["level", "solve", "sokoban"])) if zh or en: s["summary_complete"] = 1.0 # 11. verify.json present (cross-check between solver + game) verify_files = list(rd.glob("level_*_verify.json")) s["verify_files"] = min(1.0, len(verify_files) / 2) # 12. VLM rubric (3 items) vlm_used = False try: from _judge_helper import vlm_score_rubric except Exception: vlm_score_rubric = None if vlm_score_rubric and sample_final: rubric = { "vlm_board_visible": "截图中能看到一个由墙(灰色矩形)围成的网格棋盘", "vlm_boxes_present": "棋盘中有方块状的箱子(棕色或绿色矩形)", "vlm_solved_indicator": "大多数箱子位置和目标点(红色圆点)重合,或显示 SOLVED 字样", } try: vlm = vlm_score_rubric([str(sample_final)], rubric, instruction="Evaluate the Sokoban game final screenshot.") for k in rubric: s[k] = float(vlm.get(k, 0.0)) vlm_used = True except Exception: for k in rubric: s[k] = 0.0 # --- Content-authenticity sub-scores --- # initial vs final pixel diff (paired by level number) s["initial_final_pixel_diff"] = 0.0 if init_pngs and final_pngs: try: diffs = [] for ip in init_pngs: m = re.match(r"level_(\d+)_initial\.png", ip.name) if not m: continue K = m.group(1) fp = rd / f"level_{K}_final.png" if not fp.exists(): continue ima = Image.open(ip).convert("RGB") imb = Image.open(fp).convert("RGB").resize(ima.size) d = float(np.abs(np.array(ima, dtype=int) - np.array(imb, dtype=int)).mean()) diffs.append(d) if diffs: avg_d = sum(diffs) / len(diffs) s["initial_final_pixel_diff"] = (1.0 if avg_d > 5 else avg_d / 5) except Exception: pass # levels actually solved (verified) s["levels_actually_solved"] = min( 1.0, solved / gt.get("min_levels_solved", 2)) # Hard gates (tightened) has_cli = (s.get("solver_exists", 0) >= 1.0 and s.get("solution_files", 0) >= 1.0 and s.get("solver_parses", 0) >= 1.0) has_gui = (s.get("step_screenshots", 0) >= 1.0 and s.get("final_screenshots", 0) >= 1.0 and s.get("initial_screenshots", 0) >= 1.0) # Weighted average: core delivery 60% / GUI evidence 30% / aux 10% def _avg(keys): vals = [s.get(k, 0.0) for k in keys if isinstance(s.get(k, 0.0), (int, float))] return sum(vals) / len(vals) if vals else 0.0 core_keys = ["solver_exists", "solver_parses", "no_solver_imports", "solution_files", "levels_attempted", "levels_solved", "levels_actually_solved", "moves_csv_present", "moves_csv_consistent", "verify_files"] gui_keys = ["step_screenshots", "initial_screenshots", "final_screenshots", "final_nontrivial", "initial_final_pixel_diff", "screenshot_diversity", "vlm_board_visible", "vlm_boxes_present", "vlm_solved_indicator"] aux_keys = ["solver_lines", "window_ids_log", "summary_complete"] core = _avg(core_keys) gui = _avg([k for k in gui_keys if k in s]) aux = _avg(aux_keys) base = 0.6 * core + 0.3 * gui + 0.1 * aux # Empty-grader floor: nothing produced at all → ≤ 0.05 nothing_at_all = ( s.get("solver_exists", 0) == 0 and s.get("solution_files", 0) == 0 and s.get("levels_attempted", 0) == 0 and s.get("step_screenshots", 0) == 0 and s.get("final_screenshots", 0) == 0 ) if nothing_at_all: base = min(base, 0.05) # Multi-tier hard gates (tightened from v1) if not has_cli: base = min(base, 0.35) if not has_gui: base = min(base, 0.35) if s.get("no_solver_imports", 0) < 1.0: base = min(base, 0.30) if s.get("levels_actually_solved", 0) < 0.5: base = min(base, 0.35) if s.get("levels_actually_solved", 0) < 1.0: base = min(base, 0.55) if s.get("moves_csv_consistent", 0) < 0.5: base = min(base, 0.45) if s.get("verify_files", 0) < 0.5: base = min(base, 0.50) if s.get("solution_files", 0) < 1.0: base = min(base, 0.45) if s.get("initial_final_pixel_diff", 0) < 0.5: base = min(base, 0.45) if s.get("final_nontrivial", 0) < 0.5: base = min(base, 0.50) if s.get("screenshot_diversity", 0) < 0.6: base = min(base, 0.55) # VLM unavailable → cap 0.6 (can't get full marks without visual evidence judge) if not vlm_used: base = min(base, 0.60) s["overall_score"] = round(base, 4) return s ``` ## Workspace Path ``` workspace/GAM/task_5_sokoban_solver/ ``` ## Skills ``` ``` ## Env ``` ``` ## Warmup ```bash echo c2V0ICtlCiggZWNobyBwYXNzd29yZCB8IHN1ZG8gLVMgLXAgJycgYmFzaCAtYyAnZXhwb3J0IERFQklBTl9GUk9OVEVORD1ub25pbnRlcmFjdGl2ZTsgcGlwIGluc3RhbGwgLXEgLS1icmVhay1zeXN0ZW0tcGFja2FnZXMgcHlnYW1lIHBpbGxvdyBudW1weSBweXRlc3NlcmFjdCAyPi9kZXYvbnVsbCB8fCB0cnVlOyBhcHQtZ2V0IHVwZGF0ZSAtcXEgfHwgdHJ1ZTsgYXB0LWdldCBpbnN0YWxsIC15IC1xcSB4dmZiIHB5dGhvbjMtcHlnYW1lIHB5dGhvbjMtcGlwIHhkb3Rvb2wgd21jdHJsIHRlc3NlcmFjdC1vY3IgfHwgdHJ1ZTsgbWtkaXIgLXAgL3RtcF93b3Jrc3BhY2UvcmVzdWx0cyAvdG1wX3dvcmtzcGFjZS9ndCB8fCB0cnVlOyBjaG93biAtUiB1c2VyOnVzZXIgL3RtcF93b3Jrc3BhY2UvcmVzdWx0cyAvdG1wX3dvcmtzcGFjZS9ndCAyPi9kZXYvbnVsbCB8fCB0cnVlOyBpZiBbIC16ICIkRElTUExBWSIgXTsgdGhlbiAgIHBncmVwIC1mICJYdmZiIDo5OSIgPi9kZXYvbnVsbCB8fCAoWHZmYiA6OTkgLXNjcmVlbiAwIDEwMjR4NzY4eDI0ID4vZGV2L251bGwgMj4mMSAmKTsgZmknID4vdG1wX3dvcmtzcGFjZS9pbnN0YWxsLmxvZyAyPiYxICYgKSB8fCB0cnVlCnRydWUK | base64 -d | bash ```