pdo = $pdo; $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->migrate(); } public static function open(?string $dir = null): self { $dir = $dir ?? dataDir(); if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) { throw new RuntimeException('De datamap moet schrijfbaar zijn.'); } $path = $dir . '/meteors.sqlite'; $pdo = new PDO('sqlite:' . $path, null, null, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); $pdo->exec('PRAGMA journal_mode = WAL'); $pdo->exec('PRAGMA foreign_keys = ON'); $pdo->exec('PRAGMA busy_timeout = 4000'); return new self($pdo); } private function migrate(): void { $this->pdo->exec(<<<'SQL' CREATE TABLE IF NOT EXISTS lobbies ( id TEXT PRIMARY KEY, code TEXT UNIQUE NOT NULL, host_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'waiting', miss_chance REAL NOT NULL DEFAULT 0.30, flight_duration REAL NOT NULL DEFAULT 1.2, created INTEGER NOT NULL, started INTEGER, finished INTEGER ); CREATE TABLE IF NOT EXISTS members ( lobby_id TEXT NOT NULL, user_id TEXT NOT NULL, name TEXT NOT NULL, ready INTEGER NOT NULL DEFAULT 0, eliminated INTEGER NOT NULL DEFAULT 0, place INTEGER, left_at INTEGER, joined INTEGER NOT NULL, last_seen INTEGER NOT NULL, score INTEGER NOT NULL DEFAULT 0, snapshot TEXT, PRIMARY KEY (lobby_id, user_id) ); CREATE TABLE IF NOT EXISTS shots ( id INTEGER PRIMARY KEY AUTOINCREMENT, lobby_id TEXT NOT NULL, from_user TEXT NOT NULL, to_user TEXT, color INTEGER NOT NULL, client_id TEXT, created REAL NOT NULL, deliver_at REAL NOT NULL, delivered INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at); SQL); $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'"); $this->ensureColumn('shots', 'land_col', 'INTEGER'); $this->ensureColumn('shots', 'from_col', 'INTEGER'); $this->ensureColumn('shots', 'from_y', 'REAL'); } private function ensureColumn(string $table, string $column, string $ddl): void { $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(); foreach ($cols as $c) { if (($c['name'] ?? '') === $column) { return; } } $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl); } public function transaction(callable $fn): mixed { if ($this->txDepth > 0) { return $fn(); } $this->pdo->beginTransaction(); $this->txDepth++; try { $result = $fn(); $this->pdo->commit(); $this->txDepth--; return $result; } catch (Throwable $e) { $this->txDepth--; if ($this->pdo->inTransaction()) { $this->pdo->rollBack(); } throw $e; } } private function now(): int { return time(); } private function nowf(): float { return microtime(true); } private function newId(): string { return bin2hex(random_bytes(12)); } private function newCode(): string { $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; $len = strlen($alphabet); for ($attempt = 0; $attempt < 16; $attempt++) { $code = ''; for ($i = 0; $i < 4; $i++) { $code .= $alphabet[random_int(0, $len - 1)]; } $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?'); $exists->execute([$code]); if (!$exists->fetch()) { return $code; } } throw new RuntimeException('Kon geen unieke lobbycode maken.'); } public function lobbyForUser(string $userId): ?array { $stmt = $this->pdo->prepare( 'SELECT l.* FROM lobbies l JOIN members m ON m.lobby_id = l.id WHERE m.user_id = ? AND m.left_at IS NULL ORDER BY l.created DESC LIMIT 1' ); $stmt->execute([$userId]); $row = $stmt->fetch(); return $row ?: null; } public function getLobby(string $id): ?array { $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?'); $stmt->execute([$id]); $row = $stmt->fetch(); return $row ?: null; } public function getLobbyByCode(string $code): ?array { $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? ''); $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?'); $stmt->execute([$code]); $row = $stmt->fetch(); return $row ?: null; } /** @return list */ public function members(string $lobbyId, bool $includeLeft = false): array { $sql = 'SELECT * FROM members WHERE lobby_id = ?'; if (!$includeLeft) { $sql .= ' AND left_at IS NULL'; } $sql .= ' ORDER BY joined ASC'; $stmt = $this->pdo->prepare($sql); $stmt->execute([$lobbyId]); return $stmt->fetchAll(); } public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array { return $this->transaction(function () use ($userId, $name, $missChance, $planetId) { $existing = $this->lobbyForUser($userId); if ($existing && $existing['status'] !== 'finished') { throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.'); } if ($existing && $existing['status'] === 'finished') { $this->leaveMember($existing['id'], $userId); } $id = $this->newId(); $code = $this->newCode(); $now = $this->now(); $miss = max(0.0, min(1.0, $missChance)); $this->pdo->prepare( 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created) VALUES (?,?,?,?,?,?,?)' )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]); $planet = Planets::known($planetId) ? $planetId : Planets::defaultId(); $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id) VALUES (?,?,?,0,?,?,?)' )->execute([$id, $userId, $name, $now, $now, $planet]); return $this->getLobby($id); }); } public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array { return $this->transaction(function () use ($userId, $name, $code, $planetId) { $existing = $this->lobbyForUser($userId); if ($existing && $existing['status'] !== 'finished') { if (strcasecmp($existing['code'], $code) === 0) { return $existing; } throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.'); } $lobby = $this->getLobbyByCode($code); if (!$lobby) { throw new RuntimeException('Onbekende lobbycode.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('Deze lobby is al begonnen.'); } $members = $this->members($lobby['id']); if (count($members) >= METEORS_MAX_PLAYERS) { throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).'); } $now = $this->now(); $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id) VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?) ON CONFLICT(lobby_id, user_id) DO UPDATE SET name = excluded.name, ready = 0, eliminated = 0, place = NULL, left_at = NULL, joined = excluded.joined, last_seen = excluded.last_seen, score = 0, snapshot = NULL, planet_id = excluded.planet_id' )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]); return $this->getLobby($lobby['id']); }); } private function leaveMember(string $lobbyId, string $userId): void { $this->pdo->prepare( 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$this->now(), $lobbyId, $userId]); $lobby = $this->getLobby($lobbyId); if (!$lobby) { return; } $remaining = $this->members($lobbyId); if ($lobby['host_id'] === $userId) { if ($remaining) { $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?') ->execute([$remaining[0]['user_id'], $lobbyId]); } elseif ($lobby['status'] === 'waiting') { // Empty waiting lobby can stay; a later join by code still works until we want to close it. } } if ($lobby['status'] === 'playing') { $this->assignPlaceIfNeeded($lobbyId, $userId, true); $this->maybeFinish($lobbyId); } } public function leaveLobby(string $userId): void { $this->transaction(function () use ($userId) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { return; } $this->leaveMember($lobby['id'], $userId); }); } public function setReady(string $userId, bool $ready): array { return $this->transaction(function () use ($userId, $ready) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { throw new RuntimeException('Je zit niet in een lobby.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('Het spel is al begonnen.'); } $this->pdo->prepare( 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]); return $this->getLobby($lobby['id']); }); } public function startGame(string $userId): array { return $this->transaction(function () use ($userId) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { throw new RuntimeException('Je zit niet in een lobby.'); } if ($lobby['host_id'] !== $userId) { throw new RuntimeException('Alleen de host kan het spel starten.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('Het spel is al begonnen.'); } $members = $this->members($lobby['id']); if (count($members) < 2) { throw new RuntimeException('Er zijn minstens twee spelers nodig.'); } foreach ($members as $m) { if (!(int) $m['ready']) { throw new RuntimeException('Niet iedereen is gereed.'); } } $this->pdo->prepare( 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?' )->execute(['playing', $this->now(), $lobby['id']]); $this->pdo->prepare( 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL WHERE lobby_id = ? AND left_at IS NULL' )->execute([$lobby['id']]); $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]); return $this->getLobby($lobby['id']); }); } /** @param list $shots */ public function setPlanet(string $userId, string $planetId): array { return $this->transaction(function () use ($userId, $planetId) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { throw new RuntimeException('Je zit in geen lobby.'); } if ($lobby['status'] !== 'waiting') { throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.'); } if (!Planets::known($planetId)) { throw new RuntimeException('Onbekende planeet.'); } $this->pdo->prepare( 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$planetId, $this->now(), $lobby['id'], $userId]); return $this->getLobby($lobby['id']); }); } /** @param array $member */ public function missChanceForMember(array $member): float { if (isset($this->testMissOverride) && is_float($this->testMissOverride)) { return max(0.0, min(1.0, $this->testMissOverride)); } $id = (string) ($member['planet_id'] ?? Planets::defaultId()); return Planets::missChanceForId($id); } /** @var ?float Tests may force a miss chance without changing the catalog. */ public ?float $testMissOverride = null; public function recordShots(string $userId, array $shots): array { return $this->transaction(function () use ($userId, $shots) { $lobby = $this->lobbyForUser($userId); if (!$lobby || $lobby['status'] !== 'playing') { return []; } $me = $this->member($lobby['id'], $userId); if (!$me || (int) $me['eliminated']) { return []; } $targets = []; foreach ($this->members($lobby['id']) as $m) { if ($m['user_id'] !== $userId && !(int) $m['eliminated']) { $targets[] = $m; } } $results = []; $missChance = $this->missChanceForMember($me); $flight = (float) $lobby['flight_duration']; $now = $this->nowf(); $ins = $this->pdo->prepare( 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered, land_col, from_col, from_y) VALUES (?,?,?,?,?,?,?,0,?,?,?)' ); foreach ($shots as $shot) { $color = isset($shot['color']) ? (int) $shot['color'] : -1; $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? ''); $fromCol = isset($shot['col']) && $shot['col'] !== null && is_numeric($shot['col']) ? (int) $shot['col'] : null; $fromY = isset($shot['y']) && $shot['y'] !== null && is_numeric($shot['y']) ? (float) $shot['y'] : null; $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance; $to = null; $toName = null; $landCol = null; if (!$miss) { $pick = $targets[random_int(0, count($targets) - 1)]; $to = $pick['user_id']; $toName = $pick['name']; $landCol = random_int(0, 9); } $deliver = $now + $flight; $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver, $landCol, $fromCol, $fromY]); $results[] = [ 'id' => (int) $this->pdo->lastInsertId(), 'client_id' => $clientId, 'from_id' => $userId, 'from_user' => $userId, 'miss' => $miss, 'target_id' => $to, 'target_name' => $toName, 'deliver_at' => $deliver, 'color' => $color, 'flight_duration' => $flight, 'age' => 0.0, 'land_col' => $landCol, 'col' => $fromCol, 'y' => $fromY, ]; } return $results; }); } /** @return list undelivered shots whose time has come, marked delivered. */ public function takeIncoming(string $lobbyId, string $userId): array { $now = $this->nowf(); $stmt = $this->pdo->prepare( 'SELECT * FROM shots WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ? ORDER BY deliver_at ASC, id ASC' ); $stmt->execute([$lobbyId, $userId, $now]); $rows = $stmt->fetchAll(); if (!$rows) { return []; } $ids = array_column($rows, 'id'); $in = implode(',', array_fill(0, count($ids), '?')); $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids); $incoming = []; foreach ($rows as $r) { $incoming[] = [ 'id' => (int) $r['id'], 'color' => (int) $r['color'], 'from_user' => $r['from_user'], 'client_id' => $r['client_id'], 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null, 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null, 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null, ]; } return $incoming; } public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void { $lobby = $this->lobbyForUser($userId); if (!$lobby || $lobby['status'] !== 'playing') { return; } $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null; $fields = 'last_seen = ?'; $args = [$this->now()]; if ($json !== null) { $fields .= ', snapshot = ?'; $args[] = $json; } if ($score !== null) { $fields .= ', score = ?'; $args[] = $score; } $args[] = $lobby['id']; $args[] = $userId; $this->pdo->prepare( "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL" )->execute($args); if ($eliminated) { $this->assignPlaceIfNeeded($lobby['id'], $userId, false); $this->maybeFinish($lobby['id']); } } public function member(string $lobbyId, string $userId): ?array { $stmt = $this->pdo->prepare( 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?' ); $stmt->execute([$lobbyId, $userId]); $row = $stmt->fetch(); return $row ?: null; } private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void { $m = $this->member($lobbyId, $userId); if (!$m || $m['place'] !== null) { return; } $active = 0; foreach ($this->members($lobbyId) as $row) { if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) { $active++; } } // First out gets last place = number of current (incl. this) non-left players. $total = count($this->members($lobbyId)); $alreadyPlaced = 0; foreach ($this->members($lobbyId, true) as $row) { if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) { if ($row['place'] !== null) { $alreadyPlaced++; } } } $place = $active + 1; // remaining others + self → this player's place $this->pdo->prepare( 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?' )->execute([$place, $lobbyId, $userId]); } public function maybeFinish(string $lobbyId): void { $lobby = $this->getLobby($lobbyId); if (!$lobby || $lobby['status'] !== 'playing') { return; } $alive = []; foreach ($this->members($lobbyId) as $m) { if (!(int) $m['eliminated']) { $alive[] = $m; } } if (count($alive) > 1) { return; } if (count($alive) === 1) { $winner = $alive[0]; if ($winner['place'] === null) { $this->pdo->prepare( 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?' )->execute([$lobbyId, $winner['user_id']]); } } $this->pdo->prepare( 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?' )->execute(['finished', $this->now(), $lobbyId]); } public function maybeResetLobby(string $lobbyId): void { $lobby = $this->getLobby($lobbyId); if (!$lobby || $lobby['status'] !== 'finished') { return; } $finished = (int) ($lobby['finished'] ?? 0); if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) { return; } $this->pdo->prepare( 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?' )->execute(['waiting', $lobbyId]); $this->pdo->prepare( 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0 WHERE lobby_id = ? AND left_at IS NULL' )->execute([$lobbyId]); $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]); } /** * Shots still (or just) in flight, for every client in the lobby (t1125). * `age` is seconds since `created`, so a late poll can join mid-arc. * Window is flight_duration + 0.8 s (one poll slack). * * @return list */ public function recentFlights(string $lobbyId, ?float $flightDuration = null): array { $flight = $flightDuration !== null ? (float) $flightDuration : (float) METEORS_FLIGHT_DURATION; $now = $this->nowf(); $window = $flight + 0.8; $stmt = $this->pdo->prepare( 'SELECT * FROM shots WHERE lobby_id = ? AND created >= ? ORDER BY id ASC' ); $stmt->execute([$lobbyId, $now - $window]); $out = []; foreach ($stmt->fetchAll() as $r) { $to = $r['to_user']; $out[] = [ 'id' => (int) $r['id'], 'client_id' => $r['client_id'], 'from_id' => $r['from_user'], 'from_user' => $r['from_user'], 'target_id' => $to, 'miss' => $to === null || $to === '', 'color' => (int) $r['color'], 'flight_duration' => $flight, 'age' => $now - (float) $r['created'], 'deliver_at' => (float) $r['deliver_at'], 'land_col' => isset($r['land_col']) && $r['land_col'] !== null ? (int) $r['land_col'] : null, 'col' => isset($r['from_col']) && $r['from_col'] !== null ? (int) $r['from_col'] : null, 'y' => isset($r['from_y']) && $r['from_y'] !== null ? (float) $r['from_y'] : null, ]; } return $out; } /** Public view of a lobby for the given user, including incoming shots. */ public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array { return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) { $touch = $this->lobbyForUser($userId); if ($touch && $touch['status'] === 'finished') { $this->maybeResetLobby($touch['id']); } if ($touch && $touch['status'] === 'playing') { if ($snapshot !== null || $score !== null || $eliminated) { $this->updateSnapshot($userId, $snapshot, $score, $eliminated); } else { $this->pdo->prepare( 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$this->now(), $touch['id'], $userId]); } } $shotResults = []; if ($outgoing && $touch && $touch['status'] === 'playing') { $shotResults = $this->recordShots($userId, $outgoing); } $lobby = $this->lobbyForUser($userId); if (!$lobby) { return [ 'lobby' => null, 'incoming' => [], 'shot_results' => $shotResults, 'shot_flights' => [], ]; } $incoming = []; if ($lobby['status'] === 'playing') { $incoming = $this->takeIncoming($lobby['id'], $userId); } $flights = []; if ($lobby['status'] === 'playing') { $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']); } return [ 'lobby' => $this->presentLobby($lobby, $userId), 'incoming' => $incoming, 'shot_results' => $shotResults, 'shot_flights' => $flights, ]; }); } public function presentLobby(array $lobby, string $userId): array { $members = $this->members($lobby['id']); $players = []; foreach ($members as $m) { $snap = null; if (is_string($m['snapshot']) && $m['snapshot'] !== '') { $decoded = json_decode($m['snapshot'], true); $snap = is_array($decoded) ? $decoded : null; } $players[] = [ 'id' => $m['user_id'], 'name' => $m['name'], 'ready' => (bool) (int) $m['ready'], 'eliminated' => (bool) (int) $m['eliminated'], 'place' => $m['place'] !== null ? (int) $m['place'] : null, 'is_host' => $m['user_id'] === $lobby['host_id'], 'is_me' => $m['user_id'] === $userId, 'score' => (int) $m['score'], 'snapshot' => $m['user_id'] === $userId ? null : $snap, 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())), ]; } $rankings = []; if ($lobby['status'] === 'finished' || $lobby['finished']) { $all = $this->members($lobby['id'], true); foreach ($all as $m) { if ($m['place'] !== null) { $rankings[] = [ 'place' => (int) $m['place'], 'id' => $m['user_id'], 'name' => $m['name'], 'score' => (int) $m['score'], ]; } } usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']); } $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true); return [ 'id' => $lobby['id'], 'code' => $lobby['code'], 'status' => $lobby['status'], 'host_id' => $lobby['host_id'], 'miss_chance' => (float) $lobby['miss_chance'], 'flight_duration' => (float) $lobby['flight_duration'], 'players' => $players, 'all_ready' => $allReady, 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2, 'rankings' => $rankings, 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null, 'podium_seconds' => METEORS_PODIUM_SECONDS, ]; } }