| 1 | #!/usr/bin/env python3 |
| 2 | """t1173/t1174: reward screen after solo, Offline Strijd rounds and online matches. |
| 3 | |
| 4 | Local PHP server with ?test= logins. Screenshots in /workspace/meteors-shots/t1173-local-*. |
| 5 | """ |
| 6 | from __future__ import annotations |
| 7 | |
| 8 | import os |
| 9 | import socket |
| 10 | import subprocess |
| 11 | import sys |
| 12 | import tempfile |
| 13 | import time |
| 14 | from pathlib import Path |
| 15 | |
| 16 | from playwright.sync_api import sync_playwright |
| 17 | |
| 18 | ROOT = Path("/workspace/meteors") |
| 19 | SHOTS = Path("/workspace/meteors-shots") |
| 20 | SHOTS.mkdir(parents=True, exist_ok=True) |
| 21 | PHP = os.environ.get("PHP", "/home/box/.local/bin/php") |
| 22 | CHROME = "/usr/bin/google-chrome" |
| 23 | CHROME_ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"] |
| 24 | FAILURES = [] |
| 25 | URL = None |
| 26 | |
| 27 | STATE_JS = """() => { |
| 28 | const el = document.getElementById('reward'); |
| 29 | const t = document.getElementById('reward-title'); |
| 30 | const r = t ? t.getBoundingClientRect() : null; |
| 31 | const c = document.getElementById('reward-total'); |
| 32 | const cr = c ? c.getBoundingClientRect() : null; |
| 33 | return { |
| 34 | visible: !!el && !el.hidden, |
| 35 | title: t && t.textContent, |
| 36 | titleTop: r && r.top, titleH: r && r.height, |
| 37 | counter: c && c.textContent, |
| 38 | counterVisible: !!c && !c.parentNode.hidden, |
| 39 | counterY: cr && (cr.top + cr.height / 2), |
| 40 | vh: window.innerHeight, |
| 41 | dbg: (typeof Reward !== 'undefined' && Reward.debugState) ? Reward.debugState() : null, |
| 42 | mode: window.app && app.mode, |
| 43 | menuPoints: (document.getElementById('menu-points') || {}).textContent, |
| 44 | lifetime: (typeof Online !== 'undefined') ? Online.lifetimePoints : null, |
| 45 | }; |
| 46 | }""" |
| 47 | |
| 48 | |
| 49 | def check(cond, msg): |
| 50 | print(("OK " if cond else "FAIL") + " " + msg) |
| 51 | if not cond: |
| 52 | FAILURES.append(msg) |
| 53 | return cond |
| 54 | |
| 55 | |
| 56 | def shot(page, name): |
| 57 | path = SHOTS / name |
| 58 | page.screenshot(path=str(path), full_page=False) |
| 59 | print(f"wrote {path}") |
| 60 | |
| 61 | |
| 62 | def free_port(): |
| 63 | s = socket.socket() |
| 64 | s.bind(("127.0.0.1", 0)) |
| 65 | port = s.getsockname()[1] |
| 66 | s.close() |
| 67 | return port |
| 68 | |
| 69 | |
| 70 | def start_php(port, data, log_path): |
| 71 | env = os.environ.copy() |
| 72 | env["METEORS_DATA_DIR"] = str(data) |
| 73 | log = open(log_path, "w") |
| 74 | proc = subprocess.Popen( |
| 75 | [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")], |
| 76 | cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log, |
| 77 | ) |
| 78 | time.sleep(0.5) |
| 79 | if proc.poll() is not None: |
| 80 | raise RuntimeError("php failed: " + Path(log_path).read_text(errors="replace")) |
| 81 | return proc |
| 82 | |
| 83 | |
| 84 | def login(page, n, next_path="index.html"): |
| 85 | page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=15000) |
| 86 | page.wait_for_timeout(300) |
| 87 | page.goto(f"{URL}{next_path}", wait_until="domcontentloaded", timeout=15000) |
| 88 | page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000) |
| 89 | page.wait_for_timeout(400) |
| 90 | |
| 91 | |
| 92 | def state(page): |
| 93 | return page.evaluate(STATE_JS) |
| 94 | |
| 95 | |
| 96 | def pick_and_play(page, button="#btn-play"): |
| 97 | page.locator(button).click() |
| 98 | page.wait_for_selector("#planet-select:not([hidden])", timeout=8000) |
| 99 | page.wait_for_timeout(200) |
| 100 | page.locator("#btn-planet-go").click() |
| 101 | page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000) |
| 102 | page.wait_for_timeout(300) |
| 103 | |
| 104 | |
| 105 | def force_gameover(page, score): |
| 106 | page.evaluate( |
| 107 | """(s) => { app.core.score = s; app.core.state = 'gameover'; app.core.gameOverTime = 0; }""", score |
| 108 | ) |
| 109 | |
| 110 | |
| 111 | def watch_reward(page, prefix, expect_title, expect_earned): |
| 112 | """Follow one reward run; returns the final debug state.""" |
| 113 | page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000) |
| 114 | page.wait_for_timeout(350) |
| 115 | st = state(page) |
| 116 | print("intro", {k: st[k] for k in ("title", "titleTop", "vh", "counterVisible")}) |
| 117 | check(st["title"] == expect_title, f"{prefix}: title {st['title']!r} == {expect_title!r}") |
| 118 | mid = st["titleTop"] + st["titleH"] / 2 |
| 119 | check(abs(mid - st["vh"] / 2) < st["vh"] * 0.12, f"{prefix}: title centred first (mid {mid:.0f} / vh {st['vh']})") |
| 120 | check(st["dbg"] and st["dbg"]["phase"] == "intro", f"{prefix}: phase intro at 0.35 s ({st['dbg'] and st['dbg']['phase']})") |
| 121 | shot(page, f"t1173-local-{prefix}-1-centered.png") |
| 122 | # After 1 s + 0.6 s tween: title at the top. |
| 123 | page.wait_for_timeout(1500) |
| 124 | st = state(page) |
| 125 | check(st["titleTop"] < st["vh"] * 0.15, f"{prefix}: title rose to the top ({st['titleTop']:.0f})") |
| 126 | if expect_earned > 0: |
| 127 | page.wait_for_function( |
| 128 | "() => Reward.debugState() && Reward.debugState().phase === 'count' && Reward.debugState().flying >= 2", |
| 129 | timeout=6000, |
| 130 | ) |
| 131 | page.wait_for_timeout(250) |
| 132 | st = state(page) |
| 133 | d = st["dbg"] |
| 134 | print("counting", d, st["counter"]) |
| 135 | check(d["earned"] == expect_earned, f"{prefix}: earned {d['earned']} == {expect_earned}") |
| 136 | check(st["counterVisible"], f"{prefix}: counter visible at the bottom") |
| 137 | check(st["counterY"] > st["vh"] * 0.7, f"{prefix}: counter near bottom ({st['counterY']:.0f}/{st['vh']})") |
| 138 | check(d["before"] <= int(st["counter"]) <= d["after"], f"{prefix}: counter {st['counter']} within [{d['before']}, {d['after']}]") |
| 139 | check(d["flying"] >= 1, f"{prefix}: blocks are flying ({d['flying']})") |
| 140 | shot(page, f"t1173-local-{prefix}-2-counting.png") |
| 141 | page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=30000) |
| 142 | st = state(page) |
| 143 | d = st["dbg"] |
| 144 | check(int(st["counter"]) == d["after"], f"{prefix}: final counter {st['counter']} == after {d['after']}") |
| 145 | check(d["after"] - d["before"] == expect_earned, f"{prefix}: after-before == {expect_earned}") |
| 146 | check(d["after"] == st["lifetime"], f"{prefix}: final == server lifetime ({st['lifetime']})") |
| 147 | shot(page, f"t1173-local-{prefix}-3-final.png") |
| 148 | page.wait_for_function("() => document.getElementById('reward').hidden", timeout=6000) |
| 149 | page.wait_for_timeout(300) |
| 150 | return d |
| 151 | |
| 152 | |
| 153 | def test_logged_out_solo(browser): |
| 154 | print("\n== logged-out solo stays as before ==") |
| 155 | ctx = browser.new_context(viewport={"width": 1280, "height": 800}) |
| 156 | page = ctx.new_page() |
| 157 | page.goto(f"{URL}index.html", wait_until="networkidle") |
| 158 | pick_and_play(page) |
| 159 | page.wait_for_timeout(500) |
| 160 | force_gameover(page, 7) |
| 161 | page.wait_for_timeout(500) |
| 162 | st = state(page) |
| 163 | go = page.evaluate("() => !document.getElementById('game-over').hidden") |
| 164 | check(not st["visible"], "logged out: no reward screen") |
| 165 | check(go, "logged out: classic game-over overlay") |
| 166 | shot(page, "t1173-local-loggedout-gameover.png") |
| 167 | page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=8000) |
| 168 | check(True, "logged out: back to menu") |
| 169 | ctx.close() |
| 170 | |
| 171 | |
| 172 | def test_solo(browser): |
| 173 | print("\n== logged-in solo ==") |
| 174 | ctx = browser.new_context(viewport={"width": 1280, "height": 800}) |
| 175 | page = ctx.new_page() |
| 176 | errs = [] |
| 177 | page.on("pageerror", lambda e: errs.append(str(e))) |
| 178 | login(page, 1) |
| 179 | before = int(page.locator("#menu-points").inner_text().strip() or 0) |
| 180 | pick_and_play(page) |
| 181 | page.wait_for_function("() => app.playToken", timeout=8000) |
| 182 | page.wait_for_timeout(3600) # server needs >= 3 s and 4 pts/s → 12 allowed |
| 183 | force_gameover(page, 12) |
| 184 | d = watch_reward(page, "solo", "You lost...", 12) |
| 185 | check(d["before"] == before, f"solo: counter started at the old profile total {before}") |
| 186 | page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000) |
| 187 | page.wait_for_timeout(500) |
| 188 | pts = int(page.locator("#menu-points").inner_text().strip()) |
| 189 | check(pts == before + 12, f"solo: menu shows new total {pts} == {before + 12}") |
| 190 | check(not errs, f"solo: no page errors {errs[:3]}") |
| 191 | shot(page, "t1173-local-solo-4-menu.png") |
| 192 | |
| 193 | print("\n== logged-in solo, 0 points ==") |
| 194 | pick_and_play(page) |
| 195 | page.wait_for_timeout(600) |
| 196 | force_gameover(page, 0) |
| 197 | page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000) |
| 198 | page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=6000) |
| 199 | st = state(page) |
| 200 | check(st["counterVisible"] and int(st["counter"]) == pts, f"zero: shows total {st['counter']} briefly") |
| 201 | check(st["dbg"]["spawned"] == 0, "zero: no blocks") |
| 202 | shot(page, "t1173-local-solo-zero.png") |
| 203 | page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000) |
| 204 | ctx.close() |
| 205 | |
| 206 | |
| 207 | def test_offline(browser): |
| 208 | print("\n== logged-in Offline Strijd: win a round, then lose ==") |
| 209 | ctx = browser.new_context(viewport={"width": 1280, "height": 800}) |
| 210 | page = ctx.new_page() |
| 211 | login(page, 1) |
| 212 | pick_and_play(page, "#btn-offline") |
| 213 | page.wait_for_function("() => app.playToken && app.battle", timeout=8000) |
| 214 | page.wait_for_timeout(3600) |
| 215 | page.evaluate("() => { app.core.score = 8; for (const b of app.battle.bots) b.core.state = 'gameover'; }") |
| 216 | watch_reward(page, "offline-won", "You won!", 8) |
| 217 | page.wait_for_function("() => app.battle && app.battle.round === 2 && app.mode === 'playing'", timeout=6000) |
| 218 | check(True, "offline: continued to round 2 after the reward") |
| 219 | shot(page, "t1173-local-offline-round2.png") |
| 220 | page.wait_for_function("() => app.playToken", timeout=8000) |
| 221 | page.wait_for_timeout(3600) |
| 222 | force_gameover(page, 5) |
| 223 | watch_reward(page, "offline-lost", "You lost...", 5) |
| 224 | page.wait_for_function("() => !document.getElementById('offline-result').hidden", timeout=6000) |
| 225 | check(True, "offline: lost → offline result screen (as before)") |
| 226 | shot(page, "t1173-local-offline-result.png") |
| 227 | ctx.close() |
| 228 | |
| 229 | |
| 230 | def test_online(browser): |
| 231 | print("\n== online two players ==") |
| 232 | c1 = browser.new_context(viewport={"width": 1280, "height": 800}) |
| 233 | c2 = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=2) |
| 234 | p1, p2 = c1.new_page(), c2.new_page() |
| 235 | login(p1, 1, "index.html?online=1") |
| 236 | login(p2, 2, "index.html?online=1") |
| 237 | for p in (p1, p2): |
| 238 | p.locator("#online-panel").wait_for(state="visible", timeout=8000) |
| 239 | if p.locator("#online-lobby").is_visible() and p.locator("#btn-leave-lobby").is_visible(): |
| 240 | p.locator("#btn-leave-lobby").click() |
| 241 | p.wait_for_timeout(400) |
| 242 | p1.locator("#btn-create").click() |
| 243 | p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000) |
| 244 | code = p1.locator("#lobby-code").inner_text().strip() |
| 245 | p2.locator("#join-code").fill(code) |
| 246 | p2.locator("#btn-join").click() |
| 247 | p2.locator("#online-lobby").wait_for(state="visible", timeout=8000) |
| 248 | p1.locator("#btn-ready").click() |
| 249 | p2.locator("#btn-ready").click() |
| 250 | start = p1.locator("#btn-start") |
| 251 | for _ in range(20): |
| 252 | if start.is_visible() and start.is_enabled(): |
| 253 | break |
| 254 | p1.wait_for_timeout(400) |
| 255 | start.click() |
| 256 | for p in (p1, p2): |
| 257 | p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000) |
| 258 | b1 = p1.evaluate("() => app.onlineBefore") |
| 259 | b2 = p2.evaluate("() => app.onlineBefore") |
| 260 | p1.wait_for_timeout(1500) |
| 261 | p1.evaluate("() => { app.core.score = 9; }") |
| 262 | p2.evaluate("() => { app.core.score = 6; }") |
| 263 | p1.wait_for_timeout(1200) # let the scores reach the server |
| 264 | p2.evaluate("() => { app.core.state = 'gameover'; app.core.gameOverTime = 0; }") |
| 265 | p1.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000) |
| 266 | p2.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000) |
| 267 | p1.wait_for_timeout(300) |
| 268 | s1, s2 = state(p1), state(p2) |
| 269 | check(s1["title"] == "You won!", f"online winner sees You won! ({s1['title']!r})") |
| 270 | check(s2["title"] == "You lost...", f"online loser sees You lost... ({s2['title']!r})") |
| 271 | shot(p1, "t1173-local-online-winner-1-centered.png") |
| 272 | shot(p2, "t1173-local-online-mobile-loser-1-centered.png") |
| 273 | p1.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'count'", timeout=8000) |
| 274 | p1.wait_for_timeout(400) |
| 275 | shot(p1, "t1173-local-online-winner-2-counting.png") |
| 276 | p2.wait_for_function("() => Reward.debugState() && ['count','hold'].includes(Reward.debugState().phase)", timeout=8000) |
| 277 | p2.wait_for_timeout(200) |
| 278 | shot(p2, "t1173-local-online-mobile-loser-2-counting.png") |
| 279 | for p, b, earned, tag in ((p1, b1, 9, "winner"), (p2, b2, 6, "loser")): |
| 280 | p.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=20000) |
| 281 | d = state(p)["dbg"] |
| 282 | check(d["before"] == b and d["after"] - d["before"] == earned, |
| 283 | f"online {tag}: {d['before']} → {d['after']} (+{earned})") |
| 284 | shot(p2, "t1173-local-online-mobile-loser-3-final.png") |
| 285 | # Mobile: tap during the hold continues. |
| 286 | p2.tap("#reward") |
| 287 | p2.wait_for_function("() => document.getElementById('reward').hidden", timeout=3000) |
| 288 | check(True, "mobile tap in the hold continues") |
| 289 | for p, tag in ((p1, "winner"), (p2, "loser")): |
| 290 | p.wait_for_function("() => app.mode === 'online' && !document.getElementById('online-lobby').hidden", timeout=15000) |
| 291 | check(True, f"online {tag}: back in the lobby afterwards") |
| 292 | shot(p1, "t1173-local-online-winner-4-lobby.png") |
| 293 | c1.close() |
| 294 | c2.close() |
| 295 | |
| 296 | |
| 297 | def main(): |
| 298 | global URL |
| 299 | port = free_port() |
| 300 | URL = f"http://127.0.0.1:{port}/" |
| 301 | data = Path(tempfile.mkdtemp(prefix="meteors-t1173-")) |
| 302 | proc = start_php(port, data, "/tmp/t1173-php.log") |
| 303 | try: |
| 304 | with sync_playwright() as p: |
| 305 | browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True) |
| 306 | only = sys.argv[1:] or ["out", "solo", "offline", "online"] |
| 307 | if "out" in only: |
| 308 | test_logged_out_solo(browser) |
| 309 | if "solo" in only: |
| 310 | test_solo(browser) |
| 311 | if "offline" in only: |
| 312 | test_offline(browser) |
| 313 | if "online" in only: |
| 314 | test_online(browser) |
| 315 | browser.close() |
| 316 | finally: |
| 317 | proc.terminate() |
| 318 | try: |
| 319 | proc.wait(timeout=3) |
| 320 | except Exception: |
| 321 | proc.kill() |
| 322 | if FAILURES: |
| 323 | print("FAILURES:") |
| 324 | for f in FAILURES: |
| 325 | print(" -", f) |
| 326 | return 1 |
| 327 | print("ALL OK") |
| 328 | return 0 |
| 329 | |
| 330 | |
| 331 | if __name__ == "__main__": |
| 332 | sys.exit(main()) |
projects-timfalken-com meteors