WeaveBench / tasks /GAM /GAM_task_16_kmahjongg_pair_solver.md
wanlilll's picture
Add 114 tasks under 8-domain flat layout
71e9dba verified
|
Raw History Blame Contribute Delete
21.7 kB
metadata
id: GAM_task_16_kmahjongg_pair_solver
name: KMahjongg 自定义布局牌对求解 + 截屏识牌 + KConfig 取证
category: GAM
timeout_seconds: 5400

Prompt

Task background: /tmp_workspace/layouts/broken_dragon.layout is a KMahjongg .layout text layout. The layout uses a [KMahjonggLayout] header and multi-layer E...= grids, with the characters 1/2/3/4 denoting the four corners of a single 2×2 tile footprint. Player feedback indicates that this dragon-shaped layout has structural problems including orphaned corner codes, an odd tile count, and overlapping tiles on adjacent layers, which cause dealing or pair-matching to misbehave. The goal is to repair the layout structure, generate a reproducible deal using the fixed game number 424242, recognise the visible tile faces, plan at least 12 legal pair removals, and document the result through progress images and KConfig state forensics.

Produce the following files, preserving the field names and file names:

  • /tmp_workspace/results/before/broken_dragon.layout: an unmodified copy of the original layout, used for diff record-keeping.
  • /tmp_workspace/results/parse_before.json: a JSON object containing header, tiles, tile_count, and anomalies. header includes Depth,Width,Height; each tiles entry contains id,x,y,z; anomalies contains orphan_corners, tile_count_odd, and stacked_collisions, and before the repair all three anomaly categories should carry evidence.
  • /tmp_workspace/results/bugs.json: a JSON object containing three entries: bug_orphan_corner (with detected,examples), bug_odd_tile_count (with detected,tile_count), and bug_stacked_collision (with detected,positions). examples and positions must each contain at least one element.
  • /tmp_workspace/layouts/fixed_dragon.layout: the repaired layout; it should retain the [KMahjonggLayout] header and the Depth/Width/Height lines, and after parsing tile_count should be a positive even number with both orphan_corners and stacked_collisions empty.
  • /tmp_workspace/results/view_kmahjongg_menu.png: image evidence showing the KMahjongg main window or its menus, with text such as game, move, view, settings, kmahjongg, new, or help legible.
  • /tmp_workspace/results/view_broken_deal.png: image evidence showing the broken layout failing to deal, an error prompt, or an anomalous deal state with the HUD visible.
  • /tmp_workspace/results/view_fixed_deal.png: image evidence showing the fixed layout in a normal deal under game number 424242, with text such as tiles, time, matches, layout, kmahjongg, or 00: legible.
  • /tmp_workspace/results/tile_faces.json: a JSON object containing tiles, clusters_total, and face_up_count. Each tiles entry contains id,x,y,z,face_up,face_cluster,phash; clusters_total should fall between 18 and 50, face_up_count should be at least 60, and at least 60 entries should carry a sufficiently long phash string.
  • /tmp_workspace/results/plan.json: a JSON object containing pairs, pairs_planned, and solver_nodes_visited. Each pairs entry contains step,left_id,right_id,left_xy,right_xy; pairs_planned should be at least 12, and the two tiles in each pair should come from the same face_cluster.
  • /tmp_workspace/results/view_progress_1.png, view_progress_2.png, view_progress_3.png: image evidence showing continuous progress after pairs are removed per the plan, with the tile count decreasing step by step.
  • /tmp_workspace/results/view_after_play.png: image evidence showing the board state after at least 12 pairs have been removed.
  • /tmp_workspace/results/kconfig_state.json: a JSON object containing kmahjonggrc_path, general, highscore_files, tiles_removed_observed, and savegame_present. general contains Background,Tileset,Layout,GameNumber, where Layout includes fixed_dragon and GameNumber is 424242.
  • /tmp_workspace/results/parse_after.json: a JSON object whose schema matches parse_before.json; tile_count is even, anomalies.orphan_corners == [], and anomalies.stacked_collisions == [].
  • /tmp_workspace/results/diff.txt: the textual diff between the original layout and fixed_dragon.layout, with a line count between 6 and 200.
  • /tmp_workspace/results/report.json: a JSON object containing bugs_found, fixes_applied, tile_count_before, tile_count_after, face_clusters, pairs_planned, pairs_played, and screenshots; screenshots lists the file names of the menu, broken/fixed deal, three progress images, and after-play image.
  • /tmp_workspace/results/summary.md: at least 8 lines of Markdown summarising the layout parsing, image-based tile-face recognition, planned pair execution, and KConfig forensics evidence sources.

Expected Behavior

成功时,parse_before.json 能列出 header/tiles/tile_count/anomalies,且三类异常均非空; bugs.json 对孤立角码、奇数张牌和相邻层重叠均给出 detected=true 与证据。 /tmp_workspace/layouts/fixed_dragon.layout 应保持头部完整,解析后牌数为偶数,且不再存在 orphan_corners 或 stacked_collisions。

图像证据应显示主界面、broken 发牌状态、fixed 正常牌山、三段消对进度和最终牌局状态。 tile_faces.json 应给出足量可见牌的 face_cluster 与 phash,cluster 数量在合理范围内; plan.json 应列出至少 12 对同 cluster 的消对计划。kconfig_state.json 应证明布局为 fixed_dragon 且局号为 424242;diff.txt 行数处于允许范围,report.json 和 summary.md 应汇总修复、牌面识别、计划执行与 KConfig 证据。

Source

Grading Criteria

    1. parse_before.json schema 完整且 anomalies 三类都非空
    1. bugs.json 三个 bug 全部 detected=true 且证据字段非空
    1. layouts/fixed_dragon.layout 存在且解析后 tile_count 偶数
    1. fixed 解析结果 orphan_corners 与 stacked_collisions 都为空
    1. view_kmahjongg_menu.png OCR 命中 "game"/"move"/"view"/"settings"
    1. view_broken_deal.png 存在;OCR 含错误关键词或 HUD
    1. view_fixed_deal.png 存在;OCR 含 "tiles"/"time"/"matches"/"layout"
    1. tile_faces.json clusters_total ∈ [18, 50],face_up_count ≥ 60
    1. plan.json pairs_planned >= 12,且每对 face_cluster 一致
    1. ≥ 3 张 progress 截屏 + view_after_play.png 存在
    1. kconfig_state.json general.Layout 含 fixed_dragon, GameNumber == 424242
    1. diff.txt 行数 ∈ [6, 200]
    1. summary.md 4 个关键词全部出现
    1. VLM rubric 4 项 ≥ 0.6

Automated Checks

def grade(workspace_path=None, **kwargs) -> dict:
    """KMahjongg layout repair + screenshot tile-face clustering +
    KConfig forensics verifier.

    8–15 sub-scores + 3 hard gates.  Channels:
      - File   : KConfig `.layout` parse + 2×2 corner integrity check.
      - Pixel  : screenshot + per-tile patch phash clustering, OCR HUD.
      - Plan   : pair plan vs face_cluster consistency.
      - Config : kmahjonggrc grep for Layout / GameNumber + savegame.
    No GT leakage: gt/expected.json carries only invariant counts &
    keyword sets; never the patched grid.
    """
    import json, os, re, subprocess, glob
    from pathlib import Path

    ws = Path(workspace_path) if workspace_path else Path("/tmp_workspace")
    rd = ws / "results"
    lay_dir = ws / "layouts"
    gt_dir = ws / "gt"
    expected = {}
    if (gt_dir / "expected.json").exists():
        try:    expected = json.loads((gt_dir/"expected.json").read_text())
        except Exception: expected = {}
    s = {}

    # ---- 1. parse_before schema + anomalies non-empty ----
    pb = rd / "parse_before.json"
    pb_ok = 0.0
    if pb.exists():
        try:
            d = json.loads(pb.read_text())
            need = {"header","tiles","tile_count","anomalies"}
            an = d.get("anomalies", {})
            non_empty = (an.get("orphan_corners") and
                         an.get("stacked_collisions") and
                         an.get("tile_count_odd") is True)
            if need.issubset(d.keys()) and non_empty:
                pb_ok = 1.0
            elif need.issubset(d.keys()):
                pb_ok = 0.4
        except Exception: pass
    s["parse_before_complete"] = pb_ok

    # ---- 2. bugs.json three bugs ----
    bj = rd / "bugs.json"
    bugs_hit = 0
    if bj.exists():
        try:
            b = json.loads(bj.read_text())
            for k, must in [
                ("bug_orphan_corner",     ["examples"]),
                ("bug_odd_tile_count",    ["tile_count"]),
                ("bug_stacked_collision", ["positions"]),
            ]:
                v = b.get(k, {})
                if v.get("detected") and v.get(must[0]):
                    if isinstance(v.get(must[0]), list):
                        if len(v.get(must[0])) >= 1: bugs_hit += 1
                    else:
                        bugs_hit += 1
        except Exception: pass
    s["bugs_three_with_evidence"] = bugs_hit / 3.0

    # ---- 3 + 4. fixed_dragon.layout structural invariants ----
    fixed = lay_dir / "fixed_dragon.layout"
    tile_count = 0
    orphan_n = collide_n = -1
    head_ok = 0.0
    if fixed.exists():
        try:
            txt = fixed.read_text(errors="ignore")
            if txt.lstrip().startswith("[KMahjonggLayout]"):
                head_ok = 1.0
            # quick parser: extract E1..EN blocks
            depth = int(re.search(r"^Depth\s*=\s*(\d+)", txt, re.M).group(1)) \
                    if re.search(r"^Depth\s*=\s*(\d+)", txt, re.M) else 5
            tiles = {}     # (z,x,y) of upper-left corner
            orphan_local = []
            for z in range(1, depth+1):
                m = re.search(rf"^E{z}\d*\s*=\s*(.+(?:\n[^=\[]+)*)",
                              txt, re.M)
                if not m: continue
                rows = [r for r in m.group(1).splitlines() if r.strip()]
                for y,row in enumerate(rows):
                    for x,ch in enumerate(row):
                        if ch in "1234":
                            tiles.setdefault((z,x,y), ch)
            # check 2x2 integrity for every '1'
            for (z,x,y),ch in list(tiles.items()):
                if ch == "1":
                    need = [(z,x+1,y,"2"),(z,x,y+1,"3"),(z,x+1,y+1,"4")]
                    if not all(tiles.get((zz,xx,yy)) == cc
                               for zz,xx,yy,cc in need):
                        orphan_local.append((z,x,y))
            orphan_n = len(orphan_local)
            tile_count = sum(1 for v in tiles.values() if v == "1")
            # stacked collision: same (x,y) corner '1' in two adjacent z
            zs_by_xy = {}
            for (z,x,y),ch in tiles.items():
                if ch == "1": zs_by_xy.setdefault((x,y), []).append(z)
            collide_n = sum(1 for zs in zs_by_xy.values()
                            if len(zs) >= 2 and any(
                                abs(zs[i]-zs[j]) == 1
                                for i in range(len(zs))
                                for j in range(i+1, len(zs))))
        except Exception:
            pass
    s["fixed_layout_header_ok"]    = head_ok
    s["fixed_tile_count_even"]     = 1.0 if (tile_count > 0 and
                                              tile_count % 2 == 0) else 0.0
    s["fixed_no_orphan_corner"]    = 1.0 if orphan_n == 0 else 0.0
    s["fixed_no_stacked_collision"] = 1.0 if collide_n == 0 else 0.0

    # ---- 5. menu screenshot OCR ----
    menu = rd / "view_kmahjongg_menu.png"
    menu_kw = expected.get("menu_keywords",
        ["game","move","view","settings","kmahjongg","new","help"])
    s["menu_shot_present"] = 1.0 if menu.exists() else 0.0
    try:
        import pytesseract; from PIL import Image
        if menu.exists():
            tx = pytesseract.image_to_string(Image.open(menu)).lower()
            s["menu_shot_ocr"] = 1.0 if any(k in tx for k in menu_kw) else 0.0
        else:
            s["menu_shot_ocr"] = 0.0
    except Exception:
        s["menu_shot_ocr"] = 0.0

    # ---- 6 + 7. broken / fixed deal screenshots ----
    bd = rd / "view_broken_deal.png"
    fd = rd / "view_fixed_deal.png"
    s["broken_deal_shot"] = 1.0 if bd.exists() else 0.0
    s["fixed_deal_shot"]  = 1.0 if fd.exists() else 0.0
    deal_kw = expected.get("deal_keywords",
        ["tiles","time","matches","layout","kmahjongg","00:"])
    try:
        import pytesseract; from PIL import Image
        if fd.exists():
            tx = pytesseract.image_to_string(Image.open(fd)).lower()
            s["fixed_deal_ocr"] = 1.0 if any(k in tx for k in deal_kw) else 0.0
        else:
            s["fixed_deal_ocr"] = 0.0
    except Exception:
        s["fixed_deal_ocr"] = 0.0

    # ---- 8. tile_faces.json clusters / face_up_count ----
    tf = rd / "tile_faces.json"
    if tf.exists():
        try:
            d = json.loads(tf.read_text())
            cn = int(d.get("clusters_total", 0))
            fu = int(d.get("face_up_count", 0))
            s["face_clusters_in_range"] = 1.0 if 18 <= cn <= 50 else \
                (0.5 if 10 <= cn <= 80 else 0.0)
            s["face_up_count_ok"] = 1.0 if fu >= 60 else fu/60.0
            # spot-check: phash strings present
            phash_ok = sum(1 for t in d.get("tiles", [])
                           if isinstance(t.get("phash"), str)
                              and len(t["phash"]) >= 16
                              and (t.get("x"), t.get("y"), t.get("z")) in
                                  {(x,y,z) for (z,x,y),c in tiles.items() if c=="1"})
            s["tile_face_phash_present"] = 1.0 if phash_ok >= 60 else phash_ok/60.0
            hashes = {t["phash"] for t in d.get("tiles", []) if t.get("phash")}
            s["tile_face_phash_diverse"] = 1.0 if len(hashes) >= 18 else len(hashes)/18.0
        except Exception:
            s["face_clusters_in_range"] = 0.0
            s["face_up_count_ok"] = 0.0
            s["tile_face_phash_present"] = 0.0
    else:
        s["face_clusters_in_range"] = 0.0
        s["face_up_count_ok"] = 0.0
        s["tile_face_phash_present"] = 0.0

    # ---- 9. plan.json pairs_planned >= 12 + cluster consistency ----
    pj = rd / "plan.json"
    pairs_planned = 0
    pair_cluster_ok = 0.0
    if pj.exists() and tf.exists():
        try:
            p = json.loads(pj.read_text())
            tdata = json.loads(tf.read_text())
            cmap = {t["id"]: t.get("face_cluster") for t in tdata.get("tiles", [])}
            pairs = p.get("pairs", [])
            pairs_planned = len(pairs)
            good = 0
            for pr in pairs:
                lc = cmap.get(pr.get("left_id"))
                rc = cmap.get(pr.get("right_id"))
                if lc is not None and lc == rc: good += 1
            pair_cluster_ok = good / max(1, len(pairs))
        except Exception: pass
    s["plan_pairs_count"] = min(1.0, pairs_planned / 12.0)
    s["plan_pairs_cluster_consistent"] = pair_cluster_ok

    # ---- 10. progress / after-play screenshots ----
    progress = [rd / f"view_progress_{i}.png" for i in (1,2,3)]
    n_prog = sum(1 for p in progress if p.exists())
    s["progress_shots_count"] = n_prog / 3.0
    after = rd / "view_after_play.png"
    s["after_play_shot"] = 1.0 if after.exists() else 0.0

    # ---- 11. KConfig forensics ----
    kj = rd / "kconfig_state.json"
    kconfig_ok = 0.0
    if kj.exists():
        try:
            d = json.loads(kj.read_text())
            gen = d.get("general", {})
            lay = str(gen.get("Layout", "")).lower()
            gn  = int(gen.get("GameNumber", 0)) if str(gen.get("GameNumber","0")).isdigit() else 0
            live = ""
            for cand in [os.path.expanduser("~/.config/kmahjonggrc"),
                         "/root/.config/kmahjonggrc"]:
                if os.path.exists(cand): live = open(cand).read().lower(); break
            if "fixed_dragon" in lay and gn == 424242 and \
               "fixed_dragon" in live and "424242" in live:
                kconfig_ok = 1.0
            elif "fixed_dragon" in lay and gn == 424242:
                kconfig_ok = 0.4
        except Exception: pass
    # cross-check live config file as best-effort fallback
    if kconfig_ok < 1.0:
        for cand in [os.path.expanduser("~/.config/kmahjonggrc"),
                     "/root/.config/kmahjonggrc"]:
            try:
                if os.path.exists(cand):
                    t = open(cand).read().lower()
                    if "fixed_dragon" in t and "424242" in t:
                        kconfig_ok = max(kconfig_ok, 0.85)
            except Exception: pass
    s["kconfig_state_ok"] = kconfig_ok

    # ---- 12. diff lines ----
    df = rd / "diff.txt"
    dlines = 0
    if df.exists():
        try: dlines = sum(1 for _ in df.open())
        except Exception: dlines = 0
    lo = expected.get("diff_min_lines", 6)
    hi = expected.get("diff_max_lines", 200)
    s["diff_in_range"] = 1.0 if lo <= dlines <= hi else 0.0

    # ---- 13. summary.md keywords ----
    sm = rd / "summary.md"
    sm_ok = 0.0
    if sm.exists():
        t = sm.read_text(errors="ignore")
        kws = expected.get("summary_keywords",
            ["布局解析","截屏识别花色","鼠标点击消对","KConfig 取证"])
        if all(k in t for k in kws) and len(t.splitlines()) >= 8:
            sm_ok = 1.0
        elif sum(1 for k in kws if k in t) >= 3:
            sm_ok = 0.6
    s["summary_md_complete"] = sm_ok

    # ---- 14. VLM rubric ----
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None
    imgs = [str(rd/n) for n in
            ["view_fixed_deal.png","view_progress_1.png","view_after_play.png"]
            if (rd/n).exists()]
    if vlm_score_rubric and imgs:
        rubric = {
            "vlm_kmahjongg_real":   "图像确实是 KMahjongg 主窗口或对局画面,含立体牌山和 HUD",
            "vlm_layout_clean":     "fixed 布局看起来形状完整、没有孤立角,整体牌山立体感正确",
            "vlm_progress_change":  "progress 截屏与 fixed_deal 之间能看出明显的牌数减少",
            "vlm_no_cheat":         "看上去是真实点击消对,不是把存档或截屏拼接出来的",
        }
        vlm = vlm_score_rubric(imgs[:3], rubric,
                instruction="评估 KMahjongg 布局修复 + 实战消对截图的真实性")
        for k in rubric: s[k] = vlm.get(k, 0.0)
        s["judge_method"] = vlm.get("judge_method", "failed")
    else:
        for k in ["vlm_kmahjongg_real","vlm_layout_clean",
                  "vlm_progress_change","vlm_no_cheat"]:
            s[k] = 0.5

    # ---- aggregate + hard gates ----
    W = {"fixed_no_orphan_corner":3,"fixed_no_stacked_collision":3,
         "tile_face_phash_present":2,"plan_pairs_cluster_consistent":2,
         "kconfig_state_ok":2,"vlm_layout_clean":2,"vlm_no_cheat":2}
    nums=[(W.get(k,1),v) for k,v in s.items() if isinstance(v,(int,float))]
    base = sum(w*v for w,v in nums)/sum(w for w,_ in nums) if nums else 0.0
    cli_evidence = (rd/"parse_before.json").exists() and \
                   (rd/"bugs.json").exists() and \
                   (rd/"kconfig_state.json").exists() and \
                   (rd/"diff.txt").exists()
    gui_screenshot = sum((rd/n).exists() for n in
        ["view_kmahjongg_menu.png","view_broken_deal.png",
         "view_fixed_deal.png","view_after_play.png",
         "view_progress_1.png","view_progress_2.png","view_progress_3.png"]) >= 6 \
        and s.get("fixed_deal_ocr",0) >= 1.0
    vlm_avg = sum(s.get(k, 0.0) for k in
        ["vlm_kmahjongg_real","vlm_layout_clean",
         "vlm_progress_change","vlm_no_cheat"]) / 4.0
    if not cli_evidence:    base = min(base, 0.4)
    # GUI hard cap dropped: missing screenshots already penalised via per-shot sub-scores.
    if vlm_score_rubric is not None and vlm_avg < 0.6:
        base = min(base, 0.6)
    if s.get("fixed_no_orphan_corner", 0) < 1.0: base = min(base, 0.55)
    if s.get("plan_pairs_count", 0) < 1.0:       base = min(base, 0.7)
    if s.get("kconfig_state_ok", 0) < 0.5:       base = min(base, 0.65)
    s["overall_score"] = round(base, 3)
    return s

Workspace Path

workspace/GAM/task_16_kmahjongg_pair_solver

Skills


Env


Warmup

mkdir -p /tmp_workspace/results /tmp_workspace/state /tmp_workspace/exec
which tesseract || timeout 600 bash -c '(apt-get update -o Acquire::Retries=10 -qq && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=10 install -y -qq --no-install-recommends imagemagick tesseract-ocr python3-pil python3-pip)' || true
pip install -q pillow numpy pytesseract imagehash 2>/dev/null || pip3 install -q --break-system-packages pillow numpy pytesseract imagehash 2>/dev/null || true