BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

Store.php 25.2 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4require_once __DIR__ . '/Planets.php';
5
6final class Store
7{
8 private PDO $pdo;
9 private int $txDepth = 0;
10
11 public function __construct(PDO $pdo)
12 {
13 $this->pdo = $pdo;
14 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
15 $this->migrate();
16 }
17
18 public static function open(?string $dir = null): self
19 {
20 $dir = $dir ?? dataDir();
21 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
22 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
23 }
24 $path = $dir . '/meteors.sqlite';
25 $pdo = new PDO('sqlite:' . $path, null, null, [
26 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
27 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
28 ]);
29 $pdo->exec('PRAGMA journal_mode = WAL');
30 $pdo->exec('PRAGMA foreign_keys = ON');
31 $pdo->exec('PRAGMA busy_timeout = 4000');
32 return new self($pdo);
33 }
34
35 private function migrate(): void
36 {
37 $this->pdo->exec(<<<'SQL'
38CREATE TABLE IF NOT EXISTS lobbies (
39 id TEXT PRIMARY KEY,
40 code TEXT UNIQUE NOT NULL,
41 host_id TEXT NOT NULL,
42 status TEXT NOT NULL DEFAULT 'waiting',
43 miss_chance REAL NOT NULL DEFAULT 0.30,
44 flight_duration REAL NOT NULL DEFAULT 1.2,
45 created INTEGER NOT NULL,
46 started INTEGER,
47 finished INTEGER
48);
49CREATE TABLE IF NOT EXISTS members (
50 lobby_id TEXT NOT NULL,
51 user_id TEXT NOT NULL,
52 name TEXT NOT NULL,
53 ready INTEGER NOT NULL DEFAULT 0,
54 eliminated INTEGER NOT NULL DEFAULT 0,
55 place INTEGER,
56 left_at INTEGER,
57 joined INTEGER NOT NULL,
58 last_seen INTEGER NOT NULL,
59 score INTEGER NOT NULL DEFAULT 0,
60 snapshot TEXT,
61 PRIMARY KEY (lobby_id, user_id)
62);
63CREATE TABLE IF NOT EXISTS shots (
64 id INTEGER PRIMARY KEY AUTOINCREMENT,
65 lobby_id TEXT NOT NULL,
66 from_user TEXT NOT NULL,
67 to_user TEXT,
68 color INTEGER NOT NULL,
69 client_id TEXT,
70 created REAL NOT NULL,
71 deliver_at REAL NOT NULL,
72 delivered INTEGER NOT NULL DEFAULT 0
73);
74CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
75SQL);
76 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
77 }
78
79 private function ensureColumn(string $table, string $column, string $ddl): void
80 {
81 $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
82 foreach ($cols as $c) {
83 if (($c['name'] ?? '') === $column) {
84 return;
85 }
86 }
87 $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl);
88 }
89
90 public function transaction(callable $fn): mixed
91 {
92 if ($this->txDepth > 0) {
93 return $fn();
94 }
95 $this->pdo->beginTransaction();
96 $this->txDepth++;
97 try {
98 $result = $fn();
99 $this->pdo->commit();
100 $this->txDepth--;
101 return $result;
102 } catch (Throwable $e) {
103 $this->txDepth--;
104 if ($this->pdo->inTransaction()) {
105 $this->pdo->rollBack();
106 }
107 throw $e;
108 }
109 }
110
111 private function now(): int
112 {
113 return time();
114 }
115
116 private function nowf(): float
117 {
118 return microtime(true);
119 }
120
121 private function newId(): string
122 {
123 return bin2hex(random_bytes(12));
124 }
125
126 private function newCode(): string
127 {
128 $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
129 $len = strlen($alphabet);
130 for ($attempt = 0; $attempt < 16; $attempt++) {
131 $code = '';
132 for ($i = 0; $i < 4; $i++) {
133 $code .= $alphabet[random_int(0, $len - 1)];
134 }
135 $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
136 $exists->execute([$code]);
137 if (!$exists->fetch()) {
138 return $code;
139 }
140 }
141 throw new RuntimeException('Kon geen unieke lobbycode maken.');
142 }
143
144 public function lobbyForUser(string $userId): ?array
145 {
146 $stmt = $this->pdo->prepare(
147 'SELECT l.* FROM lobbies l
148 JOIN members m ON m.lobby_id = l.id
149 WHERE m.user_id = ? AND m.left_at IS NULL
150 ORDER BY l.created DESC LIMIT 1'
151 );
152 $stmt->execute([$userId]);
153 $row = $stmt->fetch();
154 return $row ?: null;
155 }
156
157 public function getLobby(string $id): ?array
158 {
159 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
160 $stmt->execute([$id]);
161 $row = $stmt->fetch();
162 return $row ?: null;
163 }
164
165 public function getLobbyByCode(string $code): ?array
166 {
167 $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
168 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
169 $stmt->execute([$code]);
170 $row = $stmt->fetch();
171 return $row ?: null;
172 }
173
174 /** @return list<array> */
175 public function members(string $lobbyId, bool $includeLeft = false): array
176 {
177 $sql = 'SELECT * FROM members WHERE lobby_id = ?';
178 if (!$includeLeft) {
179 $sql .= ' AND left_at IS NULL';
180 }
181 $sql .= ' ORDER BY joined ASC';
182 $stmt = $this->pdo->prepare($sql);
183 $stmt->execute([$lobbyId]);
184 return $stmt->fetchAll();
185 }
186
187 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array
188 {
189 return $this->transaction(function () use ($userId, $name, $missChance, $planetId) {
190 $existing = $this->lobbyForUser($userId);
191 if ($existing && $existing['status'] !== 'finished') {
192 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
193 }
194 if ($existing && $existing['status'] === 'finished') {
195 $this->leaveMember($existing['id'], $userId);
196 }
197 $id = $this->newId();
198 $code = $this->newCode();
199 $now = $this->now();
200 $miss = max(0.0, min(1.0, $missChance));
201 $this->pdo->prepare(
202 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
203 VALUES (?,?,?,?,?,?,?)'
204 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
205 $planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
206 $this->pdo->prepare(
207 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
208 VALUES (?,?,?,0,?,?,?)'
209 )->execute([$id, $userId, $name, $now, $now, $planet]);
210 return $this->getLobby($id);
211 });
212 }
213
214 public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array
215 {
216 return $this->transaction(function () use ($userId, $name, $code, $planetId) {
217 $existing = $this->lobbyForUser($userId);
218 if ($existing && $existing['status'] !== 'finished') {
219 if (strcasecmp($existing['code'], $code) === 0) {
220 return $existing;
221 }
222 throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
223 }
224 $lobby = $this->getLobbyByCode($code);
225 if (!$lobby) {
226 throw new RuntimeException('Onbekende lobbycode.');
227 }
228 if ($lobby['status'] !== 'waiting') {
229 throw new RuntimeException('Deze lobby is al begonnen.');
230 }
231 $members = $this->members($lobby['id']);
232 if (count($members) >= METEORS_MAX_PLAYERS) {
233 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
234 }
235 $now = $this->now();
236 $this->pdo->prepare(
237 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
238 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
239 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
240 name = excluded.name,
241 ready = 0,
242 eliminated = 0,
243 place = NULL,
244 left_at = NULL,
245 joined = excluded.joined,
246 last_seen = excluded.last_seen,
247 score = 0,
248 snapshot = NULL,
249 planet_id = excluded.planet_id'
250 )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
251 return $this->getLobby($lobby['id']);
252 });
253 }
254
255 private function leaveMember(string $lobbyId, string $userId): void
256 {
257 $this->pdo->prepare(
258 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
259 )->execute([$this->now(), $lobbyId, $userId]);
260 $lobby = $this->getLobby($lobbyId);
261 if (!$lobby) {
262 return;
263 }
264 $remaining = $this->members($lobbyId);
265 if ($lobby['host_id'] === $userId) {
266 if ($remaining) {
267 $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
268 ->execute([$remaining[0]['user_id'], $lobbyId]);
269 } elseif ($lobby['status'] === 'waiting') {
270 // Empty waiting lobby can stay; a later join by code still works until we want to close it.
271 }
272 }
273 if ($lobby['status'] === 'playing') {
274 $this->assignPlaceIfNeeded($lobbyId, $userId, true);
275 $this->maybeFinish($lobbyId);
276 }
277 }
278
279 public function leaveLobby(string $userId): void
280 {
281 $this->transaction(function () use ($userId) {
282 $lobby = $this->lobbyForUser($userId);
283 if (!$lobby) {
284 return;
285 }
286 $this->leaveMember($lobby['id'], $userId);
287 });
288 }
289
290 public function setReady(string $userId, bool $ready): array
291 {
292 return $this->transaction(function () use ($userId, $ready) {
293 $lobby = $this->lobbyForUser($userId);
294 if (!$lobby) {
295 throw new RuntimeException('Je zit niet in een lobby.');
296 }
297 if ($lobby['status'] !== 'waiting') {
298 throw new RuntimeException('Het spel is al begonnen.');
299 }
300 $this->pdo->prepare(
301 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
302 )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
303 return $this->getLobby($lobby['id']);
304 });
305 }
306
307 public function startGame(string $userId): array
308 {
309 return $this->transaction(function () use ($userId) {
310 $lobby = $this->lobbyForUser($userId);
311 if (!$lobby) {
312 throw new RuntimeException('Je zit niet in een lobby.');
313 }
314 if ($lobby['host_id'] !== $userId) {
315 throw new RuntimeException('Alleen de host kan het spel starten.');
316 }
317 if ($lobby['status'] !== 'waiting') {
318 throw new RuntimeException('Het spel is al begonnen.');
319 }
320 $members = $this->members($lobby['id']);
321 if (count($members) < 2) {
322 throw new RuntimeException('Er zijn minstens twee spelers nodig.');
323 }
324 foreach ($members as $m) {
325 if (!(int) $m['ready']) {
326 throw new RuntimeException('Niet iedereen is gereed.');
327 }
328 }
329 $this->pdo->prepare(
330 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
331 )->execute(['playing', $this->now(), $lobby['id']]);
332 $this->pdo->prepare(
333 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
334 WHERE lobby_id = ? AND left_at IS NULL'
335 )->execute([$lobby['id']]);
336 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
337 return $this->getLobby($lobby['id']);
338 });
339 }
340
341 /** @param list<array{client_id?:string,color?:int}> $shots */
342 public function setPlanet(string $userId, string $planetId): array
343 {
344 return $this->transaction(function () use ($userId, $planetId) {
345 $lobby = $this->lobbyForUser($userId);
346 if (!$lobby) {
347 throw new RuntimeException('Je zit in geen lobby.');
348 }
349 if ($lobby['status'] !== 'waiting') {
350 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
351 }
352 if (!Planets::known($planetId)) {
353 throw new RuntimeException('Onbekende planeet.');
354 }
355 $this->pdo->prepare(
356 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
357 )->execute([$planetId, $this->now(), $lobby['id'], $userId]);
358 return $this->getLobby($lobby['id']);
359 });
360 }
361
362 /** @param array<string,mixed> $member */
363 public function missChanceForMember(array $member): float
364 {
365 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
366 return max(0.0, min(1.0, $this->testMissOverride));
367 }
368 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
369 return Planets::missChanceForId($id);
370 }
371
372 /** @var ?float Tests may force a miss chance without changing the catalog. */
373 public ?float $testMissOverride = null;
374
375 public function recordShots(string $userId, array $shots): array
376 {
377 return $this->transaction(function () use ($userId, $shots) {
378 $lobby = $this->lobbyForUser($userId);
379 if (!$lobby || $lobby['status'] !== 'playing') {
380 return [];
381 }
382 $me = $this->member($lobby['id'], $userId);
383 if (!$me || (int) $me['eliminated']) {
384 return [];
385 }
386 $targets = [];
387 foreach ($this->members($lobby['id']) as $m) {
388 if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
389 $targets[] = $m;
390 }
391 }
392 $results = [];
393 $missChance = $this->missChanceForMember($me);
394 $flight = (float) $lobby['flight_duration'];
395 $now = $this->nowf();
396 $ins = $this->pdo->prepare(
397 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered)
398 VALUES (?,?,?,?,?,?,?,0)'
399 );
400 foreach ($shots as $shot) {
401 $color = isset($shot['color']) ? (int) $shot['color'] : -1;
402 $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
403 $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
404 $to = null;
405 $toName = null;
406 if (!$miss) {
407 $pick = $targets[random_int(0, count($targets) - 1)];
408 $to = $pick['user_id'];
409 $toName = $pick['name'];
410 }
411 $deliver = $now + $flight;
412 $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver]);
413 $results[] = [
414 'id' => (int) $this->pdo->lastInsertId(),
415 'client_id' => $clientId,
416 'miss' => $miss,
417 'target_id' => $to,
418 'target_name' => $toName,
419 'deliver_at' => $deliver,
420 'color' => $color,
421 'flight_duration' => $flight,
422 ];
423 }
424 return $results;
425 });
426 }
427
428 /** @return list<array> undelivered shots whose time has come, marked delivered. */
429 public function takeIncoming(string $lobbyId, string $userId): array
430 {
431 $now = $this->nowf();
432 $stmt = $this->pdo->prepare(
433 'SELECT * FROM shots
434 WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
435 ORDER BY deliver_at ASC, id ASC'
436 );
437 $stmt->execute([$lobbyId, $userId, $now]);
438 $rows = $stmt->fetchAll();
439 if (!$rows) {
440 return [];
441 }
442 $ids = array_column($rows, 'id');
443 $in = implode(',', array_fill(0, count($ids), '?'));
444 $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
445 $incoming = [];
446 foreach ($rows as $r) {
447 $incoming[] = [
448 'id' => (int) $r['id'],
449 'color' => (int) $r['color'],
450 'from_user' => $r['from_user'],
451 'client_id' => $r['client_id'],
452 ];
453 }
454 return $incoming;
455 }
456
457 public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
458 {
459 $lobby = $this->lobbyForUser($userId);
460 if (!$lobby || $lobby['status'] !== 'playing') {
461 return;
462 }
463 $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
464 $fields = 'last_seen = ?';
465 $args = [$this->now()];
466 if ($json !== null) {
467 $fields .= ', snapshot = ?';
468 $args[] = $json;
469 }
470 if ($score !== null) {
471 $fields .= ', score = ?';
472 $args[] = $score;
473 }
474 $args[] = $lobby['id'];
475 $args[] = $userId;
476 $this->pdo->prepare(
477 "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
478 )->execute($args);
479 if ($eliminated) {
480 $this->assignPlaceIfNeeded($lobby['id'], $userId, false);
481 $this->maybeFinish($lobby['id']);
482 }
483 }
484
485 public function member(string $lobbyId, string $userId): ?array
486 {
487 $stmt = $this->pdo->prepare(
488 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
489 );
490 $stmt->execute([$lobbyId, $userId]);
491 $row = $stmt->fetch();
492 return $row ?: null;
493 }
494
495 private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
496 {
497 $m = $this->member($lobbyId, $userId);
498 if (!$m || $m['place'] !== null) {
499 return;
500 }
501 $active = 0;
502 foreach ($this->members($lobbyId) as $row) {
503 if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
504 $active++;
505 }
506 }
507 // First out gets last place = number of current (incl. this) non-left players.
508 $total = count($this->members($lobbyId));
509 $alreadyPlaced = 0;
510 foreach ($this->members($lobbyId, true) as $row) {
511 if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
512 if ($row['place'] !== null) {
513 $alreadyPlaced++;
514 }
515 }
516 }
517 $place = $active + 1; // remaining others + self → this player's place
518 $this->pdo->prepare(
519 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
520 )->execute([$place, $lobbyId, $userId]);
521 }
522
523 public function maybeFinish(string $lobbyId): void
524 {
525 $lobby = $this->getLobby($lobbyId);
526 if (!$lobby || $lobby['status'] !== 'playing') {
527 return;
528 }
529 $alive = [];
530 foreach ($this->members($lobbyId) as $m) {
531 if (!(int) $m['eliminated']) {
532 $alive[] = $m;
533 }
534 }
535 if (count($alive) > 1) {
536 return;
537 }
538 if (count($alive) === 1) {
539 $winner = $alive[0];
540 if ($winner['place'] === null) {
541 $this->pdo->prepare(
542 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
543 )->execute([$lobbyId, $winner['user_id']]);
544 }
545 }
546 $this->pdo->prepare(
547 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
548 )->execute(['finished', $this->now(), $lobbyId]);
549 }
550
551 public function maybeResetLobby(string $lobbyId): void
552 {
553 $lobby = $this->getLobby($lobbyId);
554 if (!$lobby || $lobby['status'] !== 'finished') {
555 return;
556 }
557 $finished = (int) ($lobby['finished'] ?? 0);
558 if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
559 return;
560 }
561 $this->pdo->prepare(
562 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
563 )->execute(['waiting', $lobbyId]);
564 $this->pdo->prepare(
565 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
566 WHERE lobby_id = ? AND left_at IS NULL'
567 )->execute([$lobbyId]);
568 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
569 }
570
571 /** Public view of a lobby for the given user, including incoming shots. */
572 public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
573 {
574 return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
575 $touch = $this->lobbyForUser($userId);
576 if ($touch && $touch['status'] === 'finished') {
577 $this->maybeResetLobby($touch['id']);
578 }
579 if ($touch && $touch['status'] === 'playing') {
580 if ($snapshot !== null || $score !== null || $eliminated) {
581 $this->updateSnapshot($userId, $snapshot, $score, $eliminated);
582 } else {
583 $this->pdo->prepare(
584 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
585 )->execute([$this->now(), $touch['id'], $userId]);
586 }
587 }
588 $shotResults = [];
589 if ($outgoing && $touch && $touch['status'] === 'playing') {
590 $shotResults = $this->recordShots($userId, $outgoing);
591 }
592 $lobby = $this->lobbyForUser($userId);
593 if (!$lobby) {
594 return [
595 'lobby' => null,
596 'incoming' => [],
597 'shot_results' => $shotResults,
598 ];
599 }
600 $incoming = [];
601 if ($lobby['status'] === 'playing') {
602 $incoming = $this->takeIncoming($lobby['id'], $userId);
603 }
604 return [
605 'lobby' => $this->presentLobby($lobby, $userId),
606 'incoming' => $incoming,
607 'shot_results' => $shotResults,
608 ];
609 });
610 }
611
612 public function presentLobby(array $lobby, string $userId): array
613 {
614 $members = $this->members($lobby['id']);
615 $players = [];
616 foreach ($members as $m) {
617 $snap = null;
618 if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
619 $decoded = json_decode($m['snapshot'], true);
620 $snap = is_array($decoded) ? $decoded : null;
621 }
622 $players[] = [
623 'id' => $m['user_id'],
624 'name' => $m['name'],
625 'ready' => (bool) (int) $m['ready'],
626 'eliminated' => (bool) (int) $m['eliminated'],
627 'place' => $m['place'] !== null ? (int) $m['place'] : null,
628 'is_host' => $m['user_id'] === $lobby['host_id'],
629 'is_me' => $m['user_id'] === $userId,
630 'score' => (int) $m['score'],
631 'snapshot' => $m['user_id'] === $userId ? null : $snap,
632 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
633 ];
634 }
635 $rankings = [];
636 if ($lobby['status'] === 'finished' || $lobby['finished']) {
637 $all = $this->members($lobby['id'], true);
638 foreach ($all as $m) {
639 if ($m['place'] !== null) {
640 $rankings[] = [
641 'place' => (int) $m['place'],
642 'id' => $m['user_id'],
643 'name' => $m['name'],
644 'score' => (int) $m['score'],
645 ];
646 }
647 }
648 usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
649 }
650 $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
651 return [
652 'id' => $lobby['id'],
653 'code' => $lobby['code'],
654 'status' => $lobby['status'],
655 'host_id' => $lobby['host_id'],
656 'miss_chance' => (float) $lobby['miss_chance'],
657 'flight_duration' => (float) $lobby['flight_duration'],
658 'players' => $players,
659 'all_ready' => $allReady,
660 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
661 'rankings' => $rankings,
662 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
663 'podium_seconds' => METEORS_PODIUM_SECONDS,
664 ];
665 }
666}