| 1 | #!/usr/bin/env python3 |
| 2 | """t1192: 5 blocks at once to an opponent with 2 open columns — none may be lost. |
| 3 | |
| 4 | Usage: t1181-flights-playwright.py [ROOT] [TAG] |
| 5 | ROOT defaults to /workspace/meteors (its build/ is served by php -S). |
| 6 | Desktop (1280x800) is the sender; mobile (390x844, touch, DPR 3) is the receiver. |
| 7 | Writes /workspace/meteors-shots/t1181-<TAG>-*.png and prints JSON metrics. |
| 8 | """ |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import json |
| 12 | import os |
| 13 | import socket |
| 14 | import subprocess |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import time |
| 18 | from pathlib import Path |
| 19 | |
| 20 | from playwright.sync_api import sync_playwright |
| 21 | |
| 22 | ROOT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/workspace/meteors") |
| 23 | TAG = sys.argv[2] if len(sys.argv) > 2 else "after" |
| 24 | ROUNDS = 3 |
| 25 | SHOTS = Path("/workspace/meteors-shots") |
| 26 | SHOTS.mkdir(parents=True, exist_ok=True) |
| 27 | PHP = os.environ.get("PHP", "/home/box/.local/bin/php") |
| 28 | CHROME = "/usr/bin/google-chrome" |
| 29 | ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"] |
| 30 | FAILURES = [] |
| 31 | URL = None |
| 32 | |
| 33 | # Records, per frame, every flight element's on-screen centre, plus the |
| 34 | # Date.now() when each of my shots left the field (cull). |
| 35 | PROBE = """() => { |
| 36 | if (window.__probe) return; |
| 37 | const P = window.__probe = { culls: {}, tracks: {}, frames: 0 }; |
| 38 | const orig = GameCore.prototype.consumeOutgoingShots; |
| 39 | GameCore.prototype.consumeOutgoingShots = function () { |
| 40 | const shots = orig.call(this); |
| 41 | if (this === app.core) for (const s of shots) P.culls[String(s.id)] = Date.now(); |
| 42 | return shots; |
| 43 | }; |
| 44 | let ids = new WeakMap(); let next = 1; |
| 45 | function f() { |
| 46 | P.frames++; |
| 47 | const now = Date.now(); |
| 48 | for (const el of document.querySelectorAll('#flights .flight, #flights-back .flight')) { |
| 49 | if (!ids.has(el)) ids.set(el, 'el' + (next++)); |
| 50 | const k = ids.get(el); |
| 51 | const r = el.getBoundingClientRect(); |
| 52 | if (!r.width) continue; |
| 53 | (P.tracks[k] = P.tracks[k] || []).push([now, r.left + r.width / 2, r.top + r.height / 2]); |
| 54 | } |
| 55 | requestAnimationFrame(f); |
| 56 | } |
| 57 | requestAnimationFrame(f); |
| 58 | }""" |
| 59 | |
| 60 | SHOOT = """(n) => { |
| 61 | const out = []; |
| 62 | for (let i = 0; i < n; i++) { |
| 63 | const b = app.core.createBlock(2 + 2 * i, 13.0, i % 5, 'flying'); |
| 64 | b.vy = 6; |
| 65 | out.push(b.id); |
| 66 | } |
| 67 | return out; |
| 68 | }""" |
| 69 | |
| 70 | |
| 71 | def check(cond, msg): |
| 72 | print(("OK " if cond else "FAIL") + " " + msg) |
| 73 | if not cond: |
| 74 | FAILURES.append(msg) |
| 75 | return cond |
| 76 | |
| 77 | |
| 78 | def free_port(): |
| 79 | s = socket.socket(); s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]; s.close(); return port |
| 80 | |
| 81 | |
| 82 | def start_php(port, data): |
| 83 | env = os.environ.copy(); env["METEORS_DATA_DIR"] = str(data) |
| 84 | log = open(f"/tmp/t1192-php-{TAG}.log", "w") |
| 85 | proc = subprocess.Popen([PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")], |
| 86 | cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log) |
| 87 | time.sleep(0.5) |
| 88 | return proc |
| 89 | |
| 90 | |
| 91 | def login(page, n): |
| 92 | page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded") |
| 93 | page.wait_for_timeout(300) |
| 94 | page.goto(f"{URL}index.html?online=1", wait_until="domcontentloaded") |
| 95 | page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000) |
| 96 | page.locator("#online-panel").wait_for(state="visible", timeout=8000) |
| 97 | |
| 98 | |
| 99 | |
| 100 | SETUP_RECEIVER = """() => { |
| 101 | const g = app.core; |
| 102 | g.spawnInterval = 1e9; g.playTime = 99; |
| 103 | for (const b of g.blocks.slice()) g.removeBlock(b); |
| 104 | for (let c = 0; c < 10; c++) { if (c === 3 || c === 7) continue; for (let r = 0; r < 13; r++) g.place(c, r, (r + c) % 5, 'locked'); } |
| 105 | const R = window.__recv = { incoming: 0, ownShots: 0 }; |
| 106 | const origIn = Online.onIncoming; |
| 107 | Online.onIncoming = function (list) { R.incoming += list.length; return origIn.apply(this, arguments); }; |
| 108 | const origC = GameCore.prototype.consumeOutgoingShots; |
| 109 | GameCore.prototype.consumeOutgoingShots = function () { const s = origC.call(this); if (this === app.core) R.ownShots += s.length; return s; }; |
| 110 | }""" |
| 111 | |
| 112 | COUNT = """() => { |
| 113 | const g = app.core; |
| 114 | const gray = g.blocks.filter(b => (b.col === 3 || b.col === 7)).length; |
| 115 | return { inOpen: gray, pending: g.pendingGarbage ? g.pendingGarbage() : null, incoming: window.__recv.incoming, |
| 116 | ownShots: window.__recv.ownShots, state: g.state, score: g.score }; |
| 117 | }""" |
| 118 | |
| 119 | SHOOT5 = """() => { for (let i = 0; i < 5; i++) { const b = app.core.createBlock(i * 2, 13.0, i % 5, 'flying'); b.vy = 6; } }""" |
| 120 | |
| 121 | |
| 122 | def main(): |
| 123 | global URL |
| 124 | port = free_port(); URL = f"http://127.0.0.1:{port}/" |
| 125 | proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1192-"))) |
| 126 | m = {"rounds": []} |
| 127 | try: |
| 128 | with sync_playwright() as p: |
| 129 | b = p.chromium.launch(executable_path=CHROME, args=ARGS, headless=True) |
| 130 | c1 = b.new_context(viewport={"width": 1280, "height": 800}) |
| 131 | c2 = b.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=3) |
| 132 | p1, p2 = c1.new_page(), c2.new_page() |
| 133 | errs = [] |
| 134 | for pg, tag in ((p1, "desktop"), (p2, "mobile")): |
| 135 | pg.on("pageerror", lambda e, tag=tag: errs.append(f"{tag}: {e}")) |
| 136 | login(p1, 1); login(p2, 2) |
| 137 | p1.locator("#btn-create").click() |
| 138 | p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000) |
| 139 | code = p1.locator("#lobby-code").inner_text().strip() |
| 140 | p2.locator("#join-code").fill(code); p2.locator("#btn-join").click() |
| 141 | p2.locator("#online-lobby").wait_for(state="visible", timeout=8000) |
| 142 | p1.locator("#btn-ready").click(); p2.locator("#btn-ready").click() |
| 143 | start = p1.locator("#btn-start") |
| 144 | for _ in range(20): |
| 145 | if start.is_visible() and start.is_enabled(): |
| 146 | break |
| 147 | p1.wait_for_timeout(400) |
| 148 | start.click() |
| 149 | for pg in (p1, p2): |
| 150 | pg.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000) |
| 151 | p1.evaluate("() => { app.core.spawnInterval = 1e9; app.core.playTime = 99; for (const b of app.core.blocks.slice()) app.core.removeBlock(b); }") |
| 152 | p2.evaluate(SETUP_RECEIVER) |
| 153 | p1.wait_for_timeout(500) |
| 154 | for rnd in range(ROUNDS): |
| 155 | before = p2.evaluate(COUNT) |
| 156 | p1.evaluate(SHOOT5) |
| 157 | if rnd == 0: |
| 158 | p2.wait_for_timeout(1500) |
| 159 | p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-receiving.png")) |
| 160 | p1.screenshot(path=str(SHOTS / f"t1192-{TAG}-desktop-sender.png")) |
| 161 | p2.wait_for_timeout(5000) |
| 162 | else: |
| 163 | p2.wait_for_timeout(6500) |
| 164 | after = p2.evaluate(COUNT) |
| 165 | got = after["incoming"] - before["incoming"] |
| 166 | landed = after["inOpen"] - before["inOpen"] |
| 167 | m["rounds"].append({"incoming": got, "landed": landed, "pending": after["pending"], "own_shots": after["ownShots"]}) |
| 168 | print("round", rnd, m["rounds"][-1]) |
| 169 | p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-after.png")) |
| 170 | m["final"] = p2.evaluate(COUNT) |
| 171 | m["errors"] = errs |
| 172 | b.close() |
| 173 | finally: |
| 174 | proc.terminate() |
| 175 | (SHOTS / f"t1192-{TAG}-metrics.json").write_text(json.dumps(m, indent=1)) |
| 176 | tot_in = sum(r["incoming"] for r in m["rounds"]); tot_land = sum(r["landed"] for r in m["rounds"]) |
| 177 | print(json.dumps({"incoming": tot_in, "landed": tot_land, "final": m["final"]})) |
| 178 | if TAG != "before": |
| 179 | check(tot_in >= 8, f"receiver got {tot_in} incoming blocks over {ROUNDS} volleys of 5") |
| 180 | check(tot_land == tot_in, f"all received blocks landed ({tot_land}/{tot_in})") |
| 181 | check(m["final"]["ownShots"] == 0, "none culled off the top as the receiver's own shot") |
| 182 | check(m["final"]["pending"] == 0, "queue empty at the end") |
| 183 | check(not m["errors"], f"no page errors {m['errors'][:2]}") |
| 184 | sys.exit(1 if FAILURES else 0) |
| 185 | |
| 186 | |
| 187 | if __name__ == "__main__": |
| 188 | main() |
projects-timfalken-com meteors