BlueGit

projects-timfalken-com allianties

Files

allianties / server / lib / Engine.php

Engine.php

Engine.php 55.5 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4/**
5 * Pure, deterministic Allianties rule engine.
6 * Server and tests share this. The client replays the same event log.
7 *
8 * Extra rules (jury, shrinking arena, and future ones) are toggles on the
9 * game's `rules` object and are applied only from here, so they can be
10 * turned on or off without touching the rest of the stack.
11 */
12final class Engine
13{
14 public const TZ = 'Europe/Amsterdam';
15 public const STARTING_LIVES = 3;
16 public const STARTING_RANGE = 2;
17 public const STARTING_AP = 1;
18 public const MIN_PLAYERS = 2;
19 public const MAX_PLAYERS = 16;
20 public const MIN_GRID = 6;
21 public const MIN_ARENA = 3;
22 public const DEFAULT_SHRINK_DAYS = 7;
23 public const MIN_SHRINK_DAYS = 1;
24 public const MAX_SHRINK_DAYS = 30;
25 public const NOTE_MAX = 2000;
26 public const CHAT_MAX = 1000;
27 public const NAME_MAX = 64;
28 public const CODE_LEN = 6;
29
30 /** @var list<string> Allowed vis_shots values; first is the default. */
31 public const VIS_SHOTS = ['public', 'elim_public', 'known_target', 'elim_known_target'];
32 /** @var list<string> */
33 public const VIS_GIFTS = ['public', 'known_recipient', 'anonymous'];
34 /** @var list<string> */
35 public const VIS_AP = ['public', 'hidden'];
36 /** @var list<string> */
37 public const VIS_RANGE = ['public', 'known_in_range', 'hidden'];
38 /** @var list<string> */
39 public const VIS_LIVES = ['public', 'hidden'];
40
41 /** @var list<string> */
42 public const COLORS = [
43 '#e74c3c', '#3498db', '#2ecc71', '#f1c40f',
44 '#9b59b6', '#e67e22', '#1abc9c', '#e91e63',
45 '#00bcd4', '#8bc34a', '#ff5722', '#3f51b5',
46 '#795548', '#607d8b', '#cddc39', '#ff9800',
47 ];
48
49 /** Injected unix timestamp for tests; null means time(). */
50 public static ?int $now = null;
51
52 public static function now(): int
53 {
54 return self::$now ?? time();
55 }
56
57 public static function defaultRules(): array
58 {
59 return [
60 'jury' => true,
61 'shrinking_arena' => false,
62 'shrink_interval_days' => self::DEFAULT_SHRINK_DAYS,
63 'ceasefire' => false,
64 'ceasefire_ranges' => [],
65 'ap_loot' => false,
66 'ap_time' => '00:00',
67 'vis_shots' => 'public',
68 'vis_gifts' => 'public',
69 'vis_ap' => 'public',
70 'vis_range' => 'public',
71 'vis_lives' => 'public',
72 ];
73 }
74
75 public static function normalizeRules(array $raw): array
76 {
77 $d = self::defaultRules();
78 $d['jury'] = array_key_exists('jury', $raw) ? (bool) $raw['jury'] : true;
79 $d['shrinking_arena'] = !empty($raw['shrinking_arena']);
80 $n = isset($raw['shrink_interval_days']) ? (int) $raw['shrink_interval_days'] : self::DEFAULT_SHRINK_DAYS;
81 if ($n < self::MIN_SHRINK_DAYS) {
82 $n = self::MIN_SHRINK_DAYS;
83 }
84 if ($n > self::MAX_SHRINK_DAYS) {
85 $n = self::MAX_SHRINK_DAYS;
86 }
87 $d['shrink_interval_days'] = $n;
88 $d['ceasefire'] = self::asBool($raw['ceasefire'] ?? false);
89 $d['ceasefire_ranges'] = self::normalizeRanges($raw['ceasefire_ranges'] ?? []);
90 $d['ap_loot'] = self::asBool($raw['ap_loot'] ?? false);
91 $hm = self::parseHm($raw['ap_time'] ?? '00:00');
92 $d['ap_time'] = $hm ?? '00:00';
93 $d['vis_shots'] = self::visChoice($raw['vis_shots'] ?? null, self::VIS_SHOTS, 'public');
94 $d['vis_gifts'] = self::visChoice($raw['vis_gifts'] ?? null, self::VIS_GIFTS, 'public');
95 $d['vis_ap'] = self::visChoice($raw['vis_ap'] ?? null, self::VIS_AP, 'public');
96 $d['vis_range'] = self::visChoice($raw['vis_range'] ?? null, self::VIS_RANGE, 'public');
97 $d['vis_lives'] = self::visChoice($raw['vis_lives'] ?? null, self::VIS_LIVES, 'public');
98 return $d;
99 }
100
101 /** Square board: at least 6, about 6 tiles of space per player. */
102 public static function gridSize(int $n): int
103 {
104 if ($n < 1) {
105 $n = 1;
106 }
107 return max(self::MIN_GRID, (int) ceil(sqrt($n * 6)));
108 }
109
110 /** Largest inset that still leaves a MIN_ARENA playable square. */
111 public static function maxInset(int $size): int
112 {
113 return max(0, (int) floor(($size - self::MIN_ARENA) / 2));
114 }
115
116 /**
117 * Place players evenly on a ring around the centre, on unique tiles,
118 * starting at the top and going clockwise. Never on the same tile.
119 *
120 * @return list<array{x:int,y:int}>
121 */
122 public static function startingPositions(int $n, int $size): array
123 {
124 if ($n < 1) {
125 return [];
126 }
127 $cx = ($size - 1) / 2.0;
128 $cy = ($size - 1) / 2.0;
129 $radius = max(1.0, ($size - 1) / 2.0 - 1.0);
130 $used = [];
131 $out = [];
132 for ($i = 0; $i < $n; $i++) {
133 $ang = -M_PI / 2 + ($i * 2 * M_PI / $n);
134 $fx = $cx + $radius * cos($ang);
135 $fy = $cy + $radius * sin($ang);
136 $x = (int) max(0, min($size - 1, (int) round($fx)));
137 $y = (int) max(0, min($size - 1, (int) round($fy)));
138 $key = $x . ',' . $y;
139 if (isset($used[$key])) {
140 $found = false;
141 for ($d = 1; $d < $size * 2 && !$found; $d++) {
142 for ($dx = -$d; $dx <= $d && !$found; $dx++) {
143 for ($dy = -$d; $dy <= $d; $dy++) {
144 if (max(abs($dx), abs($dy)) !== $d) {
145 continue;
146 }
147 $nx = $x + $dx;
148 $ny = $y + $dy;
149 if ($nx < 0 || $ny < 0 || $nx >= $size || $ny >= $size) {
150 continue;
151 }
152 $k2 = $nx . ',' . $ny;
153 if (!isset($used[$k2])) {
154 $x = $nx;
155 $y = $ny;
156 $key = $k2;
157 $found = true;
158 break;
159 }
160 }
161 }
162 }
163 }
164 $used[$key] = true;
165 $out[] = ['x' => $x, 'y' => $y];
166 }
167 return $out;
168 }
169
170 public static function chebyshev(int $x1, int $y1, int $x2, int $y2): int
171 {
172 return max(abs($x1 - $x2), abs($y1 - $y2));
173 }
174
175 public static function inBounds(int $size, int $x, int $y): bool
176 {
177 return $x >= 0 && $y >= 0 && $x < $size && $y < $size;
178 }
179
180 public static function isPassable(int $size, int $inset, int $x, int $y): bool
181 {
182 if (!self::inBounds($size, $x, $y)) {
183 return false;
184 }
185 return $x >= $inset && $y >= $inset && $x < $size - $inset && $y < $size - $inset;
186 }
187
188 /**
189 * Next occurrence of a Europe/Amsterdam wall-clock time strictly after $from.
190 * Used for the per-lobby daily AP time (default 00:00).
191 * If that clock time is skipped by a spring-forward DST gap, PHP's
192 * DateTime::setTime lands on the first valid instant after the gap.
193 */
194 public static function nextDistribution(int $from, ?string $hm = null): int
195 {
196 $hm = self::parseHm($hm ?? '00:00') ?? '00:00';
197 [$h, $min] = array_map('intval', explode(':', $hm));
198 $tz = new DateTimeZone(self::TZ);
199 $dt = (new DateTime('@' . $from))->setTimezone($tz);
200 $candidate = clone $dt;
201 $candidate->setTime($h, $min, 0);
202 if ($candidate->getTimestamp() <= $from) {
203 $candidate->modify('+1 day');
204 $candidate->setTime($h, $min, 0);
205 }
206 return $candidate->getTimestamp();
207 }
208
209 /** Next 00:00 Europe/Amsterdam strictly after $from. */
210 public static function nextMidnight(int $from): int
211 {
212 return self::nextDistribution($from, '00:00');
213 }
214
215 /** Today's 00:00 Amsterdam on or before $from. */
216 public static function thisMidnight(int $from): int
217 {
218 $tz = new DateTimeZone(self::TZ);
219 $dt = new DateTime('@' . $from);
220 $dt->setTimezone($tz);
221 $dt->setTime(0, 0, 0);
222 return $dt->getTimestamp();
223 }
224
225 /**
226 * A new lobby (status=lobby) with the host as first member.
227 */
228 public static function newLobby(
229 string $id,
230 string $code,
231 string $hostId,
232 string $hostName,
233 ?string $avatar,
234 array $rules,
235 int $now
236 ): array {
237 $rules = self::normalizeRules($rules);
238 return [
239 'id' => $id,
240 'code' => $code,
241 'host_id' => $hostId,
242 'status' => 'lobby',
243 'created_at' => $now,
244 'started_at' => null,
245 'finished_at' => null,
246 'rules' => $rules,
247 'grid' => self::MIN_GRID,
248 'day' => 0,
249 'next_distribution_at' => null,
250 'arena_inset' => 0,
251 'winner_id' => null,
252 'draw' => false,
253 'players' => [
254 self::newPlayer($hostId, $hostName, $avatar, 0, $now),
255 ],
256 'events' => [],
257 'votes' => [],
258 'notes' => [],
259 'messages' => [],
260 'event_seq' => 0,
261 'version' => 1,
262 ];
263 }
264
265 public static function newPlayer(string $id, string $name, ?string $avatar, int $colorIndex, int $now): array
266 {
267 $colors = self::COLORS;
268 $color = $colors[$colorIndex % count($colors)];
269 return [
270 'id' => $id,
271 'name' => $name,
272 'avatar' => $avatar,
273 'color' => $color,
274 'color_index' => $colorIndex,
275 'x' => 0,
276 'y' => 0,
277 'lives' => self::STARTING_LIVES,
278 'ap' => 0,
279 'range' => self::STARTING_RANGE,
280 'alive' => true,
281 'surrendered' => false,
282 'joined_at' => $now,
283 ];
284 }
285
286 public static function playerIndex(array $game, string $userId): ?int
287 {
288 foreach ($game['players'] as $i => $p) {
289 if ($p['id'] === $userId) {
290 return (int) $i;
291 }
292 }
293 return null;
294 }
295
296 public static function player(array $game, string $userId): ?array
297 {
298 $i = self::playerIndex($game, $userId);
299 return $i === null ? null : $game['players'][$i];
300 }
301
302 /** @return list<array> */
303 public static function living(array $game): array
304 {
305 return array_values(array_filter($game['players'], fn ($p) => !empty($p['alive'])));
306 }
307
308 public static function occupiedByLiving(array $game, int $x, int $y, ?string $except = null): ?string
309 {
310 foreach ($game['players'] as $p) {
311 if (empty($p['alive'])) {
312 continue;
313 }
314 if ($except !== null && $p['id'] === $except) {
315 continue;
316 }
317 if ((int) $p['x'] === $x && (int) $p['y'] === $y) {
318 return $p['id'];
319 }
320 }
321 return null;
322 }
323
324 public static function pushEvent(array &$game, string $type, array $data, int $now): array
325 {
326 $game['event_seq'] = (int) ($game['event_seq'] ?? 0) + 1;
327 $game['version'] = (int) ($game['version'] ?? 0) + 1;
328 $ev = array_merge([
329 'id' => $game['event_seq'],
330 't' => $now,
331 'type' => $type,
332 ], $data);
333 $game['events'][] = $ev;
334 return $ev;
335 }
336
337 /**
338 * Join a lobby. Throws RuntimeException with a stable error code.
339 */
340 public static function join(array $game, string $userId, string $name, ?string $avatar, int $now): array
341 {
342 if ($game['status'] !== 'lobby') {
343 throw new RuntimeException('game_started');
344 }
345 if (self::playerIndex($game, $userId) !== null) {
346 return $game; // already in
347 }
348 if (count($game['players']) >= self::MAX_PLAYERS) {
349 throw new RuntimeException('lobby_full');
350 }
351 $game['players'][] = self::newPlayer($userId, $name, $avatar, count($game['players']), $now);
352 return $game;
353 }
354
355 public static function leaveLobby(array $game, string $userId, int $now): ?array
356 {
357 if ($game['status'] !== 'lobby') {
358 throw new RuntimeException('game_started');
359 }
360 $idx = self::playerIndex($game, $userId);
361 if ($idx === null) {
362 return $game;
363 }
364 array_splice($game['players'], $idx, 1);
365 if (count($game['players']) === 0) {
366 return null; // delete lobby
367 }
368 // Re-index colours; if host left, earliest joiner becomes host.
369 foreach ($game['players'] as $i => &$p) {
370 $p['color_index'] = $i;
371 $p['color'] = self::COLORS[$i % count(self::COLORS)];
372 }
373 unset($p);
374 if ($game['host_id'] === $userId) {
375 $game['host_id'] = $game['players'][0]['id'];
376 }
377 return $game;
378 }
379
380 public static function setLobbyRules(array $game, string $userId, array $rules): array
381 {
382 if ($game['status'] !== 'lobby') {
383 throw new RuntimeException('game_started');
384 }
385 if ($game['host_id'] !== $userId) {
386 throw new RuntimeException('not_host');
387 }
388 $game['rules'] = self::normalizeRules(array_merge($game['rules'], $rules));
389 return $game;
390 }
391
392 public static function start(array $game, string $userId, int $now): array
393 {
394 if ($game['status'] !== 'lobby') {
395 throw new RuntimeException('game_started');
396 }
397 if ($game['host_id'] !== $userId) {
398 throw new RuntimeException('not_host');
399 }
400 $n = count($game['players']);
401 if ($n < self::MIN_PLAYERS) {
402 throw new RuntimeException('min_players');
403 }
404 $size = self::gridSize($n);
405 $pos = self::startingPositions($n, $size);
406 $game['grid'] = $size;
407 $game['status'] = 'running';
408 $game['started_at'] = $now;
409 $game['day'] = 0;
410 $game['arena_inset'] = 0;
411 $game['next_distribution_at'] = self::nextDistribution($now, $game['rules']['ap_time'] ?? '00:00');
412 $placed = [];
413 foreach ($game['players'] as $i => &$p) {
414 $p['x'] = $pos[$i]['x'];
415 $p['y'] = $pos[$i]['y'];
416 $p['lives'] = self::STARTING_LIVES;
417 $p['ap'] = self::STARTING_AP;
418 $p['range'] = self::STARTING_RANGE;
419 $p['alive'] = true;
420 $p['surrendered'] = false;
421 $placed[] = [
422 'id' => $p['id'],
423 'x' => $p['x'],
424 'y' => $p['y'],
425 'color' => $p['color'],
426 'name' => $p['name'],
427 ];
428 }
429 unset($p);
430 self::pushEvent($game, 'start', [
431 'grid' => $size,
432 'players' => $placed,
433 'rules' => $game['rules'],
434 'spend' => false,
435 ], $now);
436 return $game;
437 }
438
439 /**
440 * Catch up daily distributions (AP, jury, shrink) until $now.
441 * Safe to call on every request.
442 */
443 public static function applyDue(array $game, int $now): array
444 {
445 if ($game['status'] !== 'running') {
446 return $game;
447 }
448 $guard = 0;
449 while (
450 isset($game['next_distribution_at'])
451 && $game['next_distribution_at'] !== null
452 && (int) $game['next_distribution_at'] <= $now
453 && $game['status'] === 'running'
454 && $guard < 4000
455 ) {
456 $at = (int) $game['next_distribution_at'];
457 $game = self::distributeOneDay($game, $at);
458 $game['next_distribution_at'] = self::nextDistribution($at, $game['rules']['ap_time'] ?? '00:00');
459 $guard++;
460 }
461 return $game;
462 }
463
464 public static function daysUntilShrink(array $game): ?int
465 {
466 if ($game['status'] !== 'running' || empty($game['rules']['shrinking_arena'])) {
467 return null;
468 }
469 $size = (int) $game['grid'];
470 if ((int) $game['arena_inset'] >= self::maxInset($size)) {
471 return null;
472 }
473 $interval = (int) $game['rules']['shrink_interval_days'];
474 $day = (int) $game['day'];
475 // Next shrink at day = k*interval for k>=1, i.e. after `interval` midnights.
476 $nextAt = (int) (ceil(($day + 1) / $interval) * $interval);
477 if ($nextAt <= $day) {
478 $nextAt += $interval;
479 }
480 return $nextAt - $day;
481 }
482
483 private static function distributeOneDay(array $game, int $at): array
484 {
485 $game['day'] = (int) $game['day'] + 1;
486 $day = (int) $game['day'];
487 $grants = [];
488 $jury = null;
489
490 // 1. Shrink first so someone who dies today does not receive AP.
491 $shrink = null;
492 if (!empty($game['rules']['shrinking_arena'])) {
493 $interval = (int) $game['rules']['shrink_interval_days'];
494 $size = (int) $game['grid'];
495 $inset = (int) $game['arena_inset'];
496 if ($interval > 0 && $day % $interval === 0 && $inset < self::maxInset($size)) {
497 $result = self::applyShrink($game, $at);
498 $game = $result['game'];
499 $shrink = $result['report'];
500 }
501 }
502
503 if ($game['status'] !== 'running') {
504 // Finished mid-shrink; still record the day event.
505 self::pushEvent($game, 'daily', [
506 'day' => $day,
507 'grants' => $grants,
508 'jury' => $jury,
509 'shrink' => $shrink,
510 'spend' => false,
511 ], $at);
512 return $game;
513 }
514
515 // 2. Jury: unique or tied living targets each get +1. Votes stay secret.
516 if (!empty($game['rules']['jury'])) {
517 $jury = self::tallyJury($game);
518 }
519
520 // 3. Grant 1 AP to every living player, plus jury bonus.
521 foreach ($game['players'] as &$p) {
522 if (empty($p['alive'])) {
523 continue;
524 }
525 $add = 1;
526 if ($jury && in_array($p['id'], $jury['winners'], true)) {
527 $add += 1;
528 }
529 $p['ap'] = (int) $p['ap'] + $add;
530 $grants[$p['id']] = $add;
531 }
532 unset($p);
533
534 // Votes reset for the new day (changeable until the next distribution).
535 $game['votes'] = [];
536
537 self::pushEvent($game, 'daily', [
538 'day' => $day,
539 'grants' => $grants,
540 'jury' => $jury,
541 'shrink' => $shrink,
542 'spend' => false,
543 ], $at);
544
545 $game = self::checkEnd($game, $at);
546 return $game;
547 }
548
549 /**
550 * Tally current votes. Winners are living players with the strictly
551 * highest count; on a tie every tied player is a winner (each +1 AP).
552 * Players with zero votes never win, even if nobody voted (no award).
553 *
554 * @return array{winners:list<string>,counts:array<string,int>,votes_cast:int}|null
555 */
556 public static function tallyJury(array $game): ?array
557 {
558 $livingIds = [];
559 foreach (self::living($game) as $p) {
560 $livingIds[$p['id']] = true;
561 }
562 $counts = [];
563 $cast = 0;
564 foreach ($game['votes'] as $voter => $target) {
565 if (!is_string($voter) || !is_string($target)) {
566 continue;
567 }
568 if (!isset($livingIds[$target])) {
569 continue;
570 }
571 // Voter should be a dead participant.
572 $v = self::player($game, $voter);
573 if (!$v || !empty($v['alive'])) {
574 continue;
575 }
576 $counts[$target] = ($counts[$target] ?? 0) + 1;
577 $cast++;
578 }
579 if ($cast === 0 || $counts === []) {
580 return ['winners' => [], 'counts' => $counts, 'votes_cast' => 0];
581 }
582 $max = max($counts);
583 $winners = [];
584 foreach ($counts as $id => $c) {
585 if ($c === $max) {
586 $winners[] = $id;
587 }
588 }
589 sort($winners);
590 return ['winners' => $winners, 'counts' => $counts, 'votes_cast' => $cast];
591 }
592
593 /**
594 * Advance arena_inset by 1. Players on the new outer ring lose 1 life
595 * and, if still alive, are pushed to the nearest free passable tile.
596 *
597 * @return array{game:array,report:array}
598 */
599 public static function applyShrink(array $game, int $now): array
600 {
601 $size = (int) $game['grid'];
602 $newInset = (int) $game['arena_inset'] + 1;
603 if ($newInset > self::maxInset($size)) {
604 return ['game' => $game, 'report' => null];
605 }
606 $game['arena_inset'] = $newInset;
607 $moved = [];
608 $hurt = [];
609 $killed = [];
610 $crushed = [];
611
612 // Deterministic order: by player id.
613 $indices = [];
614 foreach ($game['players'] as $i => $p) {
615 $indices[] = $i;
616 }
617 usort($indices, function ($a, $b) use ($game) {
618 return strcmp($game['players'][$a]['id'], $game['players'][$b]['id']);
619 });
620
621 foreach ($indices as $i) {
622 $p = $game['players'][$i];
623 if (empty($p['alive'])) {
624 continue;
625 }
626 $x = (int) $p['x'];
627 $y = (int) $p['y'];
628 if (self::isPassable($size, $newInset, $x, $y)) {
629 continue;
630 }
631 // Standing on the new ring: take 1 damage.
632 $p['lives'] = (int) $p['lives'] - 1;
633 $hurt[] = $p['id'];
634 if ($p['lives'] <= 0) {
635 $p['lives'] = 0;
636 $p['alive'] = false;
637 $p['ap'] = 0;
638 $killed[] = $p['id'];
639 $game['players'][$i] = $p;
640 self::pushEvent($game, 'death', [
641 'player' => $p['id'],
642 'cause' => 'shrink',
643 'spend' => false,
644 ], $now);
645 continue;
646 }
647 $dest = self::nearestFreeTile($game, $size, $newInset, $x, $y, $p['id']);
648 if ($dest === null) {
649 // No free inward tile: crushed, eliminated.
650 $p['lives'] = 0;
651 $p['alive'] = false;
652 $p['ap'] = 0;
653 $killed[] = $p['id'];
654 $crushed[] = $p['id'];
655 $game['players'][$i] = $p;
656 self::pushEvent($game, 'death', [
657 'player' => $p['id'],
658 'cause' => 'crushed',
659 'spend' => false,
660 ], $now);
661 continue;
662 }
663 $from = ['x' => $x, 'y' => $y];
664 $p['x'] = $dest['x'];
665 $p['y'] = $dest['y'];
666 $moved[] = ['id' => $p['id'], 'from' => $from, 'to' => $dest];
667 $game['players'][$i] = $p;
668 }
669
670 $report = [
671 'inset' => $newInset,
672 'hurt' => $hurt,
673 'killed' => $killed,
674 'crushed' => $crushed,
675 'moved' => $moved,
676 ];
677 self::pushEvent($game, 'shrink', array_merge($report, ['spend' => false]), $now);
678 $game = self::checkEnd($game, $now);
679 return ['game' => $game, 'report' => $report];
680 }
681
682 /**
683 * Nearest free passable tile, Chebyshev first, then Euclidean to centre,
684 * then (y, x) for a stable leftover tie.
685 *
686 * @return array{x:int,y:int}|null
687 */
688 public static function nearestFreeTile(
689 array $game,
690 int $size,
691 int $inset,
692 int $fromX,
693 int $fromY,
694 string $moverId
695 ): ?array {
696 $cx = ($size - 1) / 2.0;
697 $cy = ($size - 1) / 2.0;
698 $best = null;
699 $bestKey = null;
700 for ($x = $inset; $x < $size - $inset; $x++) {
701 for ($y = $inset; $y < $size - $inset; $y++) {
702 if (self::occupiedByLiving($game, $x, $y, $moverId) !== null) {
703 continue;
704 }
705 $d = self::chebyshev($fromX, $fromY, $x, $y);
706 $dc = ($x - $cx) * ($x - $cx) + ($y - $cy) * ($y - $cy);
707 $key = sprintf('%04d-%012.6f-%04d-%04d', $d, $dc, $y, $x);
708 if ($bestKey === null || $key < $bestKey) {
709 $bestKey = $key;
710 $best = ['x' => $x, 'y' => $y];
711 }
712 }
713 }
714 return $best;
715 }
716
717 public static function checkEnd(array $game, int $now): array
718 {
719 if ($game['status'] !== 'running') {
720 return $game;
721 }
722 $alive = self::living($game);
723 if (count($alive) === 1) {
724 $game['status'] = 'finished';
725 $game['finished_at'] = $now;
726 $game['winner_id'] = $alive[0]['id'];
727 $game['draw'] = false;
728 self::pushEvent($game, 'win', [
729 'player' => $alive[0]['id'],
730 'spend' => false,
731 ], $now);
732 } elseif (count($alive) === 0) {
733 $game['status'] = 'finished';
734 $game['finished_at'] = $now;
735 $game['winner_id'] = null;
736 $game['draw'] = true;
737 self::pushEvent($game, 'draw', ['spend' => false], $now);
738 }
739 return $game;
740 }
741
742 /**
743 * Legal actions for a viewer (after applyDue).
744 *
745 * @return array{
746 * move:list<array{x:int,y:int}>,
747 * shoot:list<string>,
748 * give:list<string>,
749 * upgrade:bool,
750 * surrender:bool,
751 * vote:list<string>|null,
752 * my_vote:?string
753 * }
754 */
755 public static function legal(array $game, string $userId, ?int $now = null): array
756 {
757 $now = $now ?? self::now();
758
759 $empty = [
760 'move' => [],
761 'shoot' => [],
762 'give' => [],
763 'upgrade' => false,
764 'surrender' => false,
765 'vote' => null,
766 'my_vote' => null,
767 'ceasefire' => false,
768 ];
769 if ($game['status'] !== 'running') {
770 return $empty;
771 }
772 $me = self::player($game, $userId);
773 if (!$me) {
774 return $empty;
775 }
776 $size = (int) $game['grid'];
777 $inset = (int) $game['arena_inset'];
778 if (empty($me['alive'])) {
779 $vote = null;
780 $myVote = null;
781 if (!empty($game['rules']['jury'])) {
782 $vote = [];
783 foreach (self::living($game) as $p) {
784 $vote[] = $p['id'];
785 }
786 $v = $game['votes'][$userId] ?? null;
787 $myVote = is_string($v) ? $v : null;
788 }
789 $empty['vote'] = $vote;
790 $empty['my_vote'] = $myVote;
791 return $empty;
792 }
793 $empty['surrender'] = true;
794 if ((int) $me['ap'] < 1) {
795 return $empty;
796 }
797 // Moves: 8 neighbours.
798 for ($dx = -1; $dx <= 1; $dx++) {
799 for ($dy = -1; $dy <= 1; $dy++) {
800 if ($dx === 0 && $dy === 0) {
801 continue;
802 }
803 $x = (int) $me['x'] + $dx;
804 $y = (int) $me['y'] + $dy;
805 if (!self::isPassable($size, $inset, $x, $y)) {
806 continue;
807 }
808 if (self::occupiedByLiving($game, $x, $y, $userId) !== null) {
809 continue;
810 }
811 $empty['move'][] = ['x' => $x, 'y' => $y];
812 }
813 }
814 $range = (int) $me['range'];
815 foreach ($game['players'] as $p) {
816 if ($p['id'] === $userId || empty($p['alive'])) {
817 continue;
818 }
819 $d = self::chebyshev((int) $me['x'], (int) $me['y'], (int) $p['x'], (int) $p['y']);
820 if ($d <= $range) {
821 $empty['shoot'][] = $p['id'];
822 $empty['give'][] = $p['id'];
823 }
824 }
825 // Upgrade: cap at the board's max Chebyshev distance (covers the board).
826 $maxRange = max(1, $size - 1);
827 $empty['upgrade'] = (int) $me['range'] < $maxRange;
828 if (self::ceasefireActive($game, $now)) {
829 $empty['shoot'] = [];
830 $empty['ceasefire'] = true;
831 } else {
832 $empty['ceasefire'] = false;
833 }
834 return $empty;
835 }
836
837 /**
838 * Apply a player action. $action = {type, ...}.
839 * Types: move, shoot, give, upgrade, surrender, vote.
840 */
841 public static function applyAction(array $game, string $userId, array $action, int $now): array
842 {
843 $game = self::applyDue($game, $now);
844 if ($game['status'] !== 'running') {
845 throw new RuntimeException('game_finished');
846 }
847 $type = (string) ($action['type'] ?? '');
848 $me = self::player($game, $userId);
849 if (!$me) {
850 throw new RuntimeException('not_in_game');
851 }
852
853 if ($type === 'vote') {
854 return self::actVote($game, $userId, $action, $now);
855 }
856 if ($type === 'surrender') {
857 return self::actSurrender($game, $userId, $now);
858 }
859 if (empty($me['alive'])) {
860 throw new RuntimeException('dead');
861 }
862 $legal = self::legal($game, $userId, $now);
863 return match ($type) {
864 'move' => self::actMove($game, $userId, $action, $legal, $now),
865 'shoot' => self::actShoot($game, $userId, $action, $legal, $now),
866 'give' => self::actGive($game, $userId, $action, $legal, $now),
867 'upgrade' => self::actUpgrade($game, $userId, $legal, $now),
868 default => throw new RuntimeException('unknown_action'),
869 };
870 }
871
872 private static function spendAp(array &$game, string $userId, int $n = 1): void
873 {
874 $i = self::playerIndex($game, $userId);
875 if ($i === null || (int) $game['players'][$i]['ap'] < $n) {
876 throw new RuntimeException('no_ap');
877 }
878 $game['players'][$i]['ap'] = (int) $game['players'][$i]['ap'] - $n;
879 }
880
881 private static function actMove(array $game, string $userId, array $action, array $legal, int $now): array
882 {
883 $x = (int) ($action['x'] ?? -1);
884 $y = (int) ($action['y'] ?? -1);
885 $ok = false;
886 foreach ($legal['move'] as $t) {
887 if ((int) $t['x'] === $x && (int) $t['y'] === $y) {
888 $ok = true;
889 break;
890 }
891 }
892 if (!$ok) {
893 throw new RuntimeException('invalid_move');
894 }
895 self::spendAp($game, $userId, 1);
896 $i = self::playerIndex($game, $userId);
897 $from = ['x' => (int) $game['players'][$i]['x'], 'y' => (int) $game['players'][$i]['y']];
898 $game['players'][$i]['x'] = $x;
899 $game['players'][$i]['y'] = $y;
900 self::pushEvent($game, 'move', [
901 'player' => $userId,
902 'from' => $from,
903 'to' => ['x' => $x, 'y' => $y],
904 'spend' => true,
905 ], $now);
906 return $game;
907 }
908
909 private static function actShoot(array $game, string $userId, array $action, array $legal, int $now): array
910 {
911 if (self::ceasefireActive($game, $now)) {
912 throw new RuntimeException('ceasefire');
913 }
914 $targetId = (string) ($action['target'] ?? '');
915 if (!in_array($targetId, $legal['shoot'], true)) {
916 throw new RuntimeException('out_of_range');
917 }
918 self::spendAp($game, $userId, 1);
919 $ti = self::playerIndex($game, $targetId);
920 $game['players'][$ti]['lives'] = (int) $game['players'][$ti]['lives'] - 1;
921 $livesLeft = (int) $game['players'][$ti]['lives'];
922 $killed = false;
923 $loot = 0;
924 if ($livesLeft <= 0) {
925 $game['players'][$ti]['lives'] = 0;
926 $game['players'][$ti]['alive'] = false;
927 $killed = true;
928 // AP loot (lobby option, default off): shooter takes the target's
929 // remaining AP on an eliminating shot only. Shrink/surrender do not loot.
930 if (!empty($game['rules']['ap_loot'])) {
931 $loot = max(0, (int) $game['players'][$ti]['ap']);
932 if ($loot > 0) {
933 $si = self::playerIndex($game, $userId);
934 if ($si !== null) {
935 $game['players'][$si]['ap'] = (int) $game['players'][$si]['ap'] + $loot;
936 }
937 }
938 }
939 $game['players'][$ti]['ap'] = 0;
940 }
941 $shootEv = [
942 'player' => $userId,
943 'target' => $targetId,
944 'lives_left' => max(0, $livesLeft),
945 'damage' => 1,
946 'killed' => $killed,
947 'spend' => true,
948 ];
949 if ($loot > 0) {
950 $shootEv['loot'] = $loot;
951 }
952 self::pushEvent($game, 'shoot', $shootEv, $now);
953 if ($killed) {
954 $death = [
955 'player' => $targetId,
956 'cause' => 'shot',
957 'by' => $userId,
958 'spend' => false,
959 ];
960 if ($loot > 0) {
961 $death['loot'] = $loot;
962 }
963 self::pushEvent($game, 'death', $death, $now);
964 $game = self::checkEnd($game, $now);
965 }
966 return $game;
967 }
968
969 private static function actGive(array $game, string $userId, array $action, array $legal, int $now): array
970 {
971 $targetId = (string) ($action['target'] ?? '');
972 $amount = (int) ($action['amount'] ?? 0);
973 if (!in_array($targetId, $legal['give'], true)) {
974 throw new RuntimeException('out_of_range');
975 }
976 $me = self::player($game, $userId);
977 if ($amount < 1 || $amount > (int) $me['ap']) {
978 throw new RuntimeException('bad_give');
979 }
980 self::spendAp($game, $userId, $amount);
981 $ti = self::playerIndex($game, $targetId);
982 $game['players'][$ti]['ap'] = (int) $game['players'][$ti]['ap'] + $amount;
983 self::pushEvent($game, 'give', [
984 'player' => $userId,
985 'target' => $targetId,
986 'amount' => $amount,
987 'spend' => true,
988 ], $now);
989 return $game;
990 }
991
992 private static function actUpgrade(array $game, string $userId, array $legal, int $now): array
993 {
994 if (empty($legal['upgrade'])) {
995 throw new RuntimeException('invalid_move');
996 }
997 self::spendAp($game, $userId, 1);
998 $i = self::playerIndex($game, $userId);
999 $game['players'][$i]['range'] = (int) $game['players'][$i]['range'] + 1;
1000 self::pushEvent($game, 'upgrade', [
1001 'player' => $userId,
1002 'range' => (int) $game['players'][$i]['range'],
1003 'spend' => true,
1004 ], $now);
1005 return $game;
1006 }
1007
1008 private static function actSurrender(array $game, string $userId, int $now): array
1009 {
1010 $i = self::playerIndex($game, $userId);
1011 if (empty($game['players'][$i]['alive'])) {
1012 throw new RuntimeException('dead');
1013 }
1014 $game['players'][$i]['alive'] = false;
1015 $game['players'][$i]['lives'] = 0;
1016 $game['players'][$i]['ap'] = 0;
1017 $game['players'][$i]['surrendered'] = true;
1018 self::pushEvent($game, 'surrender', [
1019 'player' => $userId,
1020 'spend' => false,
1021 ], $now);
1022 self::pushEvent($game, 'death', [
1023 'player' => $userId,
1024 'cause' => 'surrender',
1025 'spend' => false,
1026 ], $now);
1027 return self::checkEnd($game, $now);
1028 }
1029
1030 private static function actVote(array $game, string $userId, array $action, int $now): array
1031 {
1032 if (empty($game['rules']['jury'])) {
1033 throw new RuntimeException('cannot_vote');
1034 }
1035 $me = self::player($game, $userId);
1036 if (!$me || !empty($me['alive'])) {
1037 throw new RuntimeException('cannot_vote');
1038 }
1039 $targetId = (string) ($action['target'] ?? '');
1040 $t = self::player($game, $targetId);
1041 if (!$t || empty($t['alive'])) {
1042 throw new RuntimeException('bad_vote');
1043 }
1044 $game['votes'][$userId] = $targetId;
1045 // Votes are secret: no public event, but version bumps so polls refresh.
1046 $game['_vote_updated'] = $now;
1047 $game['version'] = (int) ($game['version'] ?? 0) + 1;
1048 return $game;
1049 }
1050
1051 public static function setNote(array $game, string $viewerId, string $subjectId, string $text): array
1052 {
1053 if (self::playerIndex($game, $viewerId) === null) {
1054 throw new RuntimeException('not_in_game');
1055 }
1056 if (self::playerIndex($game, $subjectId) === null) {
1057 throw new RuntimeException('not_in_game');
1058 }
1059 $text = trim($text);
1060 if (mb_strlen($text) > self::NOTE_MAX) {
1061 $text = mb_substr($text, 0, self::NOTE_MAX);
1062 }
1063 $key = $viewerId . "\0" . $subjectId;
1064 if ($text === '') {
1065 unset($game['notes'][$key]);
1066 } else {
1067 $game['notes'][$key] = $text;
1068 }
1069 $game['version'] = (int) ($game['version'] ?? 0) + 1;
1070 return $game;
1071 }
1072
1073 public static function addMessage(array $game, string $fromId, string $toId, string $text, int $now): array
1074 {
1075 if (self::playerIndex($game, $fromId) === null || self::playerIndex($game, $toId) === null) {
1076 throw new RuntimeException('not_in_game');
1077 }
1078 if ($fromId === $toId) {
1079 throw new RuntimeException('invalid_move');
1080 }
1081 $text = trim($text);
1082 if ($text === '' || mb_strlen($text) > self::CHAT_MAX) {
1083 throw new RuntimeException('bad_give');
1084 }
1085 if (preg_match('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', $text)) {
1086 throw new RuntimeException('bad_give');
1087 }
1088 $game['messages'][] = [
1089 'id' => count($game['messages']) + 1,
1090 'from' => $fromId,
1091 'to' => $toId,
1092 'text' => $text,
1093 't' => $now,
1094 ];
1095 $game['version'] = (int) ($game['version'] ?? 0) + 1;
1096 return $game;
1097 }
1098
1099 /**
1100 * Viewer-specific presentation: hide others' votes and notes, hide
1101 * other people's private chats, include legal actions and shrink ETA.
1102 */
1103
1104 public static function visChoice(mixed $raw, array $allowed, string $default): string
1105 {
1106 if (is_string($raw) && in_array($raw, $allowed, true)) {
1107 return $raw;
1108 }
1109 return $default;
1110 }
1111
1112 /**
1113 * Per-viewer player card. Own lives/AP/range are always present.
1114 * Movement, identity, and alive/dead are always public.
1115 * Hidden numeric stats are omitted (null) so the API does not leak them.
1116 *
1117 * @param array<string,mixed> $game
1118 * @param array<string,mixed> $p
1119 * @return array<string,mixed>
1120 */
1121 public static function presentPlayer(array $game, array $p, string $viewerId, string $noteKey): array
1122 {
1123 $rules = $game['rules'] ?? self::defaultRules();
1124 $isSelf = $p['id'] === $viewerId;
1125 $out = [
1126 'id' => $p['id'],
1127 'name' => $p['name'],
1128 'avatar' => $p['avatar'],
1129 'color' => $p['color'],
1130 'x' => (int) $p['x'],
1131 'y' => (int) $p['y'],
1132 'alive' => !empty($p['alive']),
1133 'surrendered' => !empty($p['surrendered']),
1134 'is_you' => $isSelf,
1135 'is_host' => $p['id'] === $game['host_id'],
1136 'note' => $game['notes'][$noteKey] ?? '',
1137 'lives' => null,
1138 'ap' => null,
1139 'range' => null,
1140 ];
1141 if ($isSelf || ($rules['vis_lives'] ?? 'public') === 'public') {
1142 $out['lives'] = (int) $p['lives'];
1143 }
1144 if ($isSelf || ($rules['vis_ap'] ?? 'public') === 'public') {
1145 $out['ap'] = (int) $p['ap'];
1146 }
1147 if ($isSelf || ($rules['vis_range'] ?? 'public') === 'public') {
1148 $out['range'] = (int) $p['range'];
1149 } elseif (($rules['vis_range'] ?? 'public') === 'known_in_range'
1150 && self::viewerInRangeOf($game, $viewerId, $p)) {
1151 $out['range'] = (int) $p['range'];
1152 }
1153 return $out;
1154 }
1155
1156 /**
1157 * True when the viewer is within $subject's current firing range
1158 * (Chebyshev, including diagonals). Used for vis_range = known_in_range.
1159 *
1160 * @param array<string,mixed> $game
1161 * @param array<string,mixed> $subject
1162 */
1163 public static function viewerInRangeOf(array $game, string $viewerId, array $subject): bool
1164 {
1165 $v = self::player($game, $viewerId);
1166 if ($v === null) {
1167 return false;
1168 }
1169 $dist = self::chebyshev((int) $v['x'], (int) $v['y'], (int) $subject['x'], (int) $subject['y']);
1170 return $dist <= (int) $subject['range'];
1171 }
1172
1173 /**
1174 * Whether $viewerId may see a shot event (who shot whom).
1175 * The shooter always sees their own shot.
1176 */
1177 public static function canSeeShot(array $rules, string $viewerId, string $shooter, string $target, bool $killed): bool
1178 {
1179 if ($viewerId === $shooter) {
1180 return true;
1181 }
1182 $mode = $rules['vis_shots'] ?? 'public';
1183 return match ($mode) {
1184 'public' => true,
1185 'elim_public' => $killed || $viewerId === $target,
1186 'known_target' => $viewerId === $target,
1187 'elim_known_target' => $killed && $viewerId === $target,
1188 default => true,
1189 };
1190 }
1191
1192 /**
1193 * Filter the stored event log for one viewer. Hidden events are omitted
1194 * entirely (no generic marker — a tick would leak that something happened).
1195 * Returns clones; the stored game is never mutated.
1196 *
1197 * @return list<array<string,mixed>>
1198 */
1199 public static function filterEvents(array $game, string $viewerId): array
1200 {
1201 $out = [];
1202 foreach ($game['events'] ?? [] as $ev) {
1203 $f = self::filterEvent($game, $ev, $viewerId);
1204 if ($f !== null) {
1205 $out[] = $f;
1206 }
1207 }
1208 return $out;
1209 }
1210
1211 /**
1212 * @param array<string,mixed> $ev
1213 * @return array<string,mixed>|null
1214 */
1215 public static function filterEvent(array $game, array $ev, string $viewerId): ?array
1216 {
1217 $rules = $game['rules'] ?? self::defaultRules();
1218 $type = $ev['type'] ?? '';
1219 $copy = $ev; // shallow copy; nested arrays are replaced when stripped
1220
1221 if ($type === 'shoot') {
1222 $shooter = (string) ($ev['player'] ?? '');
1223 $target = (string) ($ev['target'] ?? '');
1224 $killed = !empty($ev['killed']);
1225 if (!self::canSeeShot($rules, $viewerId, $shooter, $target, $killed)) {
1226 return null;
1227 }
1228 // Remaining lives belong to the target: only they (or public lives) may see them.
1229 $livesPublic = ($rules['vis_lives'] ?? 'public') === 'public' || $viewerId === $target;
1230 if (!$livesPublic) {
1231 unset($copy['lives_left']);
1232 }
1233 $copy['damage'] = (int) ($ev['damage'] ?? 1);
1234 // Loot is an AP amount: only the shooter (and public AP) may see it.
1235 if (isset($copy['loot']) && ($rules['vis_ap'] ?? 'public') !== 'public'
1236 && $viewerId !== $shooter) {
1237 unset($copy['loot']);
1238 }
1239 return $copy;
1240 }
1241
1242 if ($type === 'give') {
1243 $giver = (string) ($ev['player'] ?? '');
1244 $recipient = (string) ($ev['target'] ?? '');
1245 $mode = $rules['vis_gifts'] ?? 'public';
1246 if ($viewerId === $giver || $mode === 'public') {
1247 return $copy;
1248 }
1249 if ($mode === 'known_recipient' && $viewerId === $recipient) {
1250 return $copy;
1251 }
1252 if ($mode === 'anonymous' && $viewerId === $recipient) {
1253 unset($copy['player']);
1254 $copy['anonymous'] = true;
1255 return $copy;
1256 }
1257 return null;
1258 }
1259
1260 if ($type === 'upgrade') {
1261 $who = (string) ($ev['player'] ?? '');
1262 if ($viewerId === $who) {
1263 return $copy;
1264 }
1265 $mode = $rules['vis_range'] ?? 'public';
1266 if ($mode === 'public') {
1267 return $copy;
1268 }
1269 if ($mode === 'hidden') {
1270 return null;
1271 }
1272 // known_in_range: visible iff the viewer may currently see that player's range.
1273 $subj = self::player($game, $who);
1274 if ($subj && self::viewerInRangeOf($game, $viewerId, $subj)) {
1275 return $copy;
1276 }
1277 return null;
1278 }
1279
1280 if ($type === 'death') {
1281 // Death (alive=false) is always public. Strip "by" if the eliminating
1282 // shot is not visible to this viewer, so the killer is not leaked.
1283 $cause = $ev['cause'] ?? '';
1284 if ($cause === 'shot' && isset($ev['by'])) {
1285 $killer = (string) $ev['by'];
1286 $victim = (string) ($ev['player'] ?? '');
1287 if (!self::canSeeShot($rules, $viewerId, $killer, $victim, true)) {
1288 unset($copy['by']);
1289 }
1290 if (isset($copy['loot']) && ($rules['vis_ap'] ?? 'public') !== 'public'
1291 && $viewerId !== $killer) {
1292 unset($copy['loot']);
1293 }
1294 }
1295 return $copy;
1296 }
1297
1298 if ($type === 'daily') {
1299 $mode = $rules['vis_ap'] ?? 'public';
1300 if ($mode === 'hidden') {
1301 $grants = $ev['grants'] ?? [];
1302 if (is_array($grants)) {
1303 $copy['grants'] = array_key_exists($viewerId, $grants)
1304 ? [$viewerId => $grants[$viewerId]]
1305 : [];
1306 }
1307 }
1308 // Jury winners stay public (the announced result). Vote counts, if
1309 // present, are not needed by the client; strip to keep votes secret.
1310 if (isset($copy['jury']) && is_array($copy['jury'])) {
1311 $jury = $copy['jury'];
1312 unset($jury['counts']);
1313 $copy['jury'] = $jury;
1314 }
1315 return $copy;
1316 }
1317
1318 if ($type === 'shrink') {
1319 // Movement in the report is public. The explicit "hurt" list leaks
1320 // a life loss when lives are hidden — keep only the viewer's own id.
1321 if (($rules['vis_lives'] ?? 'public') !== 'public') {
1322 $hurt = $ev['hurt'] ?? [];
1323 $copy['hurt'] = array_values(array_filter(
1324 is_array($hurt) ? $hurt : [],
1325 fn ($id) => $id === $viewerId
1326 ));
1327 }
1328 return $copy;
1329 }
1330
1331 // move, start, surrender, win, draw, shrink deaths: always visible.
1332 return $copy;
1333 }
1334
1335 public static function present(array $game, string $viewerId, ?int $now = null): array
1336 {
1337 $now = $now ?? self::now();
1338 $legal = $game['status'] === 'running' ? self::legal($game, $viewerId, $now) : [
1339 'move' => [], 'shoot' => [], 'give' => [], 'upgrade' => false,
1340 'surrender' => false, 'vote' => null, 'my_vote' => null,
1341 ];
1342 $players = [];
1343 foreach ($game['players'] as $p) {
1344 $noteKey = $viewerId . "\0" . $p['id'];
1345 $players[] = self::presentPlayer($game, $p, $viewerId, $noteKey);
1346 }
1347 $messages = [];
1348 foreach ($game['messages'] as $m) {
1349 if ($m['from'] === $viewerId || $m['to'] === $viewerId) {
1350 $messages[] = $m;
1351 }
1352 }
1353 $events = self::filterEvents($game, $viewerId);
1354 $shrinkIn = self::daysUntilShrink($game);
1355 return [
1356 'id' => $game['id'],
1357 'code' => $game['code'],
1358 'host_id' => $game['host_id'],
1359 'status' => $game['status'],
1360 'created_at' => $game['created_at'],
1361 'started_at' => $game['started_at'],
1362 'finished_at' => $game['finished_at'],
1363 'rules' => $game['rules'],
1364 'grid' => (int) $game['grid'],
1365 'day' => (int) $game['day'],
1366 'next_distribution_at' => $game['next_distribution_at'],
1367 'arena_inset' => (int) $game['arena_inset'],
1368 'max_inset' => self::maxInset((int) $game['grid']),
1369 'shrink_in_days' => $shrinkIn,
1370 'winner_id' => $game['winner_id'],
1371 'draw' => !empty($game['draw']),
1372 'players' => $players,
1373 'events' => $events,
1374 'messages' => $messages,
1375 'legal' => $legal,
1376 'you' => $viewerId,
1377 'timezone' => self::TZ,
1378 'version' => (int) ($game['version'] ?? $game['event_seq'] ?? 0),
1379 'server_now' => $now,
1380 'ceasefire' => self::ceasefireInfo($game, $now),
1381 ];
1382 }
1383
1384 public static function lobbyView(array $game, string $viewerId): array
1385 {
1386 $players = [];
1387 foreach ($game['players'] as $p) {
1388 $players[] = [
1389 'id' => $p['id'],
1390 'name' => $p['name'],
1391 'avatar' => $p['avatar'],
1392 'color' => $p['color'],
1393 'is_you' => $p['id'] === $viewerId,
1394 'is_host' => $p['id'] === $game['host_id'],
1395 ];
1396 }
1397 return [
1398 'id' => $game['id'],
1399 'code' => $game['code'],
1400 'host_id' => $game['host_id'],
1401 'status' => $game['status'],
1402 'created_at' => $game['created_at'],
1403 'rules' => $game['rules'],
1404 'players' => $players,
1405 'can_start' => $game['status'] === 'lobby'
1406 && $game['host_id'] === $viewerId
1407 && count($game['players']) >= self::MIN_PLAYERS,
1408 'you' => $viewerId,
1409 'timezone' => self::TZ,
1410 ];
1411 }
1412
1413 public static function asBool(mixed $v): bool
1414 {
1415 if (is_bool($v)) {
1416 return $v;
1417 }
1418 if (is_int($v) || is_float($v)) {
1419 return $v != 0;
1420 }
1421 if (!is_string($v)) {
1422 return (bool) $v;
1423 }
1424 $s = strtolower(trim($v));
1425 return !in_array($s, ['', '0', 'false', 'off', 'no', 'null'], true);
1426 }
1427
1428 /**
1429 * Normalise "HH:MM"-"HH:MM" ranges. Invalid entries are dropped.
1430 * A range may wrap midnight (start > end). Zero-length (start==end) is dropped.
1431 *
1432 * @param mixed $raw
1433 * @return list<array{start:string,end:string}>
1434 */
1435 public static function normalizeRanges(mixed $raw): array
1436 {
1437 if (!is_array($raw)) {
1438 return [];
1439 }
1440 $out = [];
1441 $seen = [];
1442 foreach ($raw as $r) {
1443 if (!is_array($r)) {
1444 continue;
1445 }
1446 $start = self::parseHm($r['start'] ?? $r[0] ?? null);
1447 $end = self::parseHm($r['end'] ?? $r[1] ?? null);
1448 if ($start === null || $end === null || $start === $end) {
1449 continue;
1450 }
1451 $key = $start . '-' . $end;
1452 if (isset($seen[$key])) {
1453 continue;
1454 }
1455 $seen[$key] = true;
1456 $out[] = ['start' => $start, 'end' => $end];
1457 }
1458 usort($out, fn ($a, $b) => strcmp($a['start'], $b['start']));
1459 return array_slice($out, 0, 12);
1460 }
1461
1462 /** @return string|null "HH:MM" */
1463 public static function parseHm(mixed $v): ?string
1464 {
1465 if (is_int($v)) {
1466 if ($v < 0 || $v > 23 * 60 + 59) {
1467 return null;
1468 }
1469 return sprintf('%02d:%02d', intdiv($v, 60), $v % 60);
1470 }
1471 if (!is_string($v)) {
1472 return null;
1473 }
1474 $v = trim($v);
1475 if (!preg_match('/^(\d{1,2}):(\d{2})$/', $v, $m)) {
1476 return null;
1477 }
1478 $h = (int) $m[1];
1479 $min = (int) $m[2];
1480 if ($h > 23 || $min > 59) {
1481 return null;
1482 }
1483 return sprintf('%02d:%02d', $h, $min);
1484 }
1485
1486 public static function hmToMinutes(string $hm): int
1487 {
1488 [$h, $m] = array_map('intval', explode(':', $hm));
1489 return $h * 60 + $m;
1490 }
1491
1492 /**
1493 * Convert a local Europe/Amsterdam wall-clock on a calendar date to unix.
1494 * Uses midnight + hours/minutes so DST spring-forward skips and
1495 * fall-back uses PHP's first occurrence, then addition continues correctly.
1496 */
1497 public static function amsterdamWallclock(string $ymd, string $hm): int
1498 {
1499 $tz = new DateTimeZone(self::TZ);
1500 $dt = new DateTime($ymd . ' 00:00:00', $tz);
1501 $mins = self::hmToMinutes($hm);
1502 if ($mins > 0) {
1503 $dt->modify('+' . $mins . ' minutes');
1504 }
1505 return $dt->getTimestamp();
1506 }
1507
1508 /**
1509 * Merged cease-fire intervals as [start_ts, end_ts] covering yesterday
1510 * through two days ahead, so midnight wraps and DST are exact.
1511 *
1512 * @return list<array{0:int,1:int}>
1513 */
1514 public static function ceasefireIntervals(array $ranges, int $now): array
1515 {
1516 if ($ranges === []) {
1517 return [];
1518 }
1519 $tz = new DateTimeZone(self::TZ);
1520 $anchor = (new DateTime('@' . $now))->setTimezone($tz);
1521 $intervals = [];
1522 for ($d = -1; $d <= 3; $d++) {
1523 $day = (clone $anchor)->modify(($d >= 0 ? '+' : '') . $d . ' day');
1524 $ymd = $day->format('Y-m-d');
1525 $next = (clone $day)->modify('+1 day')->format('Y-m-d');
1526 foreach ($ranges as $r) {
1527 $startM = self::hmToMinutes($r['start']);
1528 $endM = self::hmToMinutes($r['end']);
1529 $startTs = self::amsterdamWallclock($ymd, $r['start']);
1530 if ($endM > $startM) {
1531 $endTs = self::amsterdamWallclock($ymd, $r['end']);
1532 } else {
1533 // Wraps midnight: ends on the next calendar day.
1534 $endTs = self::amsterdamWallclock($next, $r['end']);
1535 }
1536 if ($endTs > $startTs) {
1537 $intervals[] = [$startTs, $endTs];
1538 }
1539 }
1540 }
1541 if ($intervals === []) {
1542 return [];
1543 }
1544 usort($intervals, fn ($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);
1545 $merged = [];
1546 foreach ($intervals as $iv) {
1547 if ($merged === [] || $iv[0] > $merged[count($merged) - 1][1]) {
1548 $merged[] = $iv;
1549 } else {
1550 $merged[count($merged) - 1][1] = max($merged[count($merged) - 1][1], $iv[1]);
1551 }
1552 }
1553 return $merged;
1554 }
1555
1556 public static function ceasefireActive(array $game, int $now): bool
1557 {
1558 $info = self::ceasefireInfo($game, $now);
1559 return $info !== null && !empty($info['active']);
1560 }
1561
1562 /**
1563 * @return array{enabled:bool,active:bool,until:?int,seconds:int}|null
1564 * null when the rule is off or there are no ranges.
1565 */
1566 public static function ceasefireInfo(array $game, int $now): ?array
1567 {
1568 $rules = $game['rules'] ?? [];
1569 if (empty($rules['ceasefire'])) {
1570 return null;
1571 }
1572 $ranges = self::normalizeRanges($rules['ceasefire_ranges'] ?? []);
1573 if ($ranges === []) {
1574 return null;
1575 }
1576 $intervals = self::ceasefireIntervals($ranges, $now);
1577 $active = false;
1578 $until = null;
1579 foreach ($intervals as $iv) {
1580 if ($now >= $iv[0] && $now < $iv[1]) {
1581 $active = true;
1582 $until = $iv[1];
1583 break;
1584 }
1585 if ($iv[0] > $now && ($until === null || $iv[0] < $until)) {
1586 $until = $iv[0];
1587 }
1588 }
1589 $seconds = $until !== null ? max(0, $until - $now) : 0;
1590 return [
1591 'enabled' => true,
1592 'active' => $active,
1593 'until' => $until,
1594 'seconds' => $seconds,
1595 'ranges' => $ranges,
1596 ];
1597 }
1598
1599 public static function generateCode(): string
1600 {
1601 // Crockford-ish, no 0/O/I/1/L.
1602 $alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
1603 $len = strlen($alphabet);
1604 $code = '';
1605 for ($i = 0; $i < self::CODE_LEN; $i++) {
1606 $code .= $alphabet[random_int(0, $len - 1)];
1607 }
1608 return $code;
1609 }
1610
1611 public static function generateId(): string
1612 {
1613 return bin2hex(random_bytes(12));
1614 }
1615}