BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

Store.php 43.3 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4require_once __DIR__ . '/Planets.php';
5require_once __DIR__ . '/Blocks.php';
6
7final class Store
8{
9 private PDO $pdo;
10 private int $txDepth = 0;
11
12 public function __construct(PDO $pdo)
13 {
14 $this->pdo = $pdo;
15 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
16 $this->migrate();
17 }
18
19 public static function open(?string $dir = null): self
20 {
21 $dir = $dir ?? dataDir();
22 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
23 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
24 }
25 $path = $dir . '/meteors.sqlite';
26 $pdo = new PDO('sqlite:' . $path, null, null, [
27 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
28 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
29 ]);
30 $pdo->exec('PRAGMA journal_mode = WAL');
31 $pdo->exec('PRAGMA foreign_keys = ON');
32 $pdo->exec('PRAGMA busy_timeout = 4000');
33 return new self($pdo);
34 }
35
36 private function migrate(): void
37 {
38 $this->pdo->exec(<<<'SQL'
39CREATE TABLE IF NOT EXISTS lobbies (
40 id TEXT PRIMARY KEY,
41 code TEXT UNIQUE NOT NULL,
42 host_id TEXT NOT NULL,
43 status TEXT NOT NULL DEFAULT 'waiting',
44 miss_chance REAL NOT NULL DEFAULT 0.30,
45 flight_duration REAL NOT NULL DEFAULT 1.2,
46 created INTEGER NOT NULL,
47 started INTEGER,
48 finished INTEGER
49);
50CREATE TABLE IF NOT EXISTS members (
51 lobby_id TEXT NOT NULL,
52 user_id TEXT NOT NULL,
53 name TEXT NOT NULL,
54 ready INTEGER NOT NULL DEFAULT 0,
55 eliminated INTEGER NOT NULL DEFAULT 0,
56 place INTEGER,
57 left_at INTEGER,
58 joined INTEGER NOT NULL,
59 last_seen INTEGER NOT NULL,
60 score INTEGER NOT NULL DEFAULT 0,
61 snapshot TEXT,
62 PRIMARY KEY (lobby_id, user_id)
63);
64CREATE TABLE IF NOT EXISTS shots (
65 id INTEGER PRIMARY KEY AUTOINCREMENT,
66 lobby_id TEXT NOT NULL,
67 from_user TEXT NOT NULL,
68 to_user TEXT,
69 color INTEGER NOT NULL,
70 client_id TEXT,
71 created REAL NOT NULL,
72 deliver_at REAL NOT NULL,
73 delivered INTEGER NOT NULL DEFAULT 0
74);
75CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
76SQL);
77 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
78 $this->ensureColumn('members', 'planet_json', 'TEXT');
79 $this->ensureColumn('shots', 'land_col', 'INTEGER');
80 $this->ensureColumn('shots', 'from_col', 'INTEGER');
81 $this->ensureColumn('shots', 'from_y', 'REAL');
82 $this->pdo->exec(<<<'SQL'
83CREATE TABLE IF NOT EXISTS profiles (
84 user_id TEXT PRIMARY KEY,
85 lifetime_points INTEGER NOT NULL DEFAULT 0,
86 locale TEXT,
87 updated INTEGER NOT NULL
88);
89CREATE TABLE IF NOT EXISTS point_awards (
90 award_key TEXT PRIMARY KEY,
91 user_id TEXT NOT NULL,
92 mode TEXT NOT NULL,
93 points INTEGER NOT NULL,
94 created INTEGER NOT NULL
95);
96CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);
97CREATE TABLE IF NOT EXISTS play_sessions (
98 token TEXT PRIMARY KEY,
99 user_id TEXT NOT NULL,
100 mode TEXT NOT NULL,
101 started INTEGER NOT NULL,
102 finished INTEGER
103);
104CREATE TABLE IF NOT EXISTS custom_planets (
105 id TEXT PRIMARY KEY,
106 user_id TEXT NOT NULL,
107 name TEXT NOT NULL,
108 people TEXT NOT NULL,
109 jumps_to_clear REAL NOT NULL,
110 fall_time REAL NOT NULL,
111 rise_time REAL NOT NULL,
112 colors TEXT NOT NULL,
113 created INTEGER NOT NULL,
114 updated INTEGER NOT NULL
115);
116CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);
117SQL);
118 }
119
120 private function ensureColumn(string $table, string $column, string $ddl): void
121 {
122 $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
123 foreach ($cols as $c) {
124 if (($c['name'] ?? '') === $column) {
125 return;
126 }
127 }
128 $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl);
129 }
130
131 public function transaction(callable $fn): mixed
132 {
133 if ($this->txDepth > 0) {
134 return $fn();
135 }
136 $this->pdo->beginTransaction();
137 $this->txDepth++;
138 try {
139 $result = $fn();
140 $this->pdo->commit();
141 $this->txDepth--;
142 return $result;
143 } catch (Throwable $e) {
144 $this->txDepth--;
145 if ($this->pdo->inTransaction()) {
146 $this->pdo->rollBack();
147 }
148 throw $e;
149 }
150 }
151
152 /** Tests may freeze the clock without sleeping. */
153 public ?int $testNow = null;
154
155 private function now(): int
156 {
157 return $this->testNow ?? time();
158 }
159
160 private function nowf(): float
161 {
162 return microtime(true);
163 }
164
165 private function newId(): string
166 {
167 return bin2hex(random_bytes(12));
168 }
169
170 private function newCode(): string
171 {
172 $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
173 $len = strlen($alphabet);
174 for ($attempt = 0; $attempt < 16; $attempt++) {
175 $code = '';
176 for ($i = 0; $i < 4; $i++) {
177 $code .= $alphabet[random_int(0, $len - 1)];
178 }
179 $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
180 $exists->execute([$code]);
181 if (!$exists->fetch()) {
182 return $code;
183 }
184 }
185 throw new RuntimeException('Kon geen unieke lobbycode maken.');
186 }
187
188 public function lobbyForUser(string $userId): ?array
189 {
190 $stmt = $this->pdo->prepare(
191 'SELECT l.* FROM lobbies l
192 JOIN members m ON m.lobby_id = l.id
193 WHERE m.user_id = ? AND m.left_at IS NULL
194 ORDER BY l.created DESC LIMIT 1'
195 );
196 $stmt->execute([$userId]);
197 $row = $stmt->fetch();
198 return $row ?: null;
199 }
200
201 public function getLobby(string $id): ?array
202 {
203 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
204 $stmt->execute([$id]);
205 $row = $stmt->fetch();
206 return $row ?: null;
207 }
208
209 public function getLobbyByCode(string $code): ?array
210 {
211 $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
212 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
213 $stmt->execute([$code]);
214 $row = $stmt->fetch();
215 return $row ?: null;
216 }
217
218 /** @return list<array> */
219 public function members(string $lobbyId, bool $includeLeft = false): array
220 {
221 $sql = 'SELECT * FROM members WHERE lobby_id = ?';
222 if (!$includeLeft) {
223 $sql .= ' AND left_at IS NULL';
224 }
225 $sql .= ' ORDER BY joined ASC';
226 $stmt = $this->pdo->prepare($sql);
227 $stmt->execute([$lobbyId]);
228 return $stmt->fetchAll();
229 }
230
231 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array
232 {
233 return $this->transaction(function () use ($userId, $name, $missChance, $planetId) {
234 $existing = $this->lobbyForUser($userId);
235 if ($existing && $existing['status'] !== 'finished') {
236 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
237 }
238 if ($existing && $existing['status'] === 'finished') {
239 $this->leaveMember($existing['id'], $userId);
240 }
241 $id = $this->newId();
242 $code = $this->newCode();
243 $now = $this->now();
244 $miss = max(0.0, min(1.0, $missChance));
245 $this->pdo->prepare(
246 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
247 VALUES (?,?,?,?,?,?,?)'
248 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
249 $choice = $this->choosePlanet($userId, $planetId, false);
250 $this->pdo->prepare(
251 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
252 VALUES (?,?,?,0,?,?,?,?)'
253 )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
254 return $this->getLobby($id);
255 });
256 }
257
258 public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array
259 {
260 return $this->transaction(function () use ($userId, $name, $code, $planetId) {
261 $existing = $this->lobbyForUser($userId);
262 if ($existing && $existing['status'] !== 'finished') {
263 if (strcasecmp($existing['code'], $code) === 0) {
264 return $existing;
265 }
266 throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
267 }
268 $lobby = $this->getLobbyByCode($code);
269 if (!$lobby) {
270 throw new RuntimeException('Onbekende lobbycode.');
271 }
272 if ($lobby['status'] !== 'waiting') {
273 throw new RuntimeException('Deze lobby is al begonnen.');
274 }
275 $members = $this->members($lobby['id']);
276 if (count($members) >= METEORS_MAX_PLAYERS) {
277 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
278 }
279 $now = $this->now();
280 $choice = $this->choosePlanet($userId, $planetId, false);
281 $this->pdo->prepare(
282 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
283 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
284 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
285 name = excluded.name,
286 ready = 0,
287 eliminated = 0,
288 place = NULL,
289 left_at = NULL,
290 joined = excluded.joined,
291 last_seen = excluded.last_seen,
292 score = 0,
293 snapshot = NULL,
294 planet_id = excluded.planet_id,
295 planet_json = excluded.planet_json'
296 )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
297 return $this->getLobby($lobby['id']);
298 });
299 }
300
301 private function leaveMember(string $lobbyId, string $userId): void
302 {
303 $this->pdo->prepare(
304 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
305 )->execute([$this->now(), $lobbyId, $userId]);
306 $lobby = $this->getLobby($lobbyId);
307 if (!$lobby) {
308 return;
309 }
310 $remaining = $this->members($lobbyId);
311 if ($lobby['host_id'] === $userId) {
312 if ($remaining) {
313 $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
314 ->execute([$remaining[0]['user_id'], $lobbyId]);
315 } elseif ($lobby['status'] === 'waiting') {
316 // Empty waiting lobby can stay; a later join by code still works until we want to close it.
317 }
318 }
319 if ($lobby['status'] === 'playing') {
320 $this->assignPlaceIfNeeded($lobbyId, $userId, true);
321 $this->maybeFinish($lobbyId);
322 }
323 }
324
325 public function leaveLobby(string $userId): void
326 {
327 $this->transaction(function () use ($userId) {
328 $lobby = $this->lobbyForUser($userId);
329 if (!$lobby) {
330 return;
331 }
332 $this->leaveMember($lobby['id'], $userId);
333 });
334 }
335
336 public function setReady(string $userId, bool $ready): array
337 {
338 return $this->transaction(function () use ($userId, $ready) {
339 $lobby = $this->lobbyForUser($userId);
340 if (!$lobby) {
341 throw new RuntimeException('Je zit niet in een lobby.');
342 }
343 if ($lobby['status'] !== 'waiting') {
344 throw new RuntimeException('Het spel is al begonnen.');
345 }
346 $this->pdo->prepare(
347 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
348 )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
349 return $this->getLobby($lobby['id']);
350 });
351 }
352
353 public function startGame(string $userId): array
354 {
355 return $this->transaction(function () use ($userId) {
356 $lobby = $this->lobbyForUser($userId);
357 if (!$lobby) {
358 throw new RuntimeException('Je zit niet in een lobby.');
359 }
360 if ($lobby['host_id'] !== $userId) {
361 throw new RuntimeException('Alleen de host kan het spel starten.');
362 }
363 if ($lobby['status'] !== 'waiting') {
364 throw new RuntimeException('Het spel is al begonnen.');
365 }
366 $members = $this->members($lobby['id']);
367 if (count($members) < 2) {
368 throw new RuntimeException('Er zijn minstens twee spelers nodig.');
369 }
370 foreach ($members as $m) {
371 if (!(int) $m['ready']) {
372 throw new RuntimeException('Niet iedereen is gereed.');
373 }
374 }
375 $this->pdo->prepare(
376 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
377 )->execute(['playing', $this->now(), $lobby['id']]);
378 $this->pdo->prepare(
379 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
380 WHERE lobby_id = ? AND left_at IS NULL'
381 )->execute([$lobby['id']]);
382 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
383 return $this->getLobby($lobby['id']);
384 });
385 }
386
387 /** @param list<array{client_id?:string,color?:int}> $shots */
388 public function setPlanet(string $userId, string $planetId): array
389 {
390 return $this->transaction(function () use ($userId, $planetId) {
391 $lobby = $this->lobbyForUser($userId);
392 if (!$lobby) {
393 throw new RuntimeException('Je zit in geen lobby.');
394 }
395 if ($lobby['status'] !== 'waiting') {
396 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
397 }
398 $choice = $this->choosePlanet($userId, $planetId, true);
399 $this->pdo->prepare(
400 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
401 )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
402 return $this->getLobby($lobby['id']);
403 });
404 }
405
406 /** @param array<string,mixed> $member */
407 public function missChanceForMember(array $member): float
408 {
409 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
410 return max(0.0, min(1.0, $this->testMissOverride));
411 }
412 if (!empty($member['planet_json'])) {
413 $data = json_decode((string) $member['planet_json'], true);
414 if (is_array($data)) {
415 return Planets::missChance($data);
416 }
417 }
418 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
419 return Planets::missChanceForId($id);
420 }
421
422 /** @var ?float Tests may force a miss chance without changing the catalog. */
423 public ?float $testMissOverride = null;
424
425 public function recordShots(string $userId, array $shots): array
426 {
427 return $this->transaction(function () use ($userId, $shots) {
428 $lobby = $this->lobbyForUser($userId);
429 if (!$lobby || $lobby['status'] !== 'playing') {
430 return [];
431 }
432 $me = $this->member($lobby['id'], $userId);
433 if (!$me || (int) $me['eliminated']) {
434 return [];
435 }
436 $targets = [];
437 foreach ($this->members($lobby['id']) as $m) {
438 if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
439 $targets[] = $m;
440 }
441 }
442 $results = [];
443 $missChance = $this->missChanceForMember($me);
444 $flight = (float) $lobby['flight_duration'];
445 $now = $this->nowf();
446 $ins = $this->pdo->prepare(
447 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col, from_col, from_y)
448 VALUES (?,?,?,?,?,?,?,0,?,?,?)'
449 );
450 foreach ($shots as $shot) {
451 $color = isset($shot['color']) ? (int) $shot['color'] : -1;
452 $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
453 $fromCol = isset($shot['col']) && $shot['col'] !== null && is_numeric($shot['col']) ? (int) $shot['col'] : null;
454 $fromY = isset($shot['y']) && $shot['y'] !== null && is_numeric($shot['y']) ? (float) $shot['y'] : null;
455 $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
456 $to = null;
457 $toName = null;
458 $landCol = null;
459 if (!$miss) {
460 $pick = $targets[random_int(0, count($targets) - 1)];
461 $to = $pick['user_id'];
462 $toName = $pick['name'];
463 $landCol = random_int(0, 9);
464 }
465 $deliver = $now + $flight;
466 $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol, $fromCol, $fromY]);
467 $results[] = [
468 'id' => (int) $this->pdo->lastInsertId(),
469 'client_id' => $clientId,
470 'from_id' => $userId,
471 'from_user' => $userId,
472 'miss' => $miss,
473 'target_id' => $to,
474 'target_name' => $toName,
475 'deliver_at' => $deliver,
476 'color' => $color,
477 'flight_duration' => $flight,
478 'age' => 0.0,
479 'land_col' => $landCol,
480 'col' => $fromCol,
481 'y' => $fromY,
482 ];
483 }
484 return $results;
485 });
486 }
487
488 /** @return list<array> undelivered shots whose time has come, marked delivered. */
489 public function takeIncoming(string $lobbyId, string $userId): array
490 {
491 $now = $this->nowf();
492 $stmt = $this->pdo->prepare(
493 'SELECT * FROM shots
494 WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
495 ORDER BY deliver_at ASC, id ASC'
496 );
497 $stmt->execute([$lobbyId, $userId, $now]);
498 $rows = $stmt->fetchAll();
499 if (!$rows) {
500 return [];
501 }
502 $ids = array_column($rows, 'id');
503 $in = implode(',', array_fill(0, count($ids), '?'));
504 $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
505 $incoming = [];
506 foreach ($rows as $r) {
507 $incoming[] = [
508 'id' => (int) $r['id'],
509 'color' => (int) $r['color'],
510 'from_user' => $r['from_user'],
511 'client_id' => $r['client_id'],
512 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
513 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
514 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
515 ];
516 }
517 return $incoming;
518 }
519
520 public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
521 {
522 $lobby = $this->lobbyForUser($userId);
523 if (!$lobby || $lobby['status'] !== 'playing') {
524 return;
525 }
526 $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
527 $fields = 'last_seen = ?';
528 $args = [$this->now()];
529 if ($json !== null) {
530 $fields .= ', snapshot = ?';
531 $args[] = $json;
532 }
533 if ($score !== null) {
534 $fields .= ', score = ?';
535 $args[] = $score;
536 }
537 $args[] = $lobby['id'];
538 $args[] = $userId;
539 $this->pdo->prepare(
540 "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
541 )->execute($args);
542 if ($eliminated) {
543 $this->assignPlaceIfNeeded($lobby['id'], $userId, false);
544 $this->maybeFinish($lobby['id']);
545 }
546 }
547
548 public function member(string $lobbyId, string $userId): ?array
549 {
550 $stmt = $this->pdo->prepare(
551 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
552 );
553 $stmt->execute([$lobbyId, $userId]);
554 $row = $stmt->fetch();
555 return $row ?: null;
556 }
557
558 private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
559 {
560 $m = $this->member($lobbyId, $userId);
561 if (!$m || $m['place'] !== null) {
562 return;
563 }
564 $active = 0;
565 foreach ($this->members($lobbyId) as $row) {
566 if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
567 $active++;
568 }
569 }
570 // First out gets last place = number of current (incl. this) non-left players.
571 $total = count($this->members($lobbyId));
572 $alreadyPlaced = 0;
573 foreach ($this->members($lobbyId, true) as $row) {
574 if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
575 if ($row['place'] !== null) {
576 $alreadyPlaced++;
577 }
578 }
579 }
580 $place = $active + 1; // remaining others + self → this player's place
581 $this->pdo->prepare(
582 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
583 )->execute([$place, $lobbyId, $userId]);
584 }
585
586 public function maybeFinish(string $lobbyId): void
587 {
588 $lobby = $this->getLobby($lobbyId);
589 if (!$lobby || $lobby['status'] !== 'playing') {
590 return;
591 }
592 $alive = [];
593 foreach ($this->members($lobbyId) as $m) {
594 if (!(int) $m['eliminated']) {
595 $alive[] = $m;
596 }
597 }
598 if (count($alive) > 1) {
599 return;
600 }
601 if (count($alive) === 1) {
602 $winner = $alive[0];
603 if ($winner['place'] === null) {
604 $this->pdo->prepare(
605 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
606 )->execute([$lobbyId, $winner['user_id']]);
607 }
608 }
609 $this->pdo->prepare(
610 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
611 )->execute(['finished', $this->now(), $lobbyId]);
612 }
613
614 public function maybeResetLobby(string $lobbyId): void
615 {
616 $lobby = $this->getLobby($lobbyId);
617 if (!$lobby || $lobby['status'] !== 'finished') {
618 return;
619 }
620 $finished = (int) ($lobby['finished'] ?? 0);
621 if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
622 return;
623 }
624 $this->pdo->prepare(
625 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
626 )->execute(['waiting', $lobbyId]);
627 $this->pdo->prepare(
628 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
629 WHERE lobby_id = ? AND left_at IS NULL'
630 )->execute([$lobbyId]);
631 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
632 }
633
634 /**
635 * Shots still (or just) in flight, for every client in the lobby (t1125).
636 * `age` is seconds since `created`, so a late poll can join mid-arc.
637 * Window is flight_duration + 0.8 s (one poll slack).
638 *
639 * @return list<array>
640 */
641 public function recentFlights(string $lobbyId, ?float $flightDuration = null): array
642 {
643 $flight = $flightDuration !== null ? (float) $flightDuration : (float) METEORS_FLIGHT_DURATION;
644 $now = $this->nowf();
645 $window = $flight + 0.8;
646 $stmt = $this->pdo->prepare(
647 'SELECT * FROM shots
648 WHERE lobby_id = ? AND created >= ?
649 ORDER BY id ASC'
650 );
651 $stmt->execute([$lobbyId, $now - $window]);
652 $out = [];
653 foreach ($stmt->fetchAll() as $r) {
654 $to = $r['to_user'];
655 $out[] = [
656 'id' => (int) $r['id'],
657 'client_id' => $r['client_id'],
658 'from_id' => $r['from_user'],
659 'from_user' => $r['from_user'],
660 'target_id' => $to,
661 'miss' => $to === null || $to === '',
662 'color' => (int) $r['color'],
663 'flight_duration' => $flight,
664 'age' => $now - (float) $r['created'],
665 'deliver_at' => (float) $r['deliver_at'],
666 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null,
667 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null,
668 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null,
669 ];
670 }
671 return $out;
672 }
673
674 /** Public view of a lobby for the given user, including incoming shots. */
675 public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
676 {
677 return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
678 $touch = $this->lobbyForUser($userId);
679 if ($touch && $touch['status'] === 'finished') {
680 $this->maybeResetLobby($touch['id']);
681 }
682 if ($touch && $touch['status'] === 'playing') {
683 if ($snapshot !== null || $score !== null || $eliminated) {
684 $this->updateSnapshot($userId, $snapshot, $score, $eliminated);
685 } else {
686 $this->pdo->prepare(
687 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
688 )->execute([$this->now(), $touch['id'], $userId]);
689 }
690 }
691 $shotResults = [];
692 if ($outgoing && $touch && $touch['status'] === 'playing') {
693 $shotResults = $this->recordShots($userId, $outgoing);
694 }
695 $lobby = $this->lobbyForUser($userId);
696 if (!$lobby) {
697 return [
698 'lobby' => null,
699 'incoming' => [],
700 'shot_results' => $shotResults,
701 'shot_flights' => [],
702 ];
703 }
704 $incoming = [];
705 if ($lobby['status'] === 'playing') {
706 $incoming = $this->takeIncoming($lobby['id'], $userId);
707 }
708 $flights = [];
709 if ($lobby['status'] === 'playing') {
710 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
711 }
712 $this->maybeAwardOnlineLobby($lobby);
713 return [
714 'lobby' => $this->presentLobby($lobby, $userId),
715 'incoming' => $incoming,
716 'shot_results' => $shotResults,
717 'shot_flights' => $flights,
718 ];
719 });
720 }
721
722 public function presentLobby(array $lobby, string $userId): array
723 {
724 $members = $this->members($lobby['id']);
725 $players = [];
726 foreach ($members as $m) {
727 $snap = null;
728 if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
729 $decoded = json_decode($m['snapshot'], true);
730 $snap = is_array($decoded) ? $decoded : null;
731 }
732 $players[] = [
733 'id' => $m['user_id'],
734 'name' => $m['name'],
735 'ready' => (bool) (int) $m['ready'],
736 'eliminated' => (bool) (int) $m['eliminated'],
737 'place' => $m['place'] !== null ? (int) $m['place'] : null,
738 'is_host' => $m['user_id'] === $lobby['host_id'],
739 'is_me' => $m['user_id'] === $userId,
740 'score' => (int) $m['score'],
741 'snapshot' => $m['user_id'] === $userId ? null : $snap,
742 'planet' => $this->presentMemberPlanet($m),
743 ];
744 }
745 $rankings = [];
746 if ($lobby['status'] === 'finished' || $lobby['finished']) {
747 $all = $this->members($lobby['id'], true);
748 foreach ($all as $m) {
749 if ($m['place'] !== null) {
750 $rankings[] = [
751 'place' => (int) $m['place'],
752 'id' => $m['user_id'],
753 'name' => $m['name'],
754 'score' => (int) $m['score'],
755 ];
756 }
757 }
758 usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
759 }
760 $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
761 return [
762 'id' => $lobby['id'],
763 'code' => $lobby['code'],
764 'status' => $lobby['status'],
765 'host_id' => $lobby['host_id'],
766 'miss_chance' => (float) $lobby['miss_chance'],
767 'flight_duration' => (float) $lobby['flight_duration'],
768 'players' => $players,
769 'all_ready' => $allReady,
770 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
771 'rankings' => $rankings,
772 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
773 'podium_seconds' => METEORS_PODIUM_SECONDS,
774 ];
775 }
776
777 public const MAX_CUSTOM_PLANETS = 30;
778 public const MAX_GAME_POINTS = 10000;
779 public const MAX_POINTS_PER_SEC = 4.0;
780 public const MIN_PLAY_SECONDS = 3;
781 public const PLAY_TOKEN_TTL = 21600;
782 public const NAME_MAX = 32;
783
784 /** @return array{planet_id:string,planet_json:?string} */
785 public function choosePlanet(string $userId, string $planetId, bool $strict): array
786 {
787 if ($planetId === '') {
788 if ($strict) {
789 throw new RuntimeException('Onbekende planeet.');
790 }
791 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
792 }
793 if (Planets::known($planetId)) {
794 return ['planet_id' => $planetId, 'planet_json' => null];
795 }
796 $row = $this->ownedCustom($userId, $planetId);
797 if ($row) {
798 return [
799 'planet_id' => $planetId,
800 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
801 ];
802 }
803 if ($strict) {
804 throw new RuntimeException('Onbekende planeet.');
805 }
806 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
807 }
808
809 /** @param array<string,mixed> $member */
810 public function presentMemberPlanet(array $member): array
811 {
812 if (!empty($member['planet_json'])) {
813 $data = json_decode((string) $member['planet_json'], true);
814 if (is_array($data) && !empty($data['id'])) {
815 return Planets::presentData($data);
816 }
817 }
818 return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
819 }
820
821 public function ensureProfile(string $userId): array
822 {
823 $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
824 $stmt->execute([$userId]);
825 $row = $stmt->fetch();
826 if ($row) {
827 return $row;
828 }
829 $now = $this->now();
830 $this->pdo->prepare(
831 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
832 )->execute([$userId, $now]);
833 return [
834 'user_id' => $userId,
835 'lifetime_points' => 0,
836 'locale' => null,
837 'updated' => $now,
838 ];
839 }
840
841 public function lifetimePoints(string $userId): int
842 {
843 return (int) $this->ensureProfile($userId)['lifetime_points'];
844 }
845
846 public function locale(string $userId): ?string
847 {
848 $v = $this->ensureProfile($userId)['locale'] ?? null;
849 return is_string($v) && $v !== '' ? $v : null;
850 }
851
852 /** @var list<string> */
853 public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
854
855 public function setLocale(string $userId, string $locale): string
856 {
857 $locale = strtolower($locale);
858 if (!in_array($locale, self::LOCALES, true)) {
859 throw new RuntimeException('Onbekende taal.');
860 }
861 $this->ensureProfile($userId);
862 $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
863 ->execute([$locale, $this->now(), $userId]);
864 return $locale;
865 }
866
867 /**
868 * Add points once for a unique award_key. Returns the new lifetime total.
869 * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
870 */
871 public function awardPoints(string $userId, int $points, string $key, string $mode): int
872 {
873 return $this->transaction(function () use ($userId, $points, $key, $mode) {
874 $this->ensureProfile($userId);
875 $points = max(0, min(self::MAX_GAME_POINTS, $points));
876 $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
877 $stmt->execute([$key]);
878 if ($stmt->fetch()) {
879 return $this->lifetimePoints($userId);
880 }
881 $this->pdo->prepare(
882 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
883 )->execute([$key, $userId, $mode, $points, $this->now()]);
884 if ($points > 0) {
885 $this->pdo->prepare(
886 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
887 )->execute([$points, $this->now(), $userId]);
888 }
889 return $this->lifetimePoints($userId);
890 });
891 }
892
893 public function playBegin(string $userId, string $mode): array
894 {
895 if (!in_array($mode, ['solo', 'offline'], true)) {
896 throw new RuntimeException('Onbekende speelmodus.');
897 }
898 $token = bin2hex(random_bytes(16));
899 $this->pdo->prepare(
900 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
901 )->execute([$token, $userId, $mode, $this->now()]);
902 return ['token' => $token, 'started' => $this->now()];
903 }
904
905 public function playFinish(string $userId, string $token, int $score): array
906 {
907 return $this->transaction(function () use ($userId, $token, $score) {
908 $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
909 $stmt->execute([$token]);
910 $ses = $stmt->fetch();
911 if (!$ses || $ses['user_id'] !== $userId) {
912 throw new RuntimeException('Ongeldige speelsessie.');
913 }
914 $key = 'play:' . $token;
915 if ($ses['finished'] !== null) {
916 return [
917 'lifetime_points' => $this->lifetimePoints($userId),
918 'awarded' => 0,
919 'already' => true,
920 ];
921 }
922 $now = $this->now();
923 $started = (int) $ses['started'];
924 if ($now - $started > self::PLAY_TOKEN_TTL) {
925 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
926 ->execute([$now, $token]);
927 throw new RuntimeException('Speelsessie is verlopen.');
928 }
929 $duration = max(0, $now - $started);
930 $score = max(0, $score);
931 $awarded = 0;
932 if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
933 $awarded = 0;
934 } else {
935 $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
936 $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
937 }
938 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
939 ->execute([$now, $token]);
940 $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
941 return [
942 'lifetime_points' => $total,
943 'awarded' => $awarded,
944 'already' => false,
945 ];
946 });
947 }
948
949 /** @param array<string,mixed> $lobby */
950 public function maybeAwardOnlineLobby(array $lobby): void
951 {
952 $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
953 foreach ($this->members($lobby['id'], true) as $m) {
954 if (!$finished && empty($m['eliminated'])) {
955 continue;
956 }
957 $uid = (string) $m['user_id'];
958 $key = 'online:' . $lobby['id'] . ':' . $uid;
959 $this->awardPoints($uid, (int) $m['score'], $key, 'online');
960 }
961 }
962
963 /** @return ?array<string,mixed> */
964 public function ownedCustom(string $userId, string $id): ?array
965 {
966 $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
967 $stmt->execute([$id, $userId]);
968 $row = $stmt->fetch();
969 return $row ?: null;
970 }
971
972 /** @return list<array<string,mixed>> */
973 public function listCustomPlanets(string $userId): array
974 {
975 $stmt = $this->pdo->prepare(
976 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
977 );
978 $stmt->execute([$userId]);
979 $out = [];
980 foreach ($stmt->fetchAll() as $row) {
981 $out[] = $this->snapshotCustom($row);
982 }
983 return $out;
984 }
985
986 public static function sanitizeName(string $raw, string $field): string
987 {
988 $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
989 $s = strip_tags($s);
990 if ($s === '') {
991 throw new RuntimeException('Vul een ' . $field . ' in.');
992 }
993 if (mb_strlen($s) > self::NAME_MAX) {
994 $s = mb_substr($s, 0, self::NAME_MAX);
995 }
996 return $s;
997 }
998
999 /**
1000 * Create or update a custom planet owned by $userId.
1001 * @param array<string,mixed> $data
1002 * @return array<string,mixed> snapshot
1003 */
1004 public function saveCustomPlanet(string $userId, array $data): array
1005 {
1006 return $this->transaction(function () use ($userId, $data) {
1007 $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
1008 $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
1009 $j = self::clampFloat((float) ($data['jumpsToClear'] ?? 2), 1, 4);
1010 $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
1011 $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
1012 $ids = $data['colors'] ?? $data['blocks'] ?? [];
1013 if (!is_array($ids) || count($ids) !== 5) {
1014 throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
1015 }
1016 $points = $this->lifetimePoints($userId);
1017 $blockIds = [];
1018 foreach ($ids as $entry) {
1019 if (is_array($entry)) {
1020 $bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
1021 } else {
1022 $bid = (string) $entry;
1023 }
1024 if ($bid === '' || !Blocks::known($bid)) {
1025 throw new RuntimeException('Onbekend blokje.');
1026 }
1027 if (!Blocks::unlockedId($bid, $points)) {
1028 throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
1029 }
1030 if (in_array($bid, $blockIds, true)) {
1031 throw new RuntimeException('Elk blokje mag maar in één vak.');
1032 }
1033 $blockIds[] = $bid;
1034 }
1035 $now = $this->now();
1036 $id = isset($data['id']) ? (string) $data['id'] : '';
1037 if ($id !== '') {
1038 $row = $this->ownedCustom($userId, $id);
1039 if (!$row) {
1040 throw new RuntimeException('Onbekende planeet.');
1041 }
1042 $this->pdo->prepare(
1043 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
1044 )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
1045 } else {
1046 $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
1047 $stmt->execute([$userId]);
1048 if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
1049 throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
1050 }
1051 $id = 'c_' . bin2hex(random_bytes(8));
1052 $this->pdo->prepare(
1053 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
1054 VALUES (?,?,?,?,?,?,?,?,?,?)'
1055 )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
1056 }
1057 $row = $this->ownedCustom($userId, $id);
1058 if (!$row) {
1059 throw new RuntimeException('Opslaan is mislukt.');
1060 }
1061 return $this->snapshotCustom($row);
1062 });
1063 }
1064
1065 public function deleteCustomPlanet(string $userId, string $id): void
1066 {
1067 $row = $this->ownedCustom($userId, $id);
1068 if (!$row) {
1069 throw new RuntimeException('Onbekende planeet.');
1070 }
1071 $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
1072 ->execute([$id, $userId]);
1073 }
1074
1075 /** @param array<string,mixed> $row */
1076 public function snapshotCustom(array $row): array
1077 {
1078 $ids = json_decode((string) $row['colors'], true);
1079 if (!is_array($ids)) {
1080 $ids = [];
1081 }
1082 $colors = [];
1083 foreach ($ids as $i => $id) {
1084 $c = Blocks::asColor((string) $id, (int) $i);
1085 if ($c === null) {
1086 continue;
1087 }
1088 $colors[] = $c;
1089 }
1090 $p = [
1091 'id' => (string) $row['id'],
1092 'name' => (string) $row['name'],
1093 'people' => (string) $row['people'],
1094 'jumpsToClear' => (float) $row['jumps_to_clear'],
1095 'fallTime' => (float) $row['fall_time'],
1096 'riseTime' => (float) $row['rise_time'],
1097 'colors' => $colors,
1098 'custom' => true,
1099 'owner_id' => (string) $row['user_id'],
1100 ];
1101 return Planets::presentData($p);
1102 }
1103
1104 public function profilePayload(string $userId): array
1105 {
1106 $points = $this->lifetimePoints($userId);
1107 return [
1108 'lifetime_points' => $points,
1109 'locale' => $this->locale($userId),
1110 'blocks' => Blocks::present($points),
1111 'planets' => $this->listCustomPlanets($userId),
1112 ];
1113 }
1114
1115 private static function clampFloat(float $value, float $lo, float $hi): float
1116 {
1117 return max($lo, min($hi, $value));
1118 }
1119
1120
1121}