BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / SynhexSim.php

SynhexSim.php

feat: scaffold Synhex hex tactics on the Microchess lobby shell
timfa project_86226080_bot_b6e0858ac0a12dc6d49a8d25b3b0be9b · pushed by timfa · 2 months ago
24f20754 History
SynhexSim.php 19.0 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4/** Frozen-Synapse-style simultaneous act simulation. */
5final class SynhexSim
6{
7 /**
8 * Run one locked act. Mutates/returns a new state with timeline, updated units, fog, leftover paths.
9 */
10 public static function runAct(array $s, array $cfg): array
11 {
12 $tickMs = max(1, (int)$cfg['sim_tick_ms']);
13 $duration = max($tickMs, (int)$cfg['act_duration_ms']);
14 $ticks = intdiv($duration, $tickMs);
15 $walk = max(1, (int)$cfg['walk_range']);
16 $stepTicks = max(1, intdiv($ticks, $walk));
17 $walls = array_fill_keys($s['walls'], true);
18 $rng = new SynhexRng(((int)$s['seed'] ^ (($s['act'] + 1) * 10007)) & 0x7fffffff);
19
20 $units = [];
21 foreach ($s['units'] as $u) {
22 $units[$u['id']] = $u + [
23 'alive' => $u['alive'] ?? true,
24 'remaining' => $u['remaining'] ?? [],
25 'thisMoved' => false,
26 'thisTargets' => [],
27 'lastShotAt' => -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'],
28 'deathTick' => $u['deathTick'] ?? null,
29 ];
30 }
31
32 foreach (['w', 'b'] as $team) {
33 $plan = $s['plans'][$team]['units'] ?? [];
34 if (!is_array($plan)) {
35 continue;
36 }
37 foreach ($plan as $id => $spec) {
38 if (!isset($units[$id]) || $units[$id]['team'] !== $team || !$units[$id]['alive']) {
39 continue;
40 }
41 $path = self::normalizePath($spec['path'] ?? []);
42 $units[$id]['remaining'] = $path;
43 if ($path === [] && isset($spec['facing']) && is_int($spec['facing'])) {
44 $units[$id]['facing'] = ($spec['facing'] % 6 + 6) % 6;
45 }
46 }
47 }
48
49 return self::simulate($s, $cfg, $units, $walls, $rng, $tickMs, $duration, $ticks, $walk, $stepTicks);
50 }
51
52 private static function simulate(array $s, array $cfg, array $units, array $walls, SynhexRng $rng, int $tickMs, int $duration, int $ticks, int $walk, int $stepTicks): array
53 {
54 // Reset movement bookkeeping from the draft above.
55 foreach ($units as $id => &$u) {
56 $u['stepsTaken'] = 0;
57 $u['thisMoved'] = false;
58 $u['thisTargets'] = [];
59 $u['lastShotAt'] = -(int)$cfg['weapon_'.($u['weapon'] ?? 'smg').'_rof_ms'];
60 }
61 unset($u);
62
63 $shots = [];
64 $kills = [];
65 $visibleEver = ['w' => [], 'b' => []];
66 $firedTicks = [];
67 $snapshots = [];
68 $deathTick = ['w' => null, 'b' => null];
69
70 $recordSnap = static function (int $t) use (&$snapshots, &$units): void {
71 $snapshots[] = ['t' => $t, 'units' => self::publicUnits($units)];
72 };
73 $recordSnap(0);
74
75 for ($t = 0; $t <= $ticks; $t++) {
76 $steppedIds = [];
77 if ($t > 0 && $t % $stepTicks === 0) {
78 foreach ($units as $id => &$u) {
79 if (!$u['alive'] || $u['stepsTaken'] >= $walk || !$u['remaining']) {
80 continue;
81 }
82 $next = $u['remaining'][0];
83 $nq = (int)$next['q'];
84 $nr = (int)$next['r'];
85 if (isset($walls[HexGrid::key($nq, $nr)]) || !HexGrid::inBounds($nq, $nr, $s['grid']['cols'], $s['grid']['rows'])) {
86 $u['remaining'] = [];
87 continue;
88 }
89 if (HexGrid::distance($u['q'], $u['r'], $nq, $nr) !== 1) {
90 $u['remaining'] = [];
91 continue;
92 }
93 array_shift($u['remaining']);
94 $u['q'] = $nq;
95 $u['r'] = $nr;
96 $u['thisMoved'] = true;
97 $u['stepsTaken']++;
98 $steppedIds[$id] = true;
99 if (array_key_exists('facing', $next) && $next['facing'] !== null && $next['facing'] !== '') {
100 $u['facing'] = ((int)$next['facing'] % 6 + 6) % 6;
101 }
102 }
103 unset($u);
104 }
105
106 $now = $t * $tickMs;
107 $intended = self::intendedShots($units, $walls, $cfg, $now);
108 $focus = [];
109 foreach ($intended as $id => $target) {
110 $focus[$target] = ($focus[$target] ?? 0) + 1;
111 }
112 $aimedAt = array_flip($intended);
113
114 foreach ($intended as $id => $targetId) {
115 $shooter = $units[$id];
116 $weapon = $shooter['weapon'];
117 $rof = (int)$cfg['weapon_'.$weapon.'_rof_ms'];
118 $pellets = $weapon === 'shotgun' ? (int)$cfg['weapon_shotgun_pellets'] : 1;
119 $acc = self::accuracy($cfg, $units, $id, $targetId, $intended, $focus, $aimedAt, $walls, isset($steppedIds[$id]), isset($steppedIds[$targetId]));
120 $units[$id]['lastShotAt'] = $now;
121 $units[$id]['thisTargets'][$targetId] = true;
122 $firedTicks[$id] = $t;
123 $aims = self::pelletAims($shooter, $units[$targetId], $pellets, (int)$cfg['weapon_shotgun_spread']);
124 foreach ($aims as $aim) {
125 $victim = self::rayVictimToward($units, $walls, $shooter, $targetId, $aim[0], $aim[1], (int)$cfg['shot_range'], $cfg['friendly_fire']);
126 $hit = false;
127 if ($victim !== null) {
128 $chance = $victim === $targetId ? $acc : (int)$cfg['base_accuracy'];
129 $hit = $rng->chance($chance);
130 if ($hit && $units[$victim]['alive']) {
131 $units[$victim]['alive'] = false;
132 $units[$victim]['deathTick'] = $t;
133 if (($units[$victim]['role'] ?? '') === 'vip' && $deathTick[$units[$victim]['team']] === null) {
134 $deathTick[$units[$victim]['team']] = $t;
135 }
136 $kills[] = ['t' => $now, 'id' => $victim, 'by' => $id, 'weapon' => $weapon];
137 }
138 }
139 $shots[] = [
140 't' => $now,
141 'id' => $id,
142 'target' => $targetId,
143 'victim' => $victim,
144 'hit' => $hit,
145 'weapon' => $weapon,
146 'accuracy' => $acc,
147 'aim' => ['q' => $aim[0], 'r' => $aim[1]],
148 ];
149 }
150 }
151
152 $seen = self::visibility($units, $walls, $cfg, $firedTicks, $t);
153 foreach (['w', 'b'] as $team) {
154 foreach ($seen[$team] as $oid) {
155 $visibleEver[$team][$oid] = true;
156 }
157 }
158
159 if ($t === 0 || $t === $ticks || $steppedIds) {
160 $recordSnap($now);
161 }
162 }
163
164 $endUnits = [];
165 foreach ($units as $u) {
166 $prevTargets = array_keys($u['thisTargets']);
167 $endUnits[] = [
168 'id' => $u['id'],
169 'team' => $u['team'],
170 'role' => $u['role'],
171 'weapon' => $u['weapon'],
172 'q' => $u['q'],
173 'r' => $u['r'],
174 'facing' => $u['facing'],
175 'alive' => $u['alive'],
176 'remaining' => array_values($u['remaining']),
177 'stationaryPrevAct' => !$u['thisMoved'],
178 'shotTargetPrevAct' => count($prevTargets) === 1 ? $prevTargets[0] : (count($prevTargets) > 1 ? '*' : null),
179 'deathTick' => $u['deathTick'],
180 ];
181 }
182
183 $lastKnown = $s['lastKnown'] ?? ['w' => [], 'b' => []];
184 foreach (['w', 'b'] as $team) {
185 foreach ($endUnits as $u) {
186 if ($u['team'] === $team) {
187 continue;
188 }
189 $seen = isset($visibleEver[$team][$u['id']]) || isset($firedTicks[$u['id']]);
190 if ($seen || ($s['act'] === 0 && !empty($cfg['see_enemies_at_match_start']))) {
191 $lastKnown[$team][$u['id']] = ['q' => $u['q'], 'r' => $u['r'], 'facing' => $u['facing'], 'alive' => $u['alive']];
192 }
193 }
194 }
195
196 $winner = null;
197 $reason = null;
198 if ($deathTick['w'] !== null && $deathTick['b'] !== null) {
199 if ($deathTick['w'] === $deathTick['b']) {
200 $reason = 'Both VIPs fell';
201 } else {
202 $winner = $deathTick['w'] < $deathTick['b'] ? 'b' : 'w';
203 $reason = 'VIP eliminated';
204 }
205 } elseif ($deathTick['w'] !== null) {
206 $winner = 'b';
207 $reason = 'VIP eliminated';
208 } elseif ($deathTick['b'] !== null) {
209 $winner = 'w';
210 $reason = 'VIP eliminated';
211 }
212
213 $timeline = [
214 'act' => $s['act'] + 1,
215 'durationMs' => $duration,
216 'tickMs' => $tickMs,
217 'snapshots' => self::dedupeSnaps($snapshots),
218 'shots' => $shots,
219 'kills' => $kills,
220 'endUnits' => $endUnits,
221 'winner' => $winner,
222 'reason' => $reason,
223 ];
224
225 $s['units'] = $endUnits;
226 $s['act'] = $s['act'] + 1;
227 $s['phase'] = 'playback';
228 $s['committed'] = ['w' => false, 'b' => false];
229 $s['acked'] = ['w' => false, 'b' => false];
230 $s['plans'] = ['w' => null, 'b' => null];
231 $s['drafts'] = ['w' => null, 'b' => null];
232 $s['timeline'] = $timeline;
233 $s['history'][] = $timeline;
234 $s['lastKnown'] = $lastKnown;
235 $s['result'] = $winner || $reason ? ['winner' => $winner, 'reason' => $reason] : null;
236 return $s;
237 }
238
239 private static function dedupeSnaps(array $snaps): array
240 {
241 $out = [];
242 $lastT = -1;
243 foreach ($snaps as $snap) {
244 if ($snap['t'] === $lastT) {
245 $out[count($out) - 1] = $snap;
246 } else {
247 $out[] = $snap;
248 $lastT = $snap['t'];
249 }
250 }
251 return $out;
252 }
253
254 private static function publicUnits(array $units): array
255 {
256 $out = [];
257 foreach ($units as $u) {
258 $out[] = [
259 'id' => $u['id'],
260 'team' => $u['team'],
261 'role' => $u['role'],
262 'weapon' => $u['weapon'],
263 'q' => $u['q'],
264 'r' => $u['r'],
265 'facing' => $u['facing'],
266 'alive' => $u['alive'],
267 ];
268 }
269 return $out;
270 }
271
272 private static function normalizePath(mixed $path): array
273 {
274 if (!is_array($path)) {
275 return [];
276 }
277 $out = [];
278 foreach ($path as $step) {
279 if (!is_array($step) || !isset($step['q'], $step['r'])) {
280 continue;
281 }
282 $item = ['q' => (int)$step['q'], 'r' => (int)$step['r']];
283 if (array_key_exists('facing', $step) && $step['facing'] !== null && $step['facing'] !== '') {
284 $item['facing'] = ((int)$step['facing'] % 6 + 6) % 6;
285 }
286 $out[] = $item;
287 }
288 return $out;
289 }
290
291 /**
292 * @return array<string,string> shooter id => target id
293 */
294 private static function intendedShots(array $units, array $walls, array $cfg, int $now): array
295 {
296 $out = [];
297 foreach ($units as $id => $u) {
298 if (!$u['alive']) {
299 continue;
300 }
301 $rof = (int)$cfg['weapon_'.$u['weapon'].'_rof_ms'];
302 if ($now - (int)$u['lastShotAt'] < $rof) {
303 continue;
304 }
305 $best = null;
306 $bestD = PHP_INT_MAX;
307 foreach ($units as $oid => $o) {
308 if (!$o['alive'] || $o['team'] === $u['team']) {
309 continue;
310 }
311 $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
312 if ($d === 0 || $d > (int)$cfg['shot_range']) {
313 continue;
314 }
315 if (!HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])) {
316 continue;
317 }
318 if (!HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls)) {
319 continue;
320 }
321 if ($d < $bestD) {
322 $bestD = $d;
323 $best = $oid;
324 }
325 }
326 if ($best !== null) {
327 $out[$id] = $best;
328 }
329 }
330 ksort($out);
331 return $out;
332 }
333
334 private static function accuracy(array $cfg, array $units, string $id, string $targetId, array $intended, array $focus, array $aimedAt, array $walls, bool $shooterStepped, bool $targetStepped): int
335 {
336 $s = $units[$id];
337 $t = $units[$targetId];
338 $acc = (int)$cfg['base_accuracy'];
339 if (!$shooterStepped) {
340 $acc += (int)$cfg['accuracy_bonus_shooter_stationary'];
341 }
342 if (HexGrid::onFacingLine($s['q'], $s['r'], (int)$s['facing'], $t['q'], $t['r'], (int)$cfg['shot_range'])) {
343 $acc += (int)$cfg['accuracy_bonus_target_forward'];
344 }
345 $dist = HexGrid::distance($s['q'], $s['r'], $t['q'], $t['r']);
346 if ($dist <= (int)$cfg['close_range_hexes']) {
347 $acc += (int)$cfg['accuracy_bonus_target_close'];
348 if ($s['weapon'] === 'shotgun') {
349 $acc += (int)$cfg['accuracy_bonus_shotgun_close_extra'];
350 }
351 }
352 if (($intended[$targetId] ?? null) !== $id) {
353 $acc += (int)$cfg['accuracy_bonus_target_not_shooting_this'];
354 }
355 if (!empty($s['stationaryPrevAct'])) {
356 $acc += (int)$cfg['accuracy_bonus_still_previous_act'];
357 }
358 $prev = $s['shotTargetPrevAct'] ?? null;
359 if ($prev === null || $prev === $targetId) {
360 $acc += (int)$cfg['accuracy_bonus_same_or_no_target_previous_act'];
361 }
362 if (($focus[$targetId] ?? 0) > 1) {
363 $acc += (int)$cfg['accuracy_bonus_friendly_focus_fire'];
364 }
365 if (self::noCoverWall($s, $t, $walls)) {
366 $acc += (int)$cfg['accuracy_bonus_target_no_cover_wall'];
367 }
368 if (!$targetStepped) {
369 $acc += (int)$cfg['accuracy_bonus_target_stationary'];
370 }
371 if (!isset($aimedAt[$id])) {
372 $acc += (int)$cfg['accuracy_bonus_nobody_shooting_at_shooter'];
373 }
374 return max(0, min((int)$cfg['accuracy_cap'], $acc));
375 }
376
377 private static function noCoverWall(array $shooter, array $target, array $walls): bool
378 {
379 $tq = $target['q'];
380 $tr = $target['r'];
381 $cover = false;
382 foreach (HexGrid::neighbors($tq, $tr) as [$q, $r]) {
383 if (!isset($walls[HexGrid::key($q, $r)])) {
384 continue;
385 }
386 if (HexGrid::distance($shooter['q'], $shooter['r'], $q, $r) < HexGrid::distance($shooter['q'], $shooter['r'], $tq, $tr)) {
387 $cover = true;
388 break;
389 }
390 }
391 return !$cover;
392 }
393
394 /** Aim points for a volley: the target, plus nearby hexes for shotgun pellets. */
395 private static function pelletAims(array $shooter, array $target, int $pellets, int $spread): array
396 {
397 $aims = [[$target['q'], $target['r']]];
398 if ($pellets <= 1) {
399 return $aims;
400 }
401 $neighbors = HexGrid::neighbors($target['q'], $target['r']);
402 $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $target['q'], $target['r']);
403 $order = [];
404 foreach ($neighbors as $i => $hex) {
405 $away = HexGrid::distance($shooter['q'], $shooter['r'], $hex[0], $hex[1]);
406 $order[] = [$away, $i, $hex];
407 }
408 usort($order, static fn($a, $b) => $a[0] <=> $b[0] ?: $a[1] <=> $b[1]);
409 foreach ($order as [, , $hex]) {
410 if (count($aims) >= $pellets) {
411 break;
412 }
413 if (HexGrid::distance($hex[0], $hex[1], $target['q'], $target['r']) <= max(1, $spread)) {
414 $aims[] = $hex;
415 }
416 }
417 while (count($aims) < $pellets) {
418 $aims[] = HexGrid::neighbor($target['q'], $target['r'], ($dir + count($aims)) % 6);
419 }
420 return array_slice($aims, 0, $pellets);
421 }
422
423 private static function rayVictimToward(array $units, array $walls, array $shooter, string $intended, int $aq, int $ar, int $range, bool $friendlyFire): ?string
424 {
425 $occ = [];
426 foreach ($units as $u) {
427 if ($u['alive']) {
428 $occ[HexGrid::key($u['q'], $u['r'])][] = $u['id'];
429 }
430 }
431 $line = HexGrid::line($shooter['q'], $shooter['r'], $aq, $ar);
432 $dir = HexGrid::dirToward($shooter['q'], $shooter['r'], $aq, $ar);
433 while (count($line) < $range + 1) {
434 $last = $line[count($line) - 1];
435 $line[] = HexGrid::neighbor($last[0], $last[1], $dir);
436 }
437 foreach ($line as $i => [$q, $r]) {
438 if ($i === 0) {
439 continue;
440 }
441 $k = HexGrid::key($q, $r);
442 if (isset($walls[$k])) {
443 return null;
444 }
445 if (!empty($occ[$k])) {
446 foreach ($occ[$k] as $id) {
447 if ($id === $shooter['id']) {
448 continue;
449 }
450 if (!$friendlyFire && $units[$id]['team'] === $shooter['team'] && $id !== $intended) {
451 continue;
452 }
453 return $id;
454 }
455 }
456 }
457 return null;
458 }
459
460 /**
461 * @return array{w: list<string>, b: list<string>}
462 */
463 public static function visibility(array $units, array $walls, array $cfg, array $firedTicks, int $t): array
464 {
465 $seen = ['w' => [], 'b' => []];
466 foreach ($units as $u) {
467 if (!$u['alive']) {
468 continue;
469 }
470 foreach ($units as $o) {
471 if ($o['team'] === $u['team']) {
472 $seen[$u['team']][] = $o['id'];
473 continue;
474 }
475 if (!$o['alive']) {
476 continue;
477 }
478 $d = HexGrid::distance($u['q'], $u['r'], $o['q'], $o['r']);
479 $inVision = $d > 0 && $d <= (int)$cfg['vision_range']
480 && HexGrid::inCone($u['q'], $u['r'], (int)$u['facing'], $o['q'], $o['r'], (float)$cfg['vision_cone_half_deg'])
481 && HexGrid::los($u['q'], $u['r'], $o['q'], $o['r'], $walls);
482 $firing = !empty($cfg['see_enemies_when_firing']) && isset($firedTicks[$o['id']]) && $firedTicks[$o['id']] === $t;
483 if ($inVision || $firing) {
484 $seen[$u['team']][] = $o['id'];
485 }
486 }
487 }
488 foreach (['w', 'b'] as $team) {
489 $seen[$team] = array_values(array_unique($seen[$team]));
490 }
491 return $seen;
492 }
493}