BlueGit

projects-timfalken-com meteors

Files

meteors / test / t1189-spawn-timeline-playwright.py

t1189-spawn-timeline-playwright.py

t1189-spawn-timeline-playwright.py 5.0 KiB Download Raw
1#!/usr/bin/env python3
2"""t1189/t1191: measure the opening spawn timeline in a real browser.
3
4Usage: python3 test/t1189-spawn-timeline-playwright.py URL TAG
5Wraps GameCore.prototype.trySpawn before the game starts, plays 12 s of
6a logged-out solo game and records every spawn tick (play time, interval,
7whether a block appeared) plus per-frame interval samples.
8"""
9import json, sys
10from pathlib import Path
11from playwright.sync_api import sync_playwright
12
13URL = sys.argv[1] if len(sys.argv) > 1 else "https://projects.timfalken.com/meteors/"
14TAG = sys.argv[2] if len(sys.argv) > 2 else "live"
15SHOTS = Path("/workspace/meteors-shots")
16fails = []
17
18def check(c, m):
19 print(("OK " if c else "FAIL ") + m)
20 if not c: fails.append(m)
21
22HOOK = """() => {
23 const R = window.__sp = { ticks: [], samples: [] };
24 const orig = GameCore.prototype.trySpawn;
25 GameCore.prototype.trySpawn = function () {
26 const t = this.playTime, iv = this.currentSpawnInterval();
27 const b = orig.apply(this, arguments);
28 if (this === app.core) R.ticks.push([+t.toFixed(3), +iv.toFixed(4), b ? b.col : null, +this.spawnInterval.toFixed(4)]);
29 return b;
30 };
31 const loop = () => { if (window.app && app.core) R.samples.push([+app.core.playTime.toFixed(3), +app.core.currentSpawnInterval().toFixed(4)]); requestAnimationFrame(loop); };
32 requestAnimationFrame(loop);
33}"""
34
35out = {}
36with sync_playwright() as pw:
37 br = pw.chromium.launch(args=["--use-gl=angle", "--use-angle=swiftshader"])
38 for name, vp, mobile in (("desktop", {"width": 1280, "height": 800}, False), ("mobile", {"width": 390, "height": 844}, True)):
39 ctx = br.new_context(viewport=vp, is_mobile=mobile, has_touch=mobile, device_scale_factor=3 if mobile else 1)
40 page = ctx.new_page()
41 errors = []
42 page.on("pageerror", lambda e: errors.append(str(e)))
43 page.goto(URL + ("" if URL.endswith("/") else "/") + "index.html?t1189=" + TAG, wait_until="networkidle")
44 consts = page.evaluate("() => [GameCore.SPAWN_INTRO_END, GameCore.SPAWN_INTRO_INTERVAL, GameCore.SPAWN_RAMP_END, GameCore.SPAWN_SPEEDUP, GameCore.SPAWN_INTERVAL_MIN]")
45 page.evaluate(HOOK)
46 page.locator("#btn-survival").click()
47 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
48 page.wait_for_timeout(200)
49 page.locator("#btn-planet-go").click()
50 page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)
51 page.wait_for_function("() => app.core.playTime >= 2.5", timeout=10000, polling="raf")
52 page.screenshot(path=str(SHOTS / f"t1189-{TAG}-{name}-burst-2.5s.png"))
53 page.wait_for_function("() => app.core.playTime >= 6.0", timeout=15000, polling="raf")
54 page.screenshot(path=str(SHOTS / f"t1189-{TAG}-{name}-6s.png"))
55 page.wait_for_function("() => app.core.playTime >= 12 || app.core.state !== 'playing'", timeout=20000, polling="raf")
56 d = page.evaluate("() => window.__sp")
57 ctx.close()
58 ticks = d["ticks"]; samples = d["samples"]
59 def seg(a, b): return [t for t in ticks if a <= t[0] < b]
60 def iv_at(t):
61 best = min(samples, key=lambda s: abs(s[0] - t))
62 return best[1]
63 r = {
64 "constants": dict(zip(["intro_end", "intro_interval", "ramp_end", "speedup", "min"], consts)),
65 "interval_at": {str(t): iv_at(t) for t in (0.5, 2.0, 2.9, 3.5, 4.5, 5.5, 6.5, 9, 11.5)},
66 "ticks_0_3": len(seg(0, 3)), "spawned_0_3": sum(1 for t in seg(0, 3) if t[2] is not None),
67 "ticks_3_6": len(seg(3, 6)), "spawned_3_6": sum(1 for t in seg(3, 6) if t[2] is not None),
68 "ticks_6_12": len(seg(6, 12)), "spawned_6_12": sum(1 for t in seg(6, 12) if t[2] is not None),
69 "spawn_interval_at_12s": ticks[-1][3] if ticks else None,
70 "gaps_ramp": [round(b[0] - a[0], 3) for a, b in zip(seg(3, 6.5), seg(3, 6.5)[1:])],
71 "errors": errors,
72 }
73 r["spawned_0_6"] = r["spawned_0_3"] + r["spawned_3_6"]
74 r["ticks_0_6"] = r["ticks_0_3"] + r["ticks_3_6"]
75 out[name] = r
76 print(name, json.dumps(r))
77 ia = r["interval_at"]
78 check(r["constants"]["intro_end"] == 3 and r["constants"]["ramp_end"] == 6, f"{name}: constants {r['constants']}")
79 check(ia["0.5"] == 0.1 and ia["2.9"] == 0.1, f"{name}: 0.1 s during the burst")
80 check(abs(ia["4.5"] - 0.55) < 0.03, f"{name}: ~0.55 s halfway through the ramp ({ia['4.5']})")
81 check(0.95 <= ia["6.5"] <= 1.0 and ia["11.5"] < ia["6.5"], f"{name}: ~1 s after 6 s, then shrinking ({ia['6.5']} → {ia['11.5']})")
82 check(28 <= r["ticks_0_3"] <= 31, f"{name}: {r['ticks_0_3']} spawn ticks in 0–3 s")
83 check(6 <= r["ticks_3_6"] <= 9, f"{name}: {r['ticks_3_6']} spawn ticks in 3–6 s")
84 check(r["spawned_0_3"] >= 25, f"{name}: {r['spawned_0_3']} blocks really spawned in 0–3 s")
85 check(not errors, f"{name}: no page errors")
86 br.close()
87(SHOTS / f"t1189-{TAG}-metrics.json").write_text(json.dumps(out, indent=1))
88print("ALL OK" if not fails else f"{len(fails)} FAIL")
89sys.exit(1 if fails else 0)