BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

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