BlueGit

projects-timfalken-com allianties

Files

allianties / server / lib / Engine.php

Engine.php

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