BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / Store.php

Store.php

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