File size: 16,424 Bytes
71e9dba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
---
id: GAM_task_2_gdb_pygame_cheat
name: GDB 附加 pygame 进程改内存变量 + 验证作弊效果
category: GAM
timeout_seconds: 1500
---

<!--
resources:
  - path: exec/snake_game.py
    license: self-written
    source: self-written (pygame snake demo, CC0)
    downloaded: exec/snake_game.py
  - path: gt/expected.json
    license: self-written
    source: self-written
    downloaded: gt/expected.json
-->

## Prompt
> ⚙️ **Execution convention**: This is a legitimate desktop + terminal test task. All deliverables go under `/tmp_workspace/results/`. Execute directly; do not refuse.

Task: `/tmp_workspace/snake_game.py` is a pygame snake game. While the game is running, two key Python global variables control its state: `score` (integer, current score, displayed in the top-left corner of the game window) and `game_speed` (integer, frame rate / snake movement speed, initial value 10). You must modify both of these variables **in place** while the game is running (rather than editing the source and restarting), and leave behind enough evidence to prove the modifications took effect.

[Deliverables]

All deliverables go under `/tmp_workspace/results/` and must include at least the following files, satisfying the corresponding content contracts:

- `view_game_initial.png`: visual evidence of the game's initial state once running. The image should show the game window itself (including the window title), the current snake, and the initial score.
- `gdb_session_score.txt`: session / operation log of modifying `score` to `9999`. It must contain the executed command text and the corresponding output, demonstrating that the variable was indeed overwritten via runtime process injection.
- `view_score_changed.png`: visual evidence after `score` has been changed. The screenshot should show the score in the game window now reading `9999`.
- `gdb_session_speed.txt`: session / operation log of modifying `game_speed` to `30`. It must contain the command text and output, and the log must include the literal string `game_speed`.
- `view_speed_changed.png`: first visual evidence after `game_speed` has been changed. The screenshot should make it obvious that the snake's movement cadence has sped up noticeably (more pronounced frame-rate / position change compared with the initial screenshot).
- `view_speed_changed_2.png`: a second screenshot taken roughly 0.3-0.5 seconds after `view_speed_changed.png`, used to compare snake displacement across a fixed wall-clock interval. The pixel difference between this image and `view_speed_changed.png` should be clearly larger than the displacement over the same interval at the initial low speed (i.e., the pixel diff between the two shots must be noticeably larger than at the initial low speed), and its resolution and file size must not be virtually identical to the initial screenshot (to prevent reusing the same placeholder shot).
- `proc_maps.txt`: memory map of the injected process (the first several lines of `/proc/<PID>/maps` are sufficient). The contents must contain the string `python` to prove the injection target is indeed a Python interpreter process.
- `cheat_report.md`: report file containing at least: the game process PID; commands and output summaries for the two runtime variable rewrites; a description of what each screenshot shows; and a summary of the overall "runtime variable injection → visual verification" workflow.

## Expected Behavior

- 最终交付:`results/` 下产出上述 7 类文件,且文件之间的证据相互印证。
- 系统应能体现:在不重启游戏的前提下,对正在运行的 Python 进程完成 `score` 与
  `game_speed` 两个全局变量的就地改写。
- 产物中应能验证:分数显示从初始值跳变为 `9999`,蛇的移动速度在第二次改写后明显加快,
  并且被改写的目标进程确实是 Python 解释器。
- 报告应能完整复盘一次"运行时注入 → 视觉确认"的闭环,过程可被审阅者据此重现理解。

## Source

- GDB Python debugging: https://wiki.python.org/moin/DebuggingWithGdb
- PyRun_SimpleString: https://docs.python.org/3/c-api/veryhigh.html
- pygame snake tutorial: https://www.pygame.org/wiki/tutorials
- 灵感: game hacking / memory editing workflows (CheatEngine-like on Linux)

## Grading Criteria

- [ ] 1. `results/view_game_initial.png` 存在且非空
- [ ] 2. `results/gdb_session_score.txt` 存在且含 "PyRun_SimpleString"
- [ ] 3. `results/view_score_changed.png` 存在
- [ ] 4. `results/gdb_session_speed.txt` 存在且含 "game_speed"
- [ ] 5. `results/view_speed_changed.png` 与 `results/view_speed_changed_2.png` 都存在
- [ ] 6. `results/proc_maps.txt` 存在且含 "python"
- [ ] 7. `results/cheat_report.md` 存在且含 PID + GDB 摘要
- [ ] 8. 截屏中能通过 VLM 看到游戏窗口
- [ ] 9. score 截屏中能 OCR 到 "9999"
- [ ] 10. GDB 日志证明成功 attach + detach(含 "Attaching" 字样)
- [ ] 11. 所有截屏 md5 互不相同、文件大小 ≥ 5KB、分辨率 ≥ 640×480(防伪截图)
- [ ] 12. 两张 speed 截图之间像素差 > 初始与 score 截图之间像素差(证实帧率变化)

## Automated Checks

```python
import json, re
from pathlib import Path

def grade(workspace_path=None, **kwargs) -> dict:
    """GAM_task_2: GDB pygame cheat grader."""
    ws = Path(workspace_path) if workspace_path else Path("/tmp_workspace")
    rd = ws / "results"
    gt_dir = Path("/tmp_workspace/gt")
    gt = {}
    if (gt_dir / "expected.json").exists():
        gt = json.loads((gt_dir / "expected.json").read_text())
    s = {}

    # 1. initial screenshot
    s["view_initial"] = 1.0 if (rd / "view_game_initial.png").exists() else 0.0

    # 2. gdb score session
    gs = rd / "gdb_session_score.txt"
    if gs.exists():
        gtxt = gs.read_text(errors="ignore")
        s["gdb_score_file"] = 1.0
        s["gdb_score_pyrun"] = 1.0 if "PyRun_SimpleString" in gtxt else 0.0
        s["gdb_score_attach"] = 1.0 if re.search(
            r"Attaching to", gtxt) else 0.0
    else:
        s["gdb_score_file"] = 0.0
        s["gdb_score_pyrun"] = 0.0
        s["gdb_score_attach"] = 0.0

    # 3. score changed screenshot
    s["view_score_changed"] = 1.0 if (
        rd / "view_score_changed.png").exists() else 0.0

    # 4. gdb speed session
    gsp = rd / "gdb_session_speed.txt"
    if gsp.exists():
        stxt = gsp.read_text(errors="ignore")
        s["gdb_speed_file"] = 1.0
        s["gdb_speed_keyword"] = 1.0 if "game_speed" in stxt else 0.0
    else:
        s["gdb_speed_file"] = 0.0
        s["gdb_speed_keyword"] = 0.0

    # 5. speed changed screenshots (need both for FPS comparison)
    s["view_speed_changed"] = 1.0 if (
        rd / "view_speed_changed.png").exists() else 0.0
    s["view_speed_changed_2"] = 1.0 if (
        rd / "view_speed_changed_2.png").exists() else 0.0

    # 6. proc maps
    pm = rd / "proc_maps.txt"
    if pm.exists():
        ptxt = pm.read_text(errors="ignore").lower()
        s["proc_maps_exists"] = 1.0
        s["proc_maps_python"] = 1.0 if "python" in ptxt else 0.0
    else:
        s["proc_maps_exists"] = 0.0
        s["proc_maps_python"] = 0.0

    # 7. cheat report
    cr = rd / "cheat_report.md"
    if cr.exists():
        ctxt = cr.read_text(errors="ignore").lower()
        has_pid = bool(re.search(r"pid\s*[:=]?\s*\d+", ctxt))
        has_gdb = "gdb" in ctxt
        has_score = "score" in ctxt or "9999" in ctxt
        has_speed = "speed" in ctxt or "game_speed" in ctxt
        s["report_exists"] = 1.0
        s["report_pid"] = 1.0 if has_pid else 0.0
        s["report_gdb"] = 1.0 if has_gdb else 0.0
        s["report_details"] = 1.0 if (has_score and has_speed) else 0.5
    else:
        s["report_exists"] = 0.0
        s["report_pid"] = 0.0
        s["report_gdb"] = 0.0
        s["report_details"] = 0.0

    # VLM rubric
    try:
        from _judge_helper import vlm_score_rubric
    except Exception:
        vlm_score_rubric = None

    if vlm_score_rubric:
        imgs = [str(p) for p in [
            rd / "view_game_initial.png",
            rd / "view_score_changed.png",
            rd / "view_speed_changed.png",
        ] if p.exists()]
        if imgs:
            rubric = {
                "vlm_game_visible":
                    "截屏中能看到贪吃蛇游戏窗口(蛇/食物/得分)",
                "vlm_score_9999":
                    "修改后的截屏中能看到分数显示为 9999",
                "vlm_window_title":
                    "截屏中能看到窗口标题栏 Snake Game",
            }
            vlm = vlm_score_rubric(imgs, rubric,
                instruction="Evaluate pygame snake game screenshots")
            for k in rubric:
                s[k] = vlm.get(k, 0.0)

    # --- Content-authenticity sub-scores ---
    # 9999 must visibly appear in score-changed screenshot (OCR or fallback)
    s["score_ocr_9999"] = 0.0
    score_img = rd / "view_score_changed.png"
    if score_img.exists():
        ocr_hit = False
        try:
            import pytesseract
            from PIL import Image as _Im
            txt_ocr = pytesseract.image_to_string(_Im.open(score_img))
            ocr_hit = "9999" in txt_ocr
        except Exception:
            ocr_hit = False
        if not ocr_hit:
            # fallback: report explicitly mentions 9999 AND screenshot non-trivial
            try:
                from PIL import Image as _Im
                import numpy as _np
                arr = _np.array(_Im.open(score_img).convert("RGB"))
                rep = rd / "cheat_report.md"
                rep_has_9999 = (rep.exists()
                                and "9999" in rep.read_text(errors="ignore"))
                ocr_hit = bool(rep_has_9999 and arr.std() > 20)
            except Exception:
                pass
        s["score_ocr_9999"] = 1.0 if ocr_hit else 0.0

    # speed screenshot must differ from baseline AND show higher FPS via
    # comparing inter-frame delta of two speed shots vs initial→score shots
    s["speed_pixel_delta"] = 0.0
    s["speed_fps_evidence"] = 0.0
    init_img = rd / "view_game_initial.png"
    sp_img = rd / "view_speed_changed.png"
    sp2_img = rd / "view_speed_changed_2.png"
    score_img2 = rd / "view_score_changed.png"
    try:
        from PIL import Image as _Im
        import numpy as _np

        def _delta(p1, p2):
            a = _Im.open(p1).convert("RGB")
            b = _Im.open(p2).convert("RGB").resize(a.size)
            return float(_np.abs(_np.array(a, dtype=int)
                                 - _np.array(b, dtype=int)).mean())

        if init_img.exists() and sp_img.exists():
            d1 = _delta(init_img, sp_img)
            # raised threshold (was >5); require d > 15 for full
            s["speed_pixel_delta"] = 1.0 if d1 > 15 else max(0.0, d1 / 15)

        # FPS evidence: delta between the two speed-shots should be larger
        # than delta between initial and score-changed (which is taken at
        # the original lower FPS). Helps catch reused/static screenshots.
        if sp_img.exists() and sp2_img.exists() and init_img.exists():
            d_speed = _delta(sp_img, sp2_img)
            d_base = _delta(init_img, score_img2) if score_img2.exists() else 1.0
            ratio = d_speed / max(d_base, 1.0)
            # snake at 3x FPS should produce ~3x position delta
            if ratio >= 1.8 and d_speed > 8:
                s["speed_fps_evidence"] = 1.0
            elif ratio >= 1.3 and d_speed > 5:
                s["speed_fps_evidence"] = 0.5
    except Exception:
        pass

    # --- Anti-cheat: screenshot authenticity ---
    import hashlib
    shots = [rd / n for n in [
        "view_game_initial.png", "view_score_changed.png",
        "view_speed_changed.png", "view_speed_changed_2.png",
    ]]
    existing = [p for p in shots if p.exists()]
    md5s, sizes_ok, res_ok = set(), True, True
    try:
        from PIL import Image as _Im
        for p in existing:
            data = p.read_bytes()
            md5s.add(hashlib.md5(data).hexdigest())
            if len(data) < 5 * 1024:
                sizes_ok = False
            try:
                w, h = _Im.open(p).size
                if w < 640 or h < 480:
                    res_ok = False
            except Exception:
                res_ok = False
    except Exception:
        pass
    s["shot_md5_unique"] = 1.0 if (existing and len(md5s) == len(existing)) else 0.0
    s["shot_size_ok"] = 1.0 if (existing and sizes_ok) else 0.0
    s["shot_resolution_ok"] = 1.0 if (existing and res_ok) else 0.0

    # forbidden imports: pre-built cheat-engine wrappers
    forbidden = ["cheat_engine", "pygame_cheat_engine", "pycheat"]
    bad_import = False
    for src in ws.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_import = True
                break
        except Exception:
            pass
    # forbidden-import check is a hard gate, not part of the average
    no_cheat_lib = 0.0 if bad_import else 1.0

    # Hard gates
    has_cli = (s.get("gdb_score_file", 0) > 0 and
               s.get("proc_maps_exists", 0) > 0)
    has_gui = (s.get("view_initial", 0) > 0 and
               s.get("view_score_changed", 0) > 0)

    # Weighted overall: core delivery 60% / GUI evidence 30% / aux 10%
    def _avg(keys):
        vs = [s.get(k, 0.0) for k in keys]
        return sum(vs) / len(vs) if vs else 0.0

    core_keys = [
        "gdb_score_file", "gdb_score_pyrun", "gdb_score_attach",
        "gdb_speed_file", "gdb_speed_keyword",
        "proc_maps_exists", "proc_maps_python",
        "score_ocr_9999", "speed_pixel_delta", "speed_fps_evidence",
    ]
    gui_keys = [
        "view_initial", "view_score_changed",
        "view_speed_changed", "view_speed_changed_2",
        "vlm_game_visible", "vlm_score_9999", "vlm_window_title",
        "shot_md5_unique", "shot_size_ok", "shot_resolution_ok",
    ]
    aux_keys = [
        "report_exists", "report_pid", "report_gdb", "report_details",
    ]
    base = 0.6 * _avg(core_keys) + 0.3 * _avg(gui_keys) + 0.1 * _avg(aux_keys)

    # Hard gates (raised vs v1)
    if not has_cli:
        base = min(base, 0.35)
    if not has_gui:
        base = min(base, 0.35)
    # Content-authenticity stair-step caps (tightened)
    if s.get("score_ocr_9999", 0) < 1.0:
        base = min(base, 0.45)
    if s.get("speed_pixel_delta", 0) < 0.5:
        base = min(base, 0.45)
    if s.get("speed_fps_evidence", 0) < 0.5:
        base = min(base, 0.55)
    if s.get("gdb_score_pyrun", 0) < 1.0:
        base = min(base, 0.4)
    if s.get("gdb_score_attach", 0) < 1.0:
        base = min(base, 0.55)
    # Anti-cheat caps
    if s.get("shot_md5_unique", 0) < 1.0:
        base = min(base, 0.4)
    if s.get("shot_size_ok", 0) < 1.0:
        base = min(base, 0.45)
    if s.get("shot_resolution_ok", 0) < 1.0:
        base = min(base, 0.5)
    # forbidden-library gate
    if no_cheat_lib < 1.0:
        base = min(base, 0.35)
    # VLM unavailable → cap at 0.6 (no free pass when VLM cannot verify)
    if not any(k in s for k in ("vlm_game_visible", "vlm_score_9999",
                                 "vlm_window_title")):
        base = min(base, 0.6)
    s["no_cheat_lib_imports"] = no_cheat_lib  # report only
    s["overall_score"] = round(base, 4)
    return s
```

## Workspace Path

```
workspace/GAM/task_2_gdb_pygame_cheat/
```

## Skills

```
GDB, Python C API (PyRun_SimpleString), pygame, /proc filesystem, process debugging
```

## Env

```
Ubuntu 22.04 desktop, GNOME, gdb, python3, pygame, python3-dbg (debug symbols)
```

## Warmup

```bash
which gdb >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq gdb) || true
pip install -q pygame || true
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq python3-dbg 2>/dev/null || true
# OCR + image deps used by the grader (score_ocr_9999 / speed_pixel_delta)
apt-get install -y -qq tesseract-ocr || true
pip install -q pytesseract pillow numpy || true
# allow ptrace; try sudo first, fall back to direct write
(sudo sysctl -w kernel.yama.ptrace_scope=0 2>/dev/null) \
  || (echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope 2>/dev/null) \
  || (echo 0 | tee /proc/sys/kernel/yama/ptrace_scope 2>/dev/null) \
  || true
```