BlueGit

projects-timfalken-com meteors

Files

meteors / server / tests / run.php

run.php

run.php 27.1 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')), 1 / 9), 'Aurel power 1/9 (gravity 2 since t1199)');
201expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60 - 0.55 / 9), 'Aurel miss ~53.9%');
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')) === 10, 'Aurel displayed Power 10');
207
208echo "\nGravity minimum 2 (t1199)\n";
209foreach (Planets::all() as $pl) {
210 expect((float) $pl['jumpsToClear'] >= 2.0, 'catalog gravity >= 2: ' . $pl['id']);
211}
212foreach (['aurel', 'lunara', 'zephyr'] as $pid) {
213 expect(almostEqual((float) Planets::byId($pid)['jumpsToClear'], 2.0), "$pid raised to 2.0");
214}
215expect(Planets::GRAVITY_MIN === 2.0 && Planets::GRAVITY_MAX === 4.0, 'gravity range constants');
216expect(almostEqual(Planets::clampGravity(1.0), 2.0) && almostEqual(Planets::clampGravity(3.3), 3.3) && almostEqual(Planets::clampGravity(9), 4.0), 'clampGravity');
217$tdG = Planets::displayValues(['jumpsToClear' => 4, 'fallTime' => 3, 'riseTime' => 1.5]);
218expect(almostEqual($tdG['gravity'], 29.43) && $tdG['gravityPct'] === 300, 'gravity 4 shows 300% / 29.43 g');
219expect(Planets::displayValues(Planets::byId('terra'))['gravityPct'] === 100, 'Terra 100%');
220expect(Planets::displayPower(Planets::byId('cinder')) === 92, 'Cinder displayed Power 92 (5% miss)');
221expect(Planets::displayValues(Planets::byId('cinder'))['power'] === 92, 'Cinder displayValues Power 92');
222
223$store->leaveLobby('local:test_user_1');
224$store->leaveLobby('local:test_user_2');
225$pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');
226$store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');
227$presented = $store->presentLobby($pl, 'local:test_user_1');
228$byId = [];
229foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }
230expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');
231expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');
232expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60 - 0.55 / 9), 'host miss from Aurel Power');
233expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');
234
235$store->setPlanet('local:test_user_1', 'wisp');
236$presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');
237foreach ($presented['players'] as $plr) {
238 if ($plr['is_me']) {
239 expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp');
240 }
241}
242
243try {
244 $store->setPlanet('local:test_user_1', 'no-such-world');
245 expect(false, 'unknown planet must throw');
246} catch (RuntimeException $e) {
247 expect(true, 'unknown planet rejected');
248}
249
250$store->setReady('local:test_user_1', true);
251$store->setReady('local:test_user_2', true);
252$store->startGame('local:test_user_1');
253$me = $store->member($pl['id'], 'local:test_user_1');
254expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');
255$guest = $store->member($pl['id'], 'local:test_user_2');
256expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');
257try {
258 $store->setPlanet('local:test_user_1', 'terra');
259 expect(false, 'setPlanet during play must throw');
260} catch (RuntimeException $e) {
261 expect(true, 'planet locked once the match starts');
262}
263$store->leaveLobby('local:test_user_1');
264$store->leaveLobby('local:test_user_2');
265
266echo "\nshot_flights (t1125)\n";
267$e = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
268$store->joinLobby('local:test_user_2', 'test_user_2', $e['code']);
269$store->joinLobby('local:test_user_3', 'test_user_3', $e['code']);
270$store->setReady('local:test_user_1', true);
271$store->setReady('local:test_user_2', true);
272$store->setReady('local:test_user_3', true);
273$store->startGame('local:test_user_1');
274$store->testMissOverride = 0.0;
275$shots = $store->recordShots('local:test_user_1', [
276 ['client_id' => 'f1', 'color' => 2, 'col' => 6, 'y' => 12.4],
277]);
278$store->testMissOverride = null;
279expect(count($shots) === 1, 'one recorded shot');
280expect(($shots[0]['from_id'] ?? null) === 'local:test_user_1', 'shot_results includes from_id');
281expect(isset($shots[0]['age']) && almostEqual((float) $shots[0]['age'], 0.0), 'own result age is 0');
282
283$view3 = $store->viewFor('local:test_user_3');
284expect(isset($view3['shot_flights']) && is_array($view3['shot_flights']), 'viewFor exposes shot_flights');
285$found = null;
286foreach ($view3['shot_flights'] as $f) {
287 if (($f['client_id'] ?? '') === 'f1') {
288 $found = $f;
289 break;
290 }
291}
292expect($found !== null, 'third player sees the shot in shot_flights');
293if ($found) {
294 expect($found['from_id'] === 'local:test_user_1', 'shot_flights.from_id is the shooter');
295 expect($found['target_id'] === 'local:test_user_2' || $found['target_id'] === 'local:test_user_3', 'hit lands on a living opponent');
296 expect($found['miss'] === false, 'forced hit is not a miss');
297 expect($found['age'] >= 0 && $found['age'] < 2.0, 'age is seconds since created');
298 expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');
299 expect(isset($found['land_col']) && $found['land_col'] >= 0 && $found['land_col'] <= 9, 'shot_flights has land_col 0–9');
300 expect(($shots[0]['land_col'] ?? null) === $found['land_col'], 'recordShots and shot_flights share land_col');
301 expect(($shots[0]['col'] ?? null) === 6, 'shot_results echoes launch col');
302 expect(isset($shots[0]['y']) && abs((float) $shots[0]['y'] - 12.4) < 0.01, 'shot_results echoes launch y');
303 expect(($found['col'] ?? null) === 6, 'shot_flights has launch col (t1136)');
304 expect(isset($found['y']) && abs((float) $found['y'] - 12.4) < 0.01, 'shot_flights has launch y (t1136)');
305}
306// Incoming carries the same land_col (t1126).
307$targetId = $found['target_id'] ?? $shots[0]['target_id'];
308$pdoLand = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
309$pdoLand->exec('UPDATE shots SET deliver_at = 0 WHERE client_id = "f1"');
310$incLand = $store->viewFor($targetId);
311$incHit = null;
312foreach ($incLand['incoming'] as $row) {
313 if (($row['client_id'] ?? '') === 'f1') {
314 $incHit = $row;
315 break;
316 }
317}
318expect($incHit !== null, 'target receives incoming for the shot');
319if ($incHit) {
320 expect(($incHit['land_col'] ?? null) === $found['land_col'], 'incoming.land_col matches the flight');
321}
322$view1 = $store->viewFor('local:test_user_1');
323expect(count($view1['shot_flights']) >= 1, 'shooter also sees shot_flights (client de-dupes)');
324$store->leaveLobby('local:test_user_1');
325$store->leaveLobby('local:test_user_2');
326$store->leaveLobby('local:test_user_3');
327
328
329echo "\nBlocks registry and unlock thresholds\n";
330require_once dirname(__DIR__) . '/lib/Blocks.php';
331$allBlocks = Blocks::all();
332expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');
333for ($i = 0; $i < 5; $i++) {
334 expect(Blocks::threshold($i) === 0, "terra index $i is free");
335}
336expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');
337$prev = 500;
338for ($i = 6; $i < count($allBlocks); $i++) {
339 $t = Blocks::threshold($i);
340 if ($t <= $prev) {
341 expect(false, "threshold at $i should be > $prev, got $t");
342 break;
343 }
344 $prev = $t;
345}
346expect($prev > 500, 'later thresholds grow');
347expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');
348expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');
349expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');
350$terraIds = [];
351foreach ($allBlocks as $i => $b) {
352 if ($i >= 5) break;
353 $terraIds[] = $b['id'];
354}
355
356echo "\nLifetime points, anti-cheat, custom planets\n";
357$ptsStore = Store::open($tmp);
358$u = 'local:designer_a';
359$v = 'local:designer_b';
360expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');
361$t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
362expect($t1 === 200, 'first award adds 200');
363$t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
364expect($t2 === 200, 'same award_key is idempotent');
365$t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');
366expect($t3 === 250, 'second key adds 50');
367
368$ptsStore->testNow = 1_000_000;
369$ses = $ptsStore->playBegin($u, 'solo');
370expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');
371$ptsStore->testNow = 1_000_001;
372$fin = $ptsStore->playFinish($u, $ses['token'], 9000);
373expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');
374expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');
375$again = $ptsStore->playFinish($u, $ses['token'], 9000);
376expect(!empty($again['already']), 'second finish of same token is a no-op');
377
378$ptsStore->testNow = 2_000_000;
379$ses2 = $ptsStore->playBegin($u, 'offline');
380$ptsStore->testNow = 2_000_010;
381$fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);
382expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');
383expect($fin2['lifetime_points'] === 290, 'capped award is added');
384
385$ptsStore->testNow = 3_000_000;
386$ses3 = $ptsStore->playBegin($u, 'solo');
387$ptsStore->testNow = 3_000_020;
388$fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);
389expect($fin3['awarded'] === 17, 'honest score under the cap is kept');
390
391try {
392 $ptsStore->saveCustomPlanet($u, [
393 'name' => 'Lockworld', 'people' => 'Lockers',
394 'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5,
395 'colors' => array_merge($terraIds, ['rune-fehu']),
396 ]);
397 // 6 items? no that's 6. Use 4 terra + fehu
398 expect(false, 'should not reach (wrong colors count would throw first)');
399} catch (RuntimeException $e) {
400 expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'),
401 'invalid colors refused: ' . $e->getMessage());
402}
403
404try {
405 $ptsStore->saveCustomPlanet($u, [
406 'name' => 'Lockworld', 'people' => 'Lockers',
407 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'],
408 ]);
409 expect(false, 'locked block should throw');
410} catch (RuntimeException $e) {
411 expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());
412}
413
414try {
415 $ptsStore->saveCustomPlanet($u, [
416 'name' => 'Ghost', 'people' => 'Ghosts',
417 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'],
418 ]);
419 expect(false, 'unknown block should throw');
420} catch (RuntimeException $e) {
421 expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());
422}
423
424try {
425 $ptsStore->saveCustomPlanet($u, [
426 'name' => 'Twins', 'people' => 'Twins',
427 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]],
428 ]);
429 expect(false, 'duplicate block should throw');
430} catch (RuntimeException $e) {
431 expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'),
432 'duplicate block refused: ' . $e->getMessage());
433}
434
435$snap = $ptsStore->saveCustomPlanet($u, [
436 'name' => 'My World', 'people' => 'My People',
437 'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1,
438 'colors' => $terraIds,
439]);
440expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');
441expect($snap['custom'] === true, 'snapshot is marked custom');
442expect($snap['name'] === 'My World', 'name stored');
443expect(count($snap['colors']) === 5, 'five colors in snapshot');
444expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');
445expect($snap['owner_id'] === $u, 'owner_id set');
446
447$listed = $ptsStore->listCustomPlanets($u);
448expect(count($listed) === 1, 'owner lists the planet');
449
450echo "Custom planet gravity clamp (t1199)\n";
451$low = $ptsStore->saveCustomPlanet($u, [
452 'name' => 'Lowgrav', 'people' => 'Floaters',
453 'jumpsToClear' => 1, 'fallTime' => 3, 'riseTime' => 1.5,
454 'colors' => $terraIds,
455]);
456expect(almostEqual((float) $low['jumpsToClear'], 2.0), 'saving gravity 1 stores 2');
457$rawPdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
458$rawPdo->exec("UPDATE custom_planets SET jumps_to_clear = 1.2 WHERE id = '" . $low['id'] . "'");
459$lowList = array_values(array_filter($ptsStore->listCustomPlanets($u), fn($pl) => $pl['id'] === $low['id']));
460expect(count($lowList) === 1 && almostEqual((float) $lowList[0]['jumpsToClear'], 2.0), 'an old row with 1.2 loads as 2');
461$ptsStore->deleteCustomPlanet($u, $low['id']);
462
463
464echo "Last chosen planet (t1196)\n";
465expect($ptsStore->lastPlanet($u) === null, 'no last planet stored yet');
466expect($ptsStore->profilePayload($u)['last_planet'] === null, 'payload last_planet null');
467expect($ptsStore->setLastPlanet($u, 'terra') === 'terra', 'standard planet saved');
468expect($ptsStore->lastPlanet($u) === 'terra', 'standard planet read back');
469$ptsStore->setLastPlanet($u, $snap['id']);
470expect($ptsStore->profilePayload($u)['last_planet'] === $snap['id'], 'own custom planet saved and in payload');
471foreach (['', 'nope', str_repeat('x', 80)] as $bad) {
472 try { $ptsStore->setLastPlanet($u, $bad); expect(false, 'bad planet accepted: ' . $bad); }
473 catch (RuntimeException $e) { expect(true, 'bad planet refused: ' . substr($bad, 0, 8)); }
474}
475try { $ptsStore->setLastPlanet($v, $snap['id']); expect(false, 'other user may not pick my custom planet'); }
476catch (RuntimeException $e) { expect(true, "someone else's custom planet refused"); }
477expect($ptsStore->lastPlanet($u) === $snap['id'], 'refused writes keep the old value');
478
479expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');
480
481try {
482 $ptsStore->setPlanet($u, $snap['id']);
483 expect(false, 'setPlanet without a lobby should throw');
484} catch (RuntimeException $e) {
485 expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());
486}
487
488$lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);
489$view = $ptsStore->viewFor($u);
490$meP = $view['lobby']['players'][0]['planet'] ?? null;
491expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');
492expect(!empty($meP['custom']), 'presented planet is custom');
493expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');
494expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');
495
496$ptsStore->joinLobby($v, 'B', $lobby['code']);
497$viewB = $ptsStore->viewFor($v);
498$seen = null;
499foreach ($viewB['lobby']['players'] as $plr) {
500 if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }
501}
502expect($seen !== null, 'other player sees the custom planet snapshot');
503expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');
504
505try {
506 $ptsStore->setPlanet($v, $snap['id']);
507 expect(false, 'cannot pick someone else\'s custom planet');
508} catch (RuntimeException $e) {
509 expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());
510}
511
512$ptsStore->leaveLobby($u);
513$ptsStore->leaveLobby($v);
514$ptsStore->deleteCustomPlanet($u, $snap['id']);
515expect($ptsStore->lastPlanet($u) === null, "deleted custom planet → last_planet falls back to null (t1196)");
516expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');
517
518// Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.
519$snap2 = $ptsStore->saveCustomPlanet($u, [
520 'name' => 'Frozen', 'people' => 'Ice',
521 'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1,
522 'colors' => $terraIds,
523]);
524$lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);
525$ptsStore->joinLobby($v, 'B', $lobby2['code']);
526$ptsStore->setReady($u, true);
527$ptsStore->setReady($v, true);
528$ptsStore->startGame($u);
529$ptsStore->saveCustomPlanet($u, [
530 'id' => $snap2['id'],
531 'name' => 'Changed', 'people' => 'Ice',
532 'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3,
533 'colors' => $terraIds,
534]);
535$viewMid = $ptsStore->viewFor($v);
536$midP = null;
537foreach ($viewMid['lobby']['players'] as $plr) {
538 if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }
539}
540expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');
541expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');
542$ptsStore->leaveLobby($u);
543$ptsStore->leaveLobby($v);
544
545// Online award is idempotent and server-side.
546$u3 = 'local:online_award_a';
547$v3 = 'local:online_award_b';
548$lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');
549$ptsStore->joinLobby($v3, 'B', $lob['code']);
550$ptsStore->setReady($u3, true);
551$ptsStore->setReady($v3, true);
552$ptsStore->startGame($u3);
553$ptsStore->viewFor($u3, null, 80, false, []);
554$ptsStore->viewFor($u3, null, 80, true, []);
555expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');
556$ptsStore->viewFor($u3, null, 999, true, []);
557expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');
558
559$ptsStore->setLocale($u, 'nl');
560expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
561try {
562 $ptsStore->setLocale($u, 'xx');
563 expect(false, 'unknown locale should throw');
564} catch (RuntimeException $e) {
565 expect(true, 'unknown locale refused');
566}
567
568echo "\nConfig helpers\n";
569
570
571$cfg = config();
572expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
573expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
574expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');
575expect(authConfigured() === false, 'auth is unconfigured without a secret');
576putenv('METEORS_CLIENT_SECRET=test-secret-value');
577// config file empty secret falls back to env
578$cfg2 = config();
579expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');
580putenv('METEORS_CLIENT_SECRET');
581
582echo "\n$passed passed, $failed failed\n";
583
584// cleanup
585$files = new RecursiveIteratorIterator(
586 new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
587 RecursiveIteratorIterator::CHILD_FIRST
588);
589foreach ($files as $f) {
590 $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
591}
592@rmdir($tmp);
593
594exit($failed === 0 ? 0 : 1);