BlueGit

projects-timfalken-com meteors

test: side-mini layout, flight kinds and shot_flights (t1125)

Unit tests cover side vs top, alternating L/R stacks, parabola and
scale classification. PHP checks from_id and that a third player
sees shot_flights. Playwright shots cover desktop wide, stacked
rows, desktop narrow and mobile.

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
67097d3c1da4509dbff962003b28cbc813a0e5ff
Parent
2559ff60
3 files changed +477 −0
server/tests/run.php +40 −0
@@ -235,6 +235,46 @@ try {
235 235 $store->leaveLobby('local:test_user_1');
236 236 $store->leaveLobby('local:test_user_2');
237 237
238 echo "\nshot_flights (t1125)\n";
239 $e = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
240 $store->joinLobby('local:test_user_2', 'test_user_2', $e['code']);
241 $store->joinLobby('local:test_user_3', 'test_user_3', $e['code']);
242 $store->setReady('local:test_user_1', true);
243 $store->setReady('local:test_user_2', true);
244 $store->setReady('local:test_user_3', true);
245 $store->startGame('local:test_user_1');
246 $store->testMissOverride = 0.0;
247 $shots = $store->recordShots('local:test_user_1', [
248 ['client_id' => 'f1', 'color' => 2],
249 ]);
250 $store->testMissOverride = null;
251 expect(count($shots) === 1, 'one recorded shot');
252 expect(($shots[0]['from_id'] ?? null) === 'local:test_user_1', 'shot_results includes from_id');
253 expect(isset($shots[0]['age']) && almostEqual((float) $shots[0]['age'], 0.0), 'own result age is 0');
254
255 $view3 = $store->viewFor('local:test_user_3');
256 expect(isset($view3['shot_flights']) && is_array($view3['shot_flights']), 'viewFor exposes shot_flights');
257 $found = null;
258 foreach ($view3['shot_flights'] as $f) {
259 if (($f['client_id'] ?? '') === 'f1') {
260 $found = $f;
261 break;
262 }
263 }
264 expect($found !== null, 'third player sees the shot in shot_flights');
265 if ($found) {
266 expect($found['from_id'] === 'local:test_user_1', 'shot_flights.from_id is the shooter');
267 expect($found['target_id'] === 'local:test_user_2' || $found['target_id'] === 'local:test_user_3', 'hit lands on a living opponent');
268 expect($found['miss'] === false, 'forced hit is not a miss');
269 expect($found['age'] >= 0 && $found['age'] < 2.0, 'age is seconds since created');
270 expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');
271 }
272 $view1 = $store->viewFor('local:test_user_1');
273 expect(count($view1['shot_flights']) >= 1, 'shooter also sees shot_flights (client de-dupes)');
274 $store->leaveLobby('local:test_user_1');
275 $store->leaveLobby('local:test_user_2');
276 $store->leaveLobby('local:test_user_3');
277
238 278 echo "\nConfig helpers\n";
239 279
240 280 $cfg = config();
@@ -235,6 +235,46 @@ try {
235$store->leaveLobby('local:test_user_1');
235$store->leaveLobby('local:test_user_1');
236$store->leaveLobby('local:test_user_2');
236$store->leaveLobby('local:test_user_2');
237
237
238echo "\nshot_flights (t1125)\n";
239$e = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
240$store->joinLobby('local:test_user_2', 'test_user_2', $e['code']);
241$store->joinLobby('local:test_user_3', 'test_user_3', $e['code']);
242$store->setReady('local:test_user_1', true);
243$store->setReady('local:test_user_2', true);
244$store->setReady('local:test_user_3', true);
245$store->startGame('local:test_user_1');
246$store->testMissOverride = 0.0;
247$shots = $store->recordShots('local:test_user_1', [
248 ['client_id' => 'f1', 'color' => 2],
249]);
250$store->testMissOverride = null;
251expect(count($shots) === 1, 'one recorded shot');
252expect(($shots[0]['from_id'] ?? null) === 'local:test_user_1', 'shot_results includes from_id');
253expect(isset($shots[0]['age']) && almostEqual((float) $shots[0]['age'], 0.0), 'own result age is 0');
254
255$view3 = $store->viewFor('local:test_user_3');
256expect(isset($view3['shot_flights']) && is_array($view3['shot_flights']), 'viewFor exposes shot_flights');
257$found = null;
258foreach ($view3['shot_flights'] as $f) {
259 if (($f['client_id'] ?? '') === 'f1') {
260 $found = $f;
261 break;
262 }
263}
264expect($found !== null, 'third player sees the shot in shot_flights');
265if ($found) {
266 expect($found['from_id'] === 'local:test_user_1', 'shot_flights.from_id is the shooter');
267 expect($found['target_id'] === 'local:test_user_2' || $found['target_id'] === 'local:test_user_3', 'hit lands on a living opponent');
268 expect($found['miss'] === false, 'forced hit is not a miss');
269 expect($found['age'] >= 0 && $found['age'] < 2.0, 'age is seconds since created');
270 expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');
271}
272$view1 = $store->viewFor('local:test_user_1');
273expect(count($view1['shot_flights']) >= 1, 'shooter also sees shot_flights (client de-dupes)');
274$store->leaveLobby('local:test_user_1');
275$store->leaveLobby('local:test_user_2');
276$store->leaveLobby('local:test_user_3');
277
238echo "\nConfig helpers\n";
278echo "\nConfig helpers\n";
239
279
240$cfg = config();
280$cfg = config();
test/mini-layout.test.js added +120 −0
@@ -0,0 +1,120 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const MiniLayout = require('../src/miniLayout.js');
6 const Online = require('../src/online.js');
7
8 describe('MiniLayout (t1125)', () =>
9 {
10 it('uses sides on a wide desktop and top on a narrow one', () =>
11 {
12 const wide = MiniLayout.plan(1280, 900, 2, 70, 8);
13 assert.equal(wide.mode, 'sides', '1280×900 with 2 opponents is sides');
14 assert.ok(wide.tile >= MiniLayout.MIN_TILE_FOR_SIDES, 'tiles stay large enough');
15 assert.equal(wide.miniH, 0, 'sides mode does not reserve a top band');
16 assert.equal(wide.positions.length, 2);
17
18 const justUnder = MiniLayout.plan(MiniLayout.MIN_VIEWPORT_FOR_SIDES - 1, 900, 2, 70, 8);
19 assert.equal(justUnder.mode, 'top', 'just under 960 px stays on top');
20 const narrow = MiniLayout.plan(720, 800, 2, 70, 8);
21 assert.equal(narrow.mode, 'top', '720-wide keeps the top row');
22 assert.ok(narrow.miniH > 0, 'top mode reserves height above the field');
23 assert.equal(narrow.positions.length, 0);
24
25 const mobile = MiniLayout.plan(393, 851, 1, 60, 6);
26 assert.equal(mobile.mode, 'top', 'phone stays on the top layout');
27 });
28
29 it('alternates first left, second right, third left, and stacks upward', () =>
30 {
31 const plan = MiniLayout.plan(1400, 900, 6, 70, 8);
32 assert.equal(plan.mode, 'sides');
33 assert.equal(plan.positions.length, 6);
34 const sides = plan.positions.map(p => p.side);
35 assert.deepEqual(sides, ['left', 'right', 'left', 'right', 'left', 'right']);
36 const rows = plan.positions.map(p => p.row);
37 assert.deepEqual(rows, [0, 0, 1, 1, 2, 2]);
38
39 // Lowest row aligns with (or near) the field bottom; higher rows go up.
40 const lefts = plan.positions.filter(p => p.side === 'left');
41 assert.ok(lefts[0].y + lefts[0].h <= plan.fieldY + plan.fieldH + 2,
42 'first row sits at the field bottom');
43 assert.ok(lefts[1].y < lefts[0].y, 'second row is above the first');
44 assert.ok(lefts[2].y < lefts[1].y, 'third row is above the second');
45 // Same x for a column
46 assert.equal(lefts[0].x, lefts[1].x);
47 assert.ok(lefts[0].x + lefts[0].w <= plan.fieldX - MiniLayout.GAP + 0.5);
48 const rights = plan.positions.filter(p => p.side === 'right');
49 assert.ok(rights[0].x >= plan.fieldX + plan.fieldW + MiniLayout.GAP - 0.5);
50 });
51
52 it('shrinks minis so stacked rows stay under the HUD', () =>
53 {
54 const plan = MiniLayout.plan(1400, 800, 12, 70, 8);
55 assert.equal(plan.mode, 'sides');
56 for (const p of plan.positions)
57 {
58 assert.ok(p.y >= 70 + 3, 'mini top stays below the HUD, y=' + p.y);
59 assert.ok(p.canvasH >= 40, 'minis do not shrink below a readable size');
60 }
61 });
62
63 it('solo (n=0) never reserves minis', () =>
64 {
65 const plan = MiniLayout.plan(1280, 900, 0, 70, 8);
66 assert.equal(plan.mode, 'top');
67 assert.equal(plan.miniH, 0);
68 assert.equal(plan.positions.length, 0);
69 });
70 });
71
72 describe('Online flight visuals (t1125)', () =>
73 {
74 it('classifies player, enemy, and miss kinds', () =>
75 {
76 const orig = Online.playerId;
77 Online.playerId = function () { return 'player'; };
78 try
79 {
80 assert.equal(Online.flightKind('player', 'bot-1', false), 'player-to-enemy');
81 assert.equal(Online.flightKind('bot-1', 'player', false), 'enemy-to-player');
82 assert.equal(Online.flightKind('bot-1', 'bot-2', false), 'enemy-to-enemy');
83 assert.equal(Online.flightKind('player', null, true), 'player-miss');
84 assert.equal(Online.flightKind('bot-1', null, true), 'enemy-miss');
85 assert.equal(Online.flightKind('bot-3', 'player', false), 'enemy-to-player');
86 }
87 finally
88 { Online.playerId = orig; }
89 });
90
91 it('arc is a parabola that peaks at mid-flight above the chord', () =>
92 {
93 const start = { x: 0, y: 200 };
94 const end = { x: 100, y: 200 };
95 const h = 80;
96 const mid = Online.arcPoint(start, end, 0.5, h);
97 assert.equal(mid.x, 50);
98 // 4*h*t*(1-t) at t=0.5 is h, so y = 200 - 80
99 assert.equal(mid.y, 120);
100 const a = Online.arcPoint(start, end, 0, h);
101 const b = Online.arcPoint(start, end, 1, h);
102 assert.deepEqual(a, start);
103 assert.deepEqual(b, end);
104 // Symmetric and always above (smaller y) the chord
105 const q1 = Online.arcPoint(start, end, 0.25, h);
106 const q3 = Online.arcPoint(start, end, 0.75, h);
107 assert.equal(q1.y, q3.y);
108 assert.ok(q1.y < 200 && mid.y < q1.y);
109 });
110
111 it('arc height scales with distance, clamped', () =>
112 {
113 const short = Online.arcHeight({ x: 0, y: 0 }, { x: 10, y: 0 });
114 const long = Online.arcHeight({ x: 0, y: 0 }, { x: 2000, y: 0 });
115 assert.equal(short, 48);
116 assert.equal(long, 220);
117 const mid = Online.arcHeight({ x: 0, y: 0 }, { x: 400, y: 0 });
118 assert.ok(Math.abs(mid - 400 * 0.28) < 1e-9);
119 });
120 });
@@ -0,0 +1,120 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const MiniLayout = require('../src/miniLayout.js');
6const Online = require('../src/online.js');
7
8describe('MiniLayout (t1125)', () =>
9{
10 it('uses sides on a wide desktop and top on a narrow one', () =>
11 {
12 const wide = MiniLayout.plan(1280, 900, 2, 70, 8);
13 assert.equal(wide.mode, 'sides', '1280×900 with 2 opponents is sides');
14 assert.ok(wide.tile >= MiniLayout.MIN_TILE_FOR_SIDES, 'tiles stay large enough');
15 assert.equal(wide.miniH, 0, 'sides mode does not reserve a top band');
16 assert.equal(wide.positions.length, 2);
17
18 const justUnder = MiniLayout.plan(MiniLayout.MIN_VIEWPORT_FOR_SIDES - 1, 900, 2, 70, 8);
19 assert.equal(justUnder.mode, 'top', 'just under 960 px stays on top');
20 const narrow = MiniLayout.plan(720, 800, 2, 70, 8);
21 assert.equal(narrow.mode, 'top', '720-wide keeps the top row');
22 assert.ok(narrow.miniH > 0, 'top mode reserves height above the field');
23 assert.equal(narrow.positions.length, 0);
24
25 const mobile = MiniLayout.plan(393, 851, 1, 60, 6);
26 assert.equal(mobile.mode, 'top', 'phone stays on the top layout');
27 });
28
29 it('alternates first left, second right, third left, and stacks upward', () =>
30 {
31 const plan = MiniLayout.plan(1400, 900, 6, 70, 8);
32 assert.equal(plan.mode, 'sides');
33 assert.equal(plan.positions.length, 6);
34 const sides = plan.positions.map(p => p.side);
35 assert.deepEqual(sides, ['left', 'right', 'left', 'right', 'left', 'right']);
36 const rows = plan.positions.map(p => p.row);
37 assert.deepEqual(rows, [0, 0, 1, 1, 2, 2]);
38
39 // Lowest row aligns with (or near) the field bottom; higher rows go up.
40 const lefts = plan.positions.filter(p => p.side === 'left');
41 assert.ok(lefts[0].y + lefts[0].h <= plan.fieldY + plan.fieldH + 2,
42 'first row sits at the field bottom');
43 assert.ok(lefts[1].y < lefts[0].y, 'second row is above the first');
44 assert.ok(lefts[2].y < lefts[1].y, 'third row is above the second');
45 // Same x for a column
46 assert.equal(lefts[0].x, lefts[1].x);
47 assert.ok(lefts[0].x + lefts[0].w <= plan.fieldX - MiniLayout.GAP + 0.5);
48 const rights = plan.positions.filter(p => p.side === 'right');
49 assert.ok(rights[0].x >= plan.fieldX + plan.fieldW + MiniLayout.GAP - 0.5);
50 });
51
52 it('shrinks minis so stacked rows stay under the HUD', () =>
53 {
54 const plan = MiniLayout.plan(1400, 800, 12, 70, 8);
55 assert.equal(plan.mode, 'sides');
56 for (const p of plan.positions)
57 {
58 assert.ok(p.y >= 70 + 3, 'mini top stays below the HUD, y=' + p.y);
59 assert.ok(p.canvasH >= 40, 'minis do not shrink below a readable size');
60 }
61 });
62
63 it('solo (n=0) never reserves minis', () =>
64 {
65 const plan = MiniLayout.plan(1280, 900, 0, 70, 8);
66 assert.equal(plan.mode, 'top');
67 assert.equal(plan.miniH, 0);
68 assert.equal(plan.positions.length, 0);
69 });
70});
71
72describe('Online flight visuals (t1125)', () =>
73{
74 it('classifies player, enemy, and miss kinds', () =>
75 {
76 const orig = Online.playerId;
77 Online.playerId = function () { return 'player'; };
78 try
79 {
80 assert.equal(Online.flightKind('player', 'bot-1', false), 'player-to-enemy');
81 assert.equal(Online.flightKind('bot-1', 'player', false), 'enemy-to-player');
82 assert.equal(Online.flightKind('bot-1', 'bot-2', false), 'enemy-to-enemy');
83 assert.equal(Online.flightKind('player', null, true), 'player-miss');
84 assert.equal(Online.flightKind('bot-1', null, true), 'enemy-miss');
85 assert.equal(Online.flightKind('bot-3', 'player', false), 'enemy-to-player');
86 }
87 finally
88 { Online.playerId = orig; }
89 });
90
91 it('arc is a parabola that peaks at mid-flight above the chord', () =>
92 {
93 const start = { x: 0, y: 200 };
94 const end = { x: 100, y: 200 };
95 const h = 80;
96 const mid = Online.arcPoint(start, end, 0.5, h);
97 assert.equal(mid.x, 50);
98 // 4*h*t*(1-t) at t=0.5 is h, so y = 200 - 80
99 assert.equal(mid.y, 120);
100 const a = Online.arcPoint(start, end, 0, h);
101 const b = Online.arcPoint(start, end, 1, h);
102 assert.deepEqual(a, start);
103 assert.deepEqual(b, end);
104 // Symmetric and always above (smaller y) the chord
105 const q1 = Online.arcPoint(start, end, 0.25, h);
106 const q3 = Online.arcPoint(start, end, 0.75, h);
107 assert.equal(q1.y, q3.y);
108 assert.ok(q1.y < 200 && mid.y < q1.y);
109 });
110
111 it('arc height scales with distance, clamped', () =>
112 {
113 const short = Online.arcHeight({ x: 0, y: 0 }, { x: 10, y: 0 });
114 const long = Online.arcHeight({ x: 0, y: 0 }, { x: 2000, y: 0 });
115 assert.equal(short, 48);
116 assert.equal(long, 220);
117 const mid = Online.arcHeight({ x: 0, y: 0 }, { x: 400, y: 0 });
118 assert.ok(Math.abs(mid - 400 * 0.28) < 1e-9);
119 });
120});
test/minis-flights-playwright.py added +317 −0
@@ -0,0 +1,317 @@
1 #!/usr/bin/env python3
2 """Layout and flight-arc visuals for t1125 (wide / narrow / mobile)."""
3 from __future__ import annotations
4
5 import socket
6 import subprocess
7 import sys
8 import time
9 from pathlib import Path
10
11 from playwright.sync_api import sync_playwright
12
13 ROOT = Path("/workspace/meteors")
14 OUT = Path("/workspace/meteors-shots")
15 OUT.mkdir(parents=True, exist_ok=True)
16 CHROME = "/usr/bin/google-chrome"
17 CHROME_ARGS = [
18 "--use-gl=angle",
19 "--use-angle=swiftshader",
20 "--no-sandbox",
21 "--disable-dev-shm-usage",
22 "--disable-gpu-sandbox",
23 ]
24 FAILURES = []
25
26
27 def 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
35 def 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
44 def 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
51 def 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
64 def 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
89 LAYOUT_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
119 INJECT_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
183 def 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
211 def 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
225 def 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
255 def 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
280 def 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
316 if __name__ == "__main__":
317 sys.exit(main())
@@ -0,0 +1,317 @@
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())