WeaveBench / tasks /GAM /GAM_task_4_pokerth_equity_play.md
wanlilll's picture
Add 114 tasks under 8-domain flat layout
71e9dba verified
|
Raw History Blame Contribute Delete
16.5 kB
metadata
id: GAM_task_4_pokerth_equity_play
name: PokerTH 扑克概率计算与跟注决策
category: GAM
timeout_seconds: 1500

Prompt

⚙️ Execution note: This is a fully local, zero real-money desktop application test task. PokerTH is an open-source (AGPL-3.0) single-player Texas Hold'em practice game with no connection whatsoever to any gambling platform, real account, or money; it runs only inside this VM process. treys is an MIT open-source card combination enumeration math library used for Monte Carlo hand-vs-hand probability simulation, and is unrelated to any real financial/gambling business. This task tests GUI automation + probability simulation programming ability.

Task background: the local Ubuntu VM has the open-source Texas Hold'em game PokerTH installed and can play against built-in AI. Texas Hold'em win rate (equity) can be estimated via Monte Carlo simulation — randomly deal cards to the opponent, fill in the remaining community cards, and tally win rate. Decision thresholds: equity ≥ 70% → Raise, equity ≥ 40% → Call, equity < 40% → Fold. treys card notation: Card.new('Ah') = A♥, Card.new('Td') = 10♦.

Task goal: play ≥ 15 hands (minimum 10) in PokerTH. For each hand at each street (preflop/flop/turn/river), identify the cards visually from the game screen, compute equity via Monte Carlo simulation (recommended ≥ 2000 deals), and make a decision according to the thresholds. Deliverables go to /tmp_workspace/results/.

Hard constraints for the main deliverable hands.csv

  • Columns must be complete: hand_num,hole_cards,community_cards,street,equity_pct,decision,pot_size,result
  • Row count ≥ 10
  • hole_cards must look like "Ah Kd" (each card is rank+suit, 2 chars total, rank ∈ 2-9TJQKA, suit ∈ shdc)
  • equity_pct is a number between 0 and 100
  • decision must be one of Fold / Call / Raise
  • result must be one of W / L / Fold
  • The street field must cover both preflop and postflop (any one of flop / turn / river)
  • Decision rationality: the average equity_pct of Fold rows must be strictly less than the average equity_pct of Call rows

Accompanying deliverables (under /tmp_workspace/results/)

File Requirement
equity_log.json Per-hand per-street Monte Carlo simulation details (parameters + results), ≥ 12 entries (equity_log.csv also acceptable)
final_table.png Screenshot of the poker table at the end of the last hand, non-empty content (pixel std > 40)
summary.md Includes total hand count, win/loss counts, chip change, and a description of the decision strategy. Must contain either the Chinese keywords "手数" / "胜" / "筹码" or the English keywords hand / win / chip (one full set)

≥ 10 working-process screenshots

Fixed filename prefix hand_*.png (recommended hand_NN_<street>.png, where NN is the hand index). At least one per hand, showing the current table, hole/community cards, and the Call/Fold/Raise button area.

Anti-cheating constraints

  • Card information must be obtained via visual recognition from the game screen; you may not infer cards/bets by reading PokerTH config files, logs, network packets, or any internal data structures.
  • Importing poker AI decision frameworks (such as poker_solver / poker_ai_agent etc.) is forbidden. Any .py containing import poker_solver or from poker_ai_agent ... counts as a violation; equity computation and decision logic must be implemented yourself.

Expected Behavior

设计意图与典型解题路径(仅供出题人参考,不发给 agent):

  1. 推荐通道:apt install pokerth 后启动游戏,开 Single-Player vs CPU;用 xdotool / pyautogui 控制窗口与下注按钮(也可走 wmctrl 或其他 GUI 自动化方案)。
  2. 截屏:每手 / 每 street 用 gnome-screenshot 或 scrot 截窗口区,命名 hand_NN_<street>.png。
  3. 牌面识别:对截图裁剪手牌 / 公共牌区,用模板匹配 / tesseract OCR / 自训分类器识别 rank+suit;ground truth 不能从配置或日志反读。
  4. 胜率计算:把识别结果转成 treys.Card,蒙特卡洛 ≥ 2000 次随机 deal 统计 win/tie/loss → equity_pct,每个 street 的输入参数与结果追加进 equity_log.json。
  5. 决策与执行:按阈值 70/40 映射 Fold/Call/Raise,GUI 点对应按钮;同步往 hands.csv 写一行。
  6. 收尾:截 final_table.png、写 summary.md(中文「手数/胜/筹码」或英文 hand/win/chip 三词齐全)。

约束说明:

  • actions.log 与任何脚本中不得出现从 PokerTH 内部存储反读牌面的字面量(如 ~/.pokerth、config.xml 解析、stderr 内部牌面日志解析等),评测会扫描 .py 文件中的禁用 import。
  • 决策合理性是行为级强制项:若 Fold 行平均 equity ≥ Call 行平均 equity,说明决策与胜率脱节。

评分要点(hard gates):

  • 核心交付(CSV 行数 / schema / hole_cards 格式 / equity_pct 范围 / decision 与 result 合法值 / 决策合理性 / equity_log 存在与条目 / preflop+postflop 同时存在 / 无禁用 import)权重 60%;其得分 < 0.6 → 总分 cap 0.4。
  • GUI 证据(hand_*.png 数量与每手覆盖率、final_table.png 存在且像素 std > 40、VLM 对牌桌/牌面/按钮的视觉判分)权重 30%;其得分 < 0.5 → 总分 cap 0.4。
  • summary.md 完备性权重 10%。
  • 决策合理性失败 → cap 0.5;出现禁用 import → cap 0.3;VLM 通道不可用时(无法独立证明真实 GUI 交互)总分 cap 0.6。

Source

Grading Criteria

  • results/hands.csv 存在且行数 ≥ 10
  • CSV 列齐全:hand_num, hole_cards, community_cards, street, equity_pct, decision, pot_size, result
  • hole_cards 格式合法(如 "Ah Kd",每张牌 2 字符,rank+suit)
  • equity_pct 为 0-100 之间的数值
  • decision 列只含 Fold/Call/Raise
  • result 列取值合法(W / L / Fold)
  • Fold 决策的 equity_pct 平均值 < Call 决策的 equity_pct 平均值(决策合理性)
  • results/hand_*.png 截图 ≥ 10 张
  • results/equity_log.json 存在且含每手牌的蒙特卡洛模拟记录
  • results/final_table.png 存在且内容非空
  • results/summary.md 存在并含手数 / 胜负 / 筹码 / 策略
  • 无禁用导入(poker_solver / poker_ai_agent)

Automated Checks

import csv, re, json
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. hands.csv row count
    cf = rd / "hands.csv"
    rows = []
    if cf.exists():
        rows = list(csv.DictReader(cf.open()))
    min_hands = gt.get("min_hands", 10)
    s["hands_count"] = min(1.0, len(rows) / min_hands)

    # 2. CSV schema
    req = ["hand_num", "hole_cards", "community_cards", "street",
           "equity_pct", "decision", "pot_size", "result"]
    s["csv_schema"] = 1.0 if rows and all(k in rows[0] for k in req) else 0.0

    # 3. hole_cards format (e.g. "Ah Kd")
    card_pat = re.compile(r"^[2-9TJQKA][shdc]\s+[2-9TJQKA][shdc]$")
    valid_hc = sum(1 for r in rows if card_pat.match(r.get("hole_cards", "").strip()))
    s["hole_cards_valid"] = min(1.0, valid_hc / max(1, len(rows)))

    # 4. equity_pct range
    eq_ok = 0
    for r in rows:
        try:
            e = float(r.get("equity_pct", -1))
            if 0 <= e <= 100:
                eq_ok += 1
        except (ValueError, TypeError):
            pass
    s["equity_range_valid"] = min(1.0, eq_ok / max(1, len(rows)))

    # 5. decision validity
    valid_dec = {"Fold", "Call", "Raise", "fold", "call", "raise"}
    dec_ok = sum(1 for r in rows if r.get("decision", "").strip() in valid_dec)
    s["decision_valid"] = min(1.0, dec_ok / max(1, len(rows)))

    # 5b. result column semantic validity (W/L/Fold)
    valid_res = {"W", "L", "Fold", "w", "l", "fold"}
    res_ok = sum(1 for r in rows if r.get("result", "").strip() in valid_res)
    s["result_valid"] = min(1.0, res_ok / max(1, len(rows)))

    # 6. decision rationality: avg equity of Fold < avg equity of Call
    fold_eq, call_eq = [], []
    for r in rows:
        try:
            e = float(r.get("equity_pct", 50))
            d = r.get("decision", "").strip().lower()
            if d == "fold":
                fold_eq.append(e)
            elif d in ("call", "raise"):
                call_eq.append(e)
        except (ValueError, TypeError):
            pass
    if fold_eq and call_eq:
        s["decision_rationality"] = 1.0 if np.mean(fold_eq) < np.mean(call_eq) else 0.0
    else:
        s["decision_rationality"] = 0.0  # not enough data to judge

    # 7. hand screenshots
    hand_shots = list(rd.glob("hand_*.png"))
    min_shots = gt.get("min_hand_screenshots", 10)
    s["hand_screenshots"] = min(1.0, len(hand_shots) / min_shots)

    # 8. equity_log.json
    ej = rd / "equity_log.json"
    s["equity_log_exists"] = 0.0
    if ej.exists():
        try:
            data = json.loads(ej.read_text())
            s["equity_log_exists"] = 1.0 if len(data) >= 5 else len(data) / 5
        except Exception:
            pass

    # 9. final_table.png
    ft = rd / "final_table.png"
    s["final_table_exists"] = 0.0
    s["table_nontrivial"] = 0.0
    if ft.exists():
        s["final_table_exists"] = 1.0
        try:
            im = Image.open(ft).convert("RGB")
            a = np.array(im)
            s["table_nontrivial"] = 1.0 if a.std() > 40 else a.std() / 40
        except Exception:
            pass

    # 10. summary.md
    sm = rd / "summary.md"
    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", ["hand", "win", "chip"]))
        s["summary_complete"] = 1.0 if (zh or en) else 0.0
    else:
        s["summary_complete"] = 0.0

    # 11. no solver imports
    forbidden = gt.get("forbidden_imports", ["poker_solver", "poker_ai_agent"])
    bad = False
    for src in workspace.rglob("*.py"):
        try:
            t = src.read_text(errors="ignore")
            if any(re.search(rf"\bimport\s+{f}|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

    # 12. VLM rubric (optional)
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None
    rubric_keys = ["vlm_table_visible", "vlm_cards_visible", "vlm_buttons_visible"]
    if vlm_score_rubric and ft.exists():
        rubric = {
            "vlm_table_visible": "截图中能看到扑克牌桌,有牌面和筹码",
            "vlm_cards_visible": "截图中能看到手牌和/或公共牌",
            "vlm_buttons_visible": "截图中能看到 Call/Fold/Raise 按钮区域",
        }
        vlm = vlm_score_rubric([str(ft)], rubric,
                               instruction="Evaluate the PokerTH table screenshot.")
        for k in rubric:
            s[k] = vlm.get(k, 0.5)
    else:
        # VLM unavailable → structural fallback: neutral 0.5 to avoid pulling base down
        for k in rubric_keys:
            s[k] = 0.5

    # --- Content-authenticity sub-scores ---
    n_hands = len(rows)
    n_shots = len(hand_shots)
    s["hand_shots_per_hand"] = 0.0
    if n_hands > 0:
        s["hand_shots_per_hand"] = min(1.0, n_shots / n_hands)

    # equity_log row count (accept .csv or .json)
    log_rows_count = 0
    ej_csv = rd / "equity_log.csv"
    if ej_csv.exists():
        try:
            log_rows_count = sum(1 for _ in csv.DictReader(ej_csv.open()))
        except Exception:
            pass
    elif ej.exists():
        try:
            d = json.loads(ej.read_text())
            log_rows_count = len(d) if isinstance(d, list) else 0
        except Exception:
            pass
    s["equity_log_rows_ge10"] = min(1.0, log_rows_count / 12)

    # preflop / postflop decision streets present in hands.csv
    streets = set(r.get("street", "").strip().lower() for r in rows)
    has_pre = any("pre" in st for st in streets)
    has_post = any(st in ("flop", "turn", "river", "post", "postflop")
                   for st in streets)
    if has_pre and has_post:
        s["preflop_postflop_fields"] = 1.0
    elif has_pre or has_post:
        s["preflop_postflop_fields"] = 0.5
    else:
        s["preflop_postflop_fields"] = 0.0

    # --- Weighted aggregation: core 60% / gui 30% / aux 10% ---
    core_keys = [
        "hands_count", "csv_schema", "hole_cards_valid", "equity_range_valid",
        "decision_valid", "result_valid", "decision_rationality",
        "equity_log_exists", "equity_log_rows_ge10",
        "preflop_postflop_fields", "no_solver_imports",
    ]
    gui_keys = [
        "hand_screenshots", "hand_shots_per_hand",
        "final_table_exists", "table_nontrivial",
        "vlm_table_visible", "vlm_cards_visible", "vlm_buttons_visible",
    ]
    aux_keys = ["summary_complete"]

    def _avg(keys):
        vs = [float(s[k]) for k in keys if k in s]
        return sum(vs) / len(vs) if vs else 0.0

    core_score = _avg(core_keys)
    gui_score = _avg(gui_keys)
    aux_score = _avg(aux_keys)
    s["core_score"] = round(core_score, 4)
    s["gui_score"] = round(gui_score, 4)
    s["aux_score"] = round(aux_score, 4)

    base = 0.6 * core_score + 0.3 * gui_score + 0.1 * aux_score

    # --- Hard gates (single layer, no stacked stair-step caps) ---
    # G1: no CSV/log evidence at all → near-zero
    if s.get("hands_count", 0) == 0 and s.get("csv_schema", 0) == 0:
        base = min(base, 0.05)
    # G2: core delivery weak → cap 0.4
    if core_score < 0.6:
        base = min(base, 0.4)
    # G3: GUI evidence weak (no real interaction with PokerTH) → cap 0.4
    if gui_score < 0.5:
        base = min(base, 0.4)
    # G4: forbidden solver imports → hard cap 0.3
    if s.get("no_solver_imports", 0) < 1.0:
        base = min(base, 0.3)
    # G5: decision rationality failed (Fold avg equity ≥ Call avg) → cap 0.5
    if s.get("decision_rationality", 0) < 1.0:
        base = min(base, 0.5)
    # G6: VLM available and clearly fails (real screenshot doesn't show table) → cap 0.45
    vlm_used = vlm_score_rubric is not None and ft.exists()
    if vlm_used:
        vlm_avg = (s.get("vlm_table_visible", 0) + s.get("vlm_cards_visible", 0)
                   + s.get("vlm_buttons_visible", 0)) / 3.0
        if vlm_avg < 0.4:
            base = min(base, 0.45)
    else:
        # VLM unavailable → cannot prove real GUI interaction → cap 0.6
        base = min(base, 0.6)

    s["overall_score"] = round(max(0.0, base), 4)
    return s

Workspace Path

workspace/GAM/task_4_pokerth_equity_play/

Skills

poker, treys, Monte Carlo simulation

Env

Ubuntu 22.04, GNOME, pokerth, python3, treys, pillow, numpy

Warmup

set +e
echo password | sudo -S -p '' bash -c '
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -qq || true
  which pokerth >/dev/null 2>&1 || apt-get install -y -qq pokerth || true
  apt-get install -y -qq python3-pip xdotool wmctrl gnome-screenshot scrot xvfb || true
  apt-get install -y -qq tesseract-ocr || true
  pip install -q --break-system-packages treys pillow numpy pytesseract 2>/dev/null || true
  mkdir -p /tmp_workspace/results /tmp_workspace/gt || true
  chown -R user:user /tmp_workspace/results /tmp_workspace/gt 2>/dev/null || true
' >/tmp_workspace/install.log 2>&1 || true
which pokerth >/dev/null 2>&1 && echo "pokerth_ready" || echo "pokerth_missing"
true