BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

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