BlueGit

projects-timfalken-com allianties

Files

allianties / server / lib / Engine.php

Engine.php

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