BlueGit

projects-timfalken-com meteors

Files

meteors / test / minis-flights-playwright.py

minis-flights-playwright.py

minis-flights-playwright.py 11.6 KiB Download Raw
1#!/usr/bin/env python3
2"""Layout and flight-arc visuals for t1125 (wide / narrow / mobile)."""
3from __future__ import annotations
4
5import socket
6import subprocess
7import sys
8import time
9from pathlib import Path
10
11from playwright.sync_api import sync_playwright
12
13ROOT = Path("/workspace/meteors")
14OUT = Path("/workspace/meteors-shots")
15OUT.mkdir(parents=True, exist_ok=True)
16CHROME = "/usr/bin/google-chrome"
17CHROME_ARGS = [
18 "--use-gl=angle",
19 "--use-angle=swiftshader",
20 "--no-sandbox",
21 "--disable-dev-shm-usage",
22 "--disable-gpu-sandbox",
23]
24FAILURES = []
25
26
27def free_port():
28 s = socket.socket()
29 s.bind(("127.0.0.1", 0))
30 port = s.getsockname()[1]
31 s.close()
32 return port
33
34
35def check(cond, msg):
36 if not cond:
37 FAILURES.append(msg)
38 print("FAIL", msg)
39 else:
40 print("OK ", msg)
41 return cond
42
43
44def shot(page, name):
45 path = OUT / name
46 page.screenshot(path=str(path), full_page=False)
47 print(f"wrote {path} ({path.stat().st_size} bytes)")
48 return path
49
50
51def start_http(port):
52 proc = subprocess.Popen(
53 ["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1",
54 "--directory", str(ROOT / "build")],
55 stdout=subprocess.DEVNULL,
56 stderr=subprocess.DEVNULL,
57 )
58 time.sleep(0.35)
59 if proc.poll() is not None:
60 raise RuntimeError("http.server failed to start")
61 return proc
62
63
64def open_offline(page, url, round_n=1):
65 page.goto(url, wait_until="domcontentloaded", timeout=15000)
66 page.wait_for_timeout(400)
67 page.locator("#btn-offline").click()
68 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
69 page.locator("#btn-planet-go").click()
70 page.wait_for_function(
71 "() => app && app.mode === 'playing' && app.offline && app.battle && app.core",
72 timeout=10000,
73 )
74 if round_n != 1:
75 page.evaluate(
76 """(round) => {
77 teardownPlay();
78 startPlay({ planet: app.planet, offline: true, round: round });
79 }""",
80 round_n,
81 )
82 page.wait_for_function(
83 "() => app && app.mode === 'playing' && app.battle && app.miniLayout",
84 timeout=8000,
85 )
86 page.wait_for_timeout(250)
87
88
89LAYOUT_INFO = """() => {
90 const plan = app.miniLayout || {};
91 const fieldEl = app.scene && app.scene.canvas;
92 const fr = fieldEl ? fieldEl.getBoundingClientRect() : null;
93 const minis = [...document.querySelectorAll('#minis .mini')].map((el) => {
94 const r = el.getBoundingClientRect();
95 const c = el.querySelector('canvas');
96 const cr = c ? c.getBoundingClientRect() : r;
97 return {
98 id: el.getAttribute('data-player'),
99 left: r.left, right: r.right, top: r.top, bottom: r.bottom,
100 cx: cr.left + cr.width / 2,
101 cy: cr.top + cr.height / 2
102 };
103 });
104 return {
105 mode: plan.mode,
106 sidesClass: document.getElementById('minis').classList.contains('sides'),
107 n: plan.n,
108 field: fr ? { left: fr.left, right: fr.right, top: fr.top, bottom: fr.bottom,
109 x: app.fieldX, y: app.fieldY, w: app.fieldW, h: app.fieldH } : null,
110 positions: plan.positions || [],
111 minis,
112 tile: app.tile,
113 vw: window.innerWidth,
114 vh: window.innerHeight
115 };
116}"""
117
118
119INJECT_FLIGHTS = """() => {
120 const plan = app.miniLayout;
121 const field = app.scene.canvas.getBoundingClientRect();
122 const minis = [...document.querySelectorAll('#minis .mini')];
123 function anchor(id, inner) {
124 const el = document.querySelector('#minis .mini[data-player=\"' + id + '\"] canvas');
125 if (!el) return { x: 80, y: 80 };
126 const r = el.getBoundingClientRect();
127 if (plan && plan.mode === 'sides') {
128 const mid = field.left + field.width / 2;
129 const left = (r.left + r.width / 2) < mid;
130 if (inner) return { x: left ? r.right : r.left, y: r.top + r.height / 2 };
131 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
132 }
133 return { x: r.left + r.width / 2, y: inner ? r.bottom : r.top };
134 }
135 const bots = (app.battle.bots || []).map(b => b.id);
136 const a = bots[0] || 'bot-1';
137 const b = bots[1] || bots[0] || 'bot-2';
138 const pStart = {
139 x: field.left + field.width / 2,
140 y: field.top + 4
141 };
142 if (typeof Online.clearFlights === 'function') Online.clearFlights();
143 const flights = [
144 { id: 'vis-p2e', client_id: 'vis-p2e', from_id: 'player', target_id: a, miss: false, color: 0, flight_duration: 1.2, age: 0.55 },
145 { id: 'vis-e2p', client_id: 'vis-e2p', from_id: a, target_id: 'player', miss: false, color: 1, flight_duration: 1.2, age: 0.55 },
146 { id: 'vis-e2e', client_id: 'vis-e2e', from_id: a, target_id: b, miss: false, color: 2, flight_duration: 1.2, age: 0.55 },
147 { id: 'vis-emiss', client_id: 'vis-emiss', from_id: b, target_id: null, miss: true, color: 3, flight_duration: 1.2, age: 0.45 }
148 ];
149 const aOut = anchor(a, true);
150 const bOut = anchor(b, true);
151 const locals = {
152 'vis-p2e': { from_id: 'player', color: 0, startX: pStart.x, startY: pStart.y, col: 4 },
153 'vis-e2p': { from_id: a, color: 1, startX: aOut.x, startY: aOut.y },
154 'vis-e2e': { from_id: a, color: 2, startX: aOut.x, startY: aOut.y },
155 'vis-emiss': { from_id: b, color: 3, startX: bOut.x, startY: bOut.y }
156 };
157 Online.spawnFlights(flights, locals);
158 Online.tickFlights();
159 const front = [...document.querySelectorAll('#flights .flight')].map(el => ({
160 cls: el.className,
161 transform: el.style.transform,
162 opacity: el.style.opacity,
163 parent: 'front'
164 }));
165 const back = [...document.querySelectorAll('#flights-back .flight')].map(el => ({
166 cls: el.className,
167 transform: el.style.transform,
168 opacity: el.style.opacity,
169 parent: 'back'
170 }));
171 return {
172 front: front.length,
173 back: back.length,
174 kinds: (Online._flights || []).map(f => ({
175 kind: f.kind, miss: f.miss,
176 startScale: f.startScale, endScale: f.endScale,
177 parent: (f.el && f.el.parentElement && f.el.parentElement.id) || ''
178 }))
179 };
180}"""
181
182
183def assert_sides(info, tag, expect_rows=False):
184 check(info["mode"] == "sides", f"{tag}: mode is sides (got {info['mode']})")
185 check(info["sidesClass"], f"{tag}: #minis has .sides")
186 field = info["field"]
187 minis = info["minis"]
188 check(len(minis) >= 1, f"{tag}: at least one mini ({len(minis)})")
189 if not field or not minis:
190 return
191 for i, m in enumerate(minis):
192 if i % 2 == 0:
193 check(m["right"] <= field["left"] + 2,
194 f"{tag}: mini {i} ({m['id']}) is on the left of the field "
195 f"(right={m['right']:.1f} field.left={field['left']:.1f})")
196 else:
197 check(m["left"] >= field["right"] - 2,
198 f"{tag}: mini {i} ({m['id']}) is on the right of the field "
199 f"(left={m['left']:.1f} field.right={field['right']:.1f})")
200 check(m["bottom"] <= field["bottom"] + 8,
201 f"{tag}: mini {i} does not hang below the field")
202 check(m["top"] >= 50,
203 f"{tag}: mini {i} stays under the HUD (top={m['top']:.1f})")
204 if expect_rows and len(minis) >= 3:
205 # 3rd (index 2) is left, stacked above the first
206 check(minis[2]["bottom"] <= minis[0]["top"] + 4,
207 f"{tag}: third mini is stacked above the first "
208 f"(b={minis[2]['bottom']:.1f} vs top={minis[0]['top']:.1f})")
209
210
211def assert_top(info, tag):
212 check(info["mode"] == "top", f"{tag}: mode is top (got {info['mode']})")
213 check(not info["sidesClass"], f"{tag}: #minis is not .sides")
214 field = info["field"]
215 minis = info["minis"]
216 check(len(minis) >= 1, f"{tag}: at least one mini")
217 if not field or not minis:
218 return
219 for i, m in enumerate(minis):
220 check(m["bottom"] <= field["top"] + 12,
221 f"{tag}: mini {i} sits above the field "
222 f"(bottom={m['bottom']:.1f} field.top={field['top']:.1f})")
223
224
225def assert_flights(info, tag, expect_behind=True):
226 check(info["front"] >= 3, f"{tag}: front flights present ({info['front']})")
227 kinds = {k["kind"]: k for k in info["kinds"]}
228 check("player-to-enemy" in kinds, f"{tag}: player-to-enemy")
229 check("enemy-to-player" in kinds, f"{tag}: enemy-to-player")
230 check("enemy-miss" in kinds, f"{tag}: enemy-miss")
231 if "player-to-enemy" in kinds:
232 k = kinds["player-to-enemy"]
233 check(k["startScale"] > k["endScale"],
234 f"{tag}: player-to-enemy shrinks ({k['startScale']:.2f}→{k['endScale']:.2f})")
235 if "enemy-to-player" in kinds:
236 k = kinds["enemy-to-player"]
237 check(k["endScale"] > k["startScale"],
238 f"{tag}: enemy-to-player grows ({k['startScale']:.2f}→{k['endScale']:.2f})")
239 if "enemy-to-enemy" in kinds:
240 k = kinds["enemy-to-enemy"]
241 check(abs(k["startScale"] - k["endScale"]) < 0.05,
242 f"{tag}: enemy-to-enemy stays small ({k['startScale']:.2f})")
243 check(k["parent"] == "flights-back",
244 f"{tag}: enemy-to-enemy is in #flights-back (got {k['parent']})")
245 if expect_behind:
246 check(info["back"] >= 1, f"{tag}: at least one behind-field flight")
247 if "enemy-miss" in kinds:
248 k = kinds["enemy-miss"]
249 check(k["startScale"] < 0.7,
250 f"{tag}: enemy-miss starts small ({k['startScale']:.2f})")
251 check(k["parent"] == "flights",
252 f"{tag}: enemy-miss is in #flights (got {k['parent']})")
253
254
255def run_viewport(browser, url, name, width, height, is_mobile, round_n, expect_mode):
256 context = browser.new_context(
257 viewport={"width": width, "height": height},
258 device_scale_factor=1,
259 is_mobile=is_mobile,
260 has_touch=is_mobile,
261 )
262 page = context.new_page()
263 open_offline(page, url, round_n=round_n)
264 page.wait_for_timeout(300)
265 info = page.evaluate(LAYOUT_INFO)
266 print(f"--- {name} layout:", {k: info[k] for k in ('mode', 'n', 'tile', 'vw', 'vh', 'sidesClass')})
267 if expect_mode == "sides":
268 assert_sides(info, name, expect_rows=(round_n >= 12))
269 else:
270 assert_top(info, name)
271 shot(page, f"t1125-{name}-layout.png")
272
273 flights = page.evaluate(INJECT_FLIGHTS)
274 print(f"--- {name} flights:", flights)
275 assert_flights(flights, name)
276 shot(page, f"t1125-{name}-flights.png")
277 context.close()
278
279
280def main():
281 port = free_port()
282 http = start_http(port)
283 url = f"http://127.0.0.1:{port}/"
284 try:
285 with sync_playwright() as p:
286 browser = p.chromium.launch(
287 executable_path=CHROME,
288 args=CHROME_ARGS,
289 headless=True,
290 )
291 # Desktop wide: 2 opponents (round 2) alternating L/R
292 run_viewport(browser, url, "desktop-wide", 1280, 900, False, 2, "sides")
293 # Many opponents, stacked rows (round 25 → 8 bots)
294 run_viewport(browser, url, "desktop-wide-many", 1400, 900, False, 25, "sides")
295 # Desktop narrow: top layout
296 run_viewport(browser, url, "desktop-narrow", 720, 800, False, 2, "top")
297 # Mobile
298 run_viewport(browser, url, "mobile", 393, 851, True, 2, "top")
299 browser.close()
300 finally:
301 http.terminate()
302 try:
303 http.wait(timeout=3)
304 except subprocess.TimeoutExpired:
305 http.kill()
306
307 if FAILURES:
308 print(f"\n{len(FAILURES)} failure(s):")
309 for f in FAILURES:
310 print(" -", f)
311 return 1
312 print("\nall minis/flights checks passed")
313 return 0
314
315
316if __name__ == "__main__":
317 sys.exit(main())