BlueGit

projects-timfalken-com allianties

Files

allianties / server / lib / Engine.php

Engine.php

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