BlueGit

projects-timfalken-com meteors

Files

meteors / server / tests / run.php

run.php

run.php 25.4 KiB Download Raw
1<?php
2declare(strict_types=1);
3// php server/tests/run.php
4define('METEORS_NO_SESSION', true);
5require dirname(__DIR__) . '/lib/bootstrap.php';
6require dirname(__DIR__) . '/lib/Store.php';
7
8$failed = 0;
9$passed = 0;
10
11function expect(bool $cond, string $msg): void
12{
13 global $failed, $passed;
14 if ($cond) {
15 $passed++;
16 echo " ok $msg\n";
17 } else {
18 $failed++;
19 echo " FAIL $msg\n";
20 }
21}
22
23function almostEqual(float $a, float $b, float $eps = 1e-6): bool
24{
25 return abs($a - $b) <= $eps;
26}
27
28$tmp = sys_get_temp_dir() . '/meteors-test-' . bin2hex(random_bytes(6));
29mkdir($tmp, 0775, true);
30putenv('METEORS_DATA_DIR=' . $tmp);
31
32echo "Login return target (t1193)\n";
33expect(loginReturnTarget(null) === 'menu', 'no return param → main menu');
34expect(loginReturnTarget('') === 'menu', 'empty return → main menu');
35expect(loginReturnTarget('online') === 'online', 'return=online → online play');
36expect(loginReturnTarget('https://evil.example/') === 'menu', 'unknown/URL value → main menu (no open redirect)');
37expect(loginReturnTarget(['online']) === 'menu', 'array value → main menu');
38expect(loginReturnPath('menu') === 'index.html', 'menu path has no online flag');
39expect(loginReturnPath(null) === 'index.html', 'missing session value → menu');
40expect(loginReturnPath('online') === 'index.html?online=1', 'online path opens the online panel');
41$cbSrc = (string) file_get_contents(dirname(__DIR__) . '/callback.php');
42expect(strpos($cbSrc, "index.html?online=1'") === false, 'callback no longer hard-codes ?online=1');
43expect(strpos($cbSrc, 'loginReturnPath(') !== false, 'callback uses loginReturnPath');
44$authSrc = (string) file_get_contents(dirname(__DIR__) . '/auth.php');
45expect(strpos($authSrc, "loginReturnTarget(\$_GET['return']") !== false, 'auth.php stores the return target');
46
47echo "Store: lobby and game\n";
48$store = Store::open($tmp);
49
50$a = $store->createLobby('local:test_user_1', 'test_user_1', 0.30);
51expect(isset($a['id'], $a['code']), 'create lobby returns id and code');
52expect($a['status'] === 'waiting', 'new lobby is waiting');
53expect(strlen($a['code']) === 4, 'code is 4 characters');
54expect(almostEqual((float) $a['miss_chance'], 0.30), 'default miss chance 0.30');
55
56$view = $store->viewFor('local:test_user_1');
57expect($view['lobby']['players'][0]['is_host'] === true, 'creator is host');
58expect($view['lobby']['can_start'] === false, 'cannot start alone');
59
60try {
61 $store->startGame('local:test_user_1');
62 expect(false, 'start alone should throw');
63} catch (RuntimeException $e) {
64 expect(str_contains($e->getMessage(), 'twee'), 'start alone is refused: ' . $e->getMessage());
65}
66
67$joined = $store->joinLobby('local:test_user_2', 'test_user_2', $a['code']);
68expect($joined['id'] === $a['id'], 'second player joins by code');
69$view = $store->viewFor('local:test_user_1');
70expect(count($view['lobby']['players']) === 2, 'two players in lobby');
71expect($view['lobby']['can_start'] === false, 'cannot start until both ready');
72
73$store->setReady('local:test_user_1', true);
74$store->setReady('local:test_user_2', true);
75$view = $store->viewFor('local:test_user_1');
76expect($view['lobby']['all_ready'] === true, 'all ready');
77expect($view['lobby']['can_start'] === true, 'host can start when all ready and 2+');
78
79$view2 = $store->viewFor('local:test_user_2');
80expect($view2['lobby']['can_start'] === false, 'non-host cannot start');
81
82try {
83 $store->startGame('local:test_user_2');
84 expect(false, 'non-host start should throw');
85} catch (RuntimeException $e) {
86 expect(str_contains($e->getMessage(), 'host'), 'non-host start refused');
87}
88
89$started = $store->startGame('local:test_user_1');
90expect($started['status'] === 'playing', 'game starts');
91
92// Shots: force miss by using miss_chance 1.0 on a fresh lobby later.
93// Here miss is 0.30 — fire many shots and check some hits and some misses, or set chance.
94$results = $store->recordShots('local:test_user_1', [
95 ['client_id' => 'c1', 'color' => 2],
96 ['client_id' => 'c2', 'color' => -1],
97]);
98expect(count($results) === 2, 'two shot results');
99expect(isset($results[0]['miss'], $results[0]['flight_duration']), 'result has miss and duration');
100expect(almostEqual($results[0]['flight_duration'], METEORS_FLIGHT_DURATION), 'flight duration 1.2');
101
102// Incoming is delayed until deliver_at.
103$inc = $store->viewFor('local:test_user_2');
104$hits = array_filter($results, fn ($r) => !$r['miss']);
105if ($hits) {
106 expect(count($inc['incoming']) === 0, 'incoming not delivered before flight duration');
107} else {
108 expect(true, 'all missed — no incoming expected');
109}
110
111// Fast-forward: rewrite deliver_at in the sqlite file.
112$pdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
113$pdo->exec('UPDATE shots SET deliver_at = 0 WHERE to_user = "local:test_user_2"');
114$inc = $store->viewFor('local:test_user_2');
115$expectedHits = count($hits);
116expect(count($inc['incoming']) === $expectedHits, 'incoming delivered after deliver_at (' . count($inc['incoming']) . " vs $expectedHits)");
117$inc2 = $store->viewFor('local:test_user_2');
118expect(count($inc2['incoming']) === 0, 'incoming is delivered only once');
119
120// Elimination and podium.
121$store->updateSnapshot('local:test_user_2', ['score' => 3, 'blocks' => []], 3, true);
122$view = $store->viewFor('local:test_user_1');
123expect($view['lobby']['status'] === 'finished', 'game finishes when one remains');
124$ranks = $view['lobby']['rankings'];
125expect(count($ranks) >= 2, 'rankings present');
126$first = $ranks[0];
127expect($first['place'] === 1 && $first['id'] === 'local:test_user_1', 'survivor is 1st');
128$second = $ranks[1];
129expect($second['place'] === 2 && $second['id'] === 'local:test_user_2', 'eliminated is 2nd');
130
131// Podium wait: not yet reset.
132$view = $store->viewFor('local:test_user_1');
133expect($view['lobby']['status'] === 'finished', 'still finished during podium');
134
135$pdo->exec('UPDATE lobbies SET finished = ' . (time() - 6));
136$view = $store->viewFor('local:test_user_1');
137expect($view['lobby']['status'] === 'waiting', 'back to lobby after podium seconds');
138expect($view['lobby']['players'][0]['ready'] === false, 'ready flags reset');
139
140// Host leave transfers host.
141$store->leaveLobby('local:test_user_1');
142$view = $store->viewFor('local:test_user_2');
143expect($view['lobby']['host_id'] === 'local:test_user_2', 'host transfers to remaining player');
144
145// Mid-game leave counts as elimination.
146$store->leaveLobby('local:test_user_2');
147$b = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
148$store->joinLobby('local:test_user_2', 'test_user_2', $b['code']);
149$store->setReady('local:test_user_1', true);
150$store->setReady('local:test_user_2', true);
151$store->startGame('local:test_user_1');
152$store->leaveLobby('local:test_user_2');
153$view = $store->viewFor('local:test_user_1');
154expect($view['lobby']['status'] === 'finished', 'leave mid-game finishes if one remains');
155expect($view['lobby']['rankings'][0]['id'] === 'local:test_user_1', 'stayer wins');
156
157// Miss chance 1.0: all miss. Need a fresh game with 2 players.
158// Leave leftover memberships.
159$store->leaveLobby('local:test_user_1');
160$c = $store->createLobby('local:test_user_1', 'test_user_1', 1.0);
161$store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);
162$store->setReady('local:test_user_1', true);
163$store->setReady('local:test_user_2', true);
164$store->startGame('local:test_user_1');
165$store->testMissOverride = 1.0;
166$allMiss = $store->recordShots('local:test_user_1', [
167 ['client_id' => 'm1', 'color' => 0],
168 ['client_id' => 'm2', 'color' => 1],
169 ['client_id' => 'm3', 'color' => 2],
170]);
171$store->testMissOverride = null;
172expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'forced miss 1.0 → all miss');
173
174$d = null;
175$store->leaveLobby('local:test_user_1');
176$store->leaveLobby('local:test_user_2');
177$d = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
178$store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
179$store->setReady('local:test_user_1', true);
180$store->setReady('local:test_user_2', true);
181$store->startGame('local:test_user_1');
182$store->testMissOverride = 0.0;
183$allHit = $store->recordShots('local:test_user_1', [
184 ['client_id' => 'h1', 'color' => 0],
185 ['client_id' => 'h2', 'color' => 1],
186]);
187$store->testMissOverride = null;
188expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'forced miss 0 → all hit the other player');
189
190// Eliminated player is not a target.
191$store->updateSnapshot('local:test_user_2', null, 0, true);
192$none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' => 0]]);
193// Game may already be finished; recordShots on finished returns [].
194expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
195
196
197echo "\nPlanets and per-sender Power miss\n";
198expect(count(Planets::all()) >= 8 && count(Planets::all()) <= 12, 'catalog has 8–12 planets');
199expect(Planets::known('terra') && Planets::known('cinder') && Planets::known('aurel'), 'terra, cinder, aurel exist');
200expect(almostEqual(Planets::power(Planets::byId('aurel')), 0.0), 'Aurel power 0');
201expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel miss 60%');
202expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');
203expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');
204$td = Planets::displayValues(Planets::byId('terra'));
205expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 44, 'Terra display g/d/F/Power');
206expect(Planets::displayPower(Planets::byId('aurel')) === 0, 'Aurel displayed Power 0');
207expect(Planets::displayPower(Planets::byId('cinder')) === 92, 'Cinder displayed Power 92 (5% miss)');
208expect(Planets::displayValues(Planets::byId('cinder'))['power'] === 92, 'Cinder displayValues Power 92');
209
210$store->leaveLobby('local:test_user_1');
211$store->leaveLobby('local:test_user_2');
212$pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');
213$store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');
214$presented = $store->presentLobby($pl, 'local:test_user_1');
215$byId = [];
216foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }
217expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');
218expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');
219expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60), 'host miss from Aurel Power');
220expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');
221
222$store->setPlanet('local:test_user_1', 'wisp');
223$presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');
224foreach ($presented['players'] as $plr) {
225 if ($plr['is_me']) {
226 expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp');
227 }
228}
229
230try {
231 $store->setPlanet('local:test_user_1', 'no-such-world');
232 expect(false, 'unknown planet must throw');
233} catch (RuntimeException $e) {
234 expect(true, 'unknown planet rejected');
235}
236
237$store->setReady('local:test_user_1', true);
238$store->setReady('local:test_user_2', true);
239$store->startGame('local:test_user_1');
240$me = $store->member($pl['id'], 'local:test_user_1');
241expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');
242$guest = $store->member($pl['id'], 'local:test_user_2');
243expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');
244try {
245 $store->setPlanet('local:test_user_1', 'terra');
246 expect(false, 'setPlanet during play must throw');
247} catch (RuntimeException $e) {
248 expect(true, 'planet locked once the match starts');
249}
250$store->leaveLobby('local:test_user_1');
251$store->leaveLobby('local:test_user_2');
252
253echo "\nshot_flights (t1125)\n";
254$e = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
255$store->joinLobby('local:test_user_2', 'test_user_2', $e['code']);
256$store->joinLobby('local:test_user_3', 'test_user_3', $e['code']);
257$store->setReady('local:test_user_1', true);
258$store->setReady('local:test_user_2', true);
259$store->setReady('local:test_user_3', true);
260$store->startGame('local:test_user_1');
261$store->testMissOverride = 0.0;
262$shots = $store->recordShots('local:test_user_1', [
263 ['client_id' => 'f1', 'color' => 2, 'col' => 6, 'y' => 12.4],
264]);
265$store->testMissOverride = null;
266expect(count($shots) === 1, 'one recorded shot');
267expect(($shots[0]['from_id'] ?? null) === 'local:test_user_1', 'shot_results includes from_id');
268expect(isset($shots[0]['age']) && almostEqual((float) $shots[0]['age'], 0.0), 'own result age is 0');
269
270$view3 = $store->viewFor('local:test_user_3');
271expect(isset($view3['shot_flights']) && is_array($view3['shot_flights']), 'viewFor exposes shot_flights');
272$found = null;
273foreach ($view3['shot_flights'] as $f) {
274 if (($f['client_id'] ?? '') === 'f1') {
275 $found = $f;
276 break;
277 }
278}
279expect($found !== null, 'third player sees the shot in shot_flights');
280if ($found) {
281 expect($found['from_id'] === 'local:test_user_1', 'shot_flights.from_id is the shooter');
282 expect($found['target_id'] === 'local:test_user_2' || $found['target_id'] === 'local:test_user_3', 'hit lands on a living opponent');
283 expect($found['miss'] === false, 'forced hit is not a miss');
284 expect($found['age'] >= 0 && $found['age'] < 2.0, 'age is seconds since created');
285 expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');
286 expect(isset($found['land_col']) && $found['land_col'] >= 0 && $found['land_col'] <= 9, 'shot_flights has land_col 0–9');
287 expect(($shots[0]['land_col'] ?? null) === $found['land_col'], 'recordShots and shot_flights share land_col');
288 expect(($shots[0]['col'] ?? null) === 6, 'shot_results echoes launch col');
289 expect(isset($shots[0]['y']) && abs((float) $shots[0]['y'] - 12.4) < 0.01, 'shot_results echoes launch y');
290 expect(($found['col'] ?? null) === 6, 'shot_flights has launch col (t1136)');
291 expect(isset($found['y']) && abs((float) $found['y'] - 12.4) < 0.01, 'shot_flights has launch y (t1136)');
292}
293// Incoming carries the same land_col (t1126).
294$targetId = $found['target_id'] ?? $shots[0]['target_id'];
295$pdoLand = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
296$pdoLand->exec('UPDATE shots SET deliver_at = 0 WHERE client_id = "f1"');
297$incLand = $store->viewFor($targetId);
298$incHit = null;
299foreach ($incLand['incoming'] as $row) {
300 if (($row['client_id'] ?? '') === 'f1') {
301 $incHit = $row;
302 break;
303 }
304}
305expect($incHit !== null, 'target receives incoming for the shot');
306if ($incHit) {
307 expect(($incHit['land_col'] ?? null) === $found['land_col'], 'incoming.land_col matches the flight');
308}
309$view1 = $store->viewFor('local:test_user_1');
310expect(count($view1['shot_flights']) >= 1, 'shooter also sees shot_flights (client de-dupes)');
311$store->leaveLobby('local:test_user_1');
312$store->leaveLobby('local:test_user_2');
313$store->leaveLobby('local:test_user_3');
314
315
316echo "\nBlocks registry and unlock thresholds\n";
317require_once dirname(__DIR__) . '/lib/Blocks.php';
318$allBlocks = Blocks::all();
319expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');
320for ($i = 0; $i < 5; $i++) {
321 expect(Blocks::threshold($i) === 0, "terra index $i is free");
322}
323expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');
324$prev = 500;
325for ($i = 6; $i < count($allBlocks); $i++) {
326 $t = Blocks::threshold($i);
327 if ($t <= $prev) {
328 expect(false, "threshold at $i should be > $prev, got $t");
329 break;
330 }
331 $prev = $t;
332}
333expect($prev > 500, 'later thresholds grow');
334expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');
335expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');
336expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');
337$terraIds = [];
338foreach ($allBlocks as $i => $b) {
339 if ($i >= 5) break;
340 $terraIds[] = $b['id'];
341}
342
343echo "\nLifetime points, anti-cheat, custom planets\n";
344$ptsStore = Store::open($tmp);
345$u = 'local:designer_a';
346$v = 'local:designer_b';
347expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');
348$t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
349expect($t1 === 200, 'first award adds 200');
350$t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
351expect($t2 === 200, 'same award_key is idempotent');
352$t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');
353expect($t3 === 250, 'second key adds 50');
354
355$ptsStore->testNow = 1_000_000;
356$ses = $ptsStore->playBegin($u, 'solo');
357expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');
358$ptsStore->testNow = 1_000_001;
359$fin = $ptsStore->playFinish($u, $ses['token'], 9000);
360expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');
361expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');
362$again = $ptsStore->playFinish($u, $ses['token'], 9000);
363expect(!empty($again['already']), 'second finish of same token is a no-op');
364
365$ptsStore->testNow = 2_000_000;
366$ses2 = $ptsStore->playBegin($u, 'offline');
367$ptsStore->testNow = 2_000_010;
368$fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);
369expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');
370expect($fin2['lifetime_points'] === 290, 'capped award is added');
371
372$ptsStore->testNow = 3_000_000;
373$ses3 = $ptsStore->playBegin($u, 'solo');
374$ptsStore->testNow = 3_000_020;
375$fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);
376expect($fin3['awarded'] === 17, 'honest score under the cap is kept');
377
378try {
379 $ptsStore->saveCustomPlanet($u, [
380 'name' => 'Lockworld', 'people' => 'Lockers',
381 'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5,
382 'colors' => array_merge($terraIds, ['rune-fehu']),
383 ]);
384 // 6 items? no that's 6. Use 4 terra + fehu
385 expect(false, 'should not reach (wrong colors count would throw first)');
386} catch (RuntimeException $e) {
387 expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'),
388 'invalid colors refused: ' . $e->getMessage());
389}
390
391try {
392 $ptsStore->saveCustomPlanet($u, [
393 'name' => 'Lockworld', 'people' => 'Lockers',
394 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'],
395 ]);
396 expect(false, 'locked block should throw');
397} catch (RuntimeException $e) {
398 expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());
399}
400
401try {
402 $ptsStore->saveCustomPlanet($u, [
403 'name' => 'Ghost', 'people' => 'Ghosts',
404 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'],
405 ]);
406 expect(false, 'unknown block should throw');
407} catch (RuntimeException $e) {
408 expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());
409}
410
411try {
412 $ptsStore->saveCustomPlanet($u, [
413 'name' => 'Twins', 'people' => 'Twins',
414 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]],
415 ]);
416 expect(false, 'duplicate block should throw');
417} catch (RuntimeException $e) {
418 expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'),
419 'duplicate block refused: ' . $e->getMessage());
420}
421
422$snap = $ptsStore->saveCustomPlanet($u, [
423 'name' => 'My World', 'people' => 'My People',
424 'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1,
425 'colors' => $terraIds,
426]);
427expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');
428expect($snap['custom'] === true, 'snapshot is marked custom');
429expect($snap['name'] === 'My World', 'name stored');
430expect(count($snap['colors']) === 5, 'five colors in snapshot');
431expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');
432expect($snap['owner_id'] === $u, 'owner_id set');
433
434$listed = $ptsStore->listCustomPlanets($u);
435expect(count($listed) === 1, 'owner lists the planet');
436
437echo "Last chosen planet (t1196)\n";
438expect($ptsStore->lastPlanet($u) === null, 'no last planet stored yet');
439expect($ptsStore->profilePayload($u)['last_planet'] === null, 'payload last_planet null');
440expect($ptsStore->setLastPlanet($u, 'terra') === 'terra', 'standard planet saved');
441expect($ptsStore->lastPlanet($u) === 'terra', 'standard planet read back');
442$ptsStore->setLastPlanet($u, $snap['id']);
443expect($ptsStore->profilePayload($u)['last_planet'] === $snap['id'], 'own custom planet saved and in payload');
444foreach (['', 'nope', str_repeat('x', 80)] as $bad) {
445 try { $ptsStore->setLastPlanet($u, $bad); expect(false, 'bad planet accepted: ' . $bad); }
446 catch (RuntimeException $e) { expect(true, 'bad planet refused: ' . substr($bad, 0, 8)); }
447}
448try { $ptsStore->setLastPlanet($v, $snap['id']); expect(false, 'other user may not pick my custom planet'); }
449catch (RuntimeException $e) { expect(true, "someone else's custom planet refused"); }
450expect($ptsStore->lastPlanet($u) === $snap['id'], 'refused writes keep the old value');
451
452expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');
453
454try {
455 $ptsStore->setPlanet($u, $snap['id']);
456 expect(false, 'setPlanet without a lobby should throw');
457} catch (RuntimeException $e) {
458 expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());
459}
460
461$lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);
462$view = $ptsStore->viewFor($u);
463$meP = $view['lobby']['players'][0]['planet'] ?? null;
464expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');
465expect(!empty($meP['custom']), 'presented planet is custom');
466expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');
467expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');
468
469$ptsStore->joinLobby($v, 'B', $lobby['code']);
470$viewB = $ptsStore->viewFor($v);
471$seen = null;
472foreach ($viewB['lobby']['players'] as $plr) {
473 if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }
474}
475expect($seen !== null, 'other player sees the custom planet snapshot');
476expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');
477
478try {
479 $ptsStore->setPlanet($v, $snap['id']);
480 expect(false, 'cannot pick someone else\'s custom planet');
481} catch (RuntimeException $e) {
482 expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());
483}
484
485$ptsStore->leaveLobby($u);
486$ptsStore->leaveLobby($v);
487$ptsStore->deleteCustomPlanet($u, $snap['id']);
488expect($ptsStore->lastPlanet($u) === null, "deleted custom planet → last_planet falls back to null (t1196)");
489expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');
490
491// Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.
492$snap2 = $ptsStore->saveCustomPlanet($u, [
493 'name' => 'Frozen', 'people' => 'Ice',
494 'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1,
495 'colors' => $terraIds,
496]);
497$lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);
498$ptsStore->joinLobby($v, 'B', $lobby2['code']);
499$ptsStore->setReady($u, true);
500$ptsStore->setReady($v, true);
501$ptsStore->startGame($u);
502$ptsStore->saveCustomPlanet($u, [
503 'id' => $snap2['id'],
504 'name' => 'Changed', 'people' => 'Ice',
505 'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3,
506 'colors' => $terraIds,
507]);
508$viewMid = $ptsStore->viewFor($v);
509$midP = null;
510foreach ($viewMid['lobby']['players'] as $plr) {
511 if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }
512}
513expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');
514expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');
515$ptsStore->leaveLobby($u);
516$ptsStore->leaveLobby($v);
517
518// Online award is idempotent and server-side.
519$u3 = 'local:online_award_a';
520$v3 = 'local:online_award_b';
521$lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');
522$ptsStore->joinLobby($v3, 'B', $lob['code']);
523$ptsStore->setReady($u3, true);
524$ptsStore->setReady($v3, true);
525$ptsStore->startGame($u3);
526$ptsStore->viewFor($u3, null, 80, false, []);
527$ptsStore->viewFor($u3, null, 80, true, []);
528expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');
529$ptsStore->viewFor($u3, null, 999, true, []);
530expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');
531
532$ptsStore->setLocale($u, 'nl');
533expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
534try {
535 $ptsStore->setLocale($u, 'xx');
536 expect(false, 'unknown locale should throw');
537} catch (RuntimeException $e) {
538 expect(true, 'unknown locale refused');
539}
540
541echo "\nConfig helpers\n";
542
543
544$cfg = config();
545expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
546expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
547expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');
548expect(authConfigured() === false, 'auth is unconfigured without a secret');
549putenv('METEORS_CLIENT_SECRET=test-secret-value');
550// config file empty secret falls back to env
551$cfg2 = config();
552expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');
553putenv('METEORS_CLIENT_SECRET');
554
555echo "\n$passed passed, $failed failed\n";
556
557// cleanup
558$files = new RecursiveIteratorIterator(
559 new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
560 RecursiveIteratorIterator::CHILD_FIRST
561);
562foreach ($files as $f) {
563 $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
564}
565@rmdir($tmp);
566
567exit($failed === 0 ? 0 : 1);