From 8bf715251247311199bebf476103cb7d9b708a0b Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Wed, 7 Oct 2026 08:44:37 +0200 Subject: [PATCH] =?UTF-8?q?ChimeraBot=5Fgarage:=20M7=20twin=20gun=20?= =?UTF-8?q?=E2=80=94=20flight-horizon=20aiming,=20spread-based=20power,=20?= =?UTF-8?q?aim-bias=20corrector,=20Dodger=20archetype?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ChimeraBot_garage/benchmarks/m7_g8.md | 25 ++ ChimeraBot_garage/benchmarks/m7_g8_live.md | 19 + ChimeraBot_garage/src/ChimeraBot.nim | 37 ++ ChimeraBot_garage/src/ChimeraBot.nimble | 2 + .../src/ChimeraBot/chimera/aimer.nim | 335 ++++++++++++++++++ .../src/ChimeraBot/chimera/observer.nim | 46 ++- .../tests/archetypes/Dodger/Dodger.cmd | 3 + .../tests/archetypes/Dodger/Dodger.json | 9 + .../tests/archetypes/Dodger/Dodger.nim | 65 ++++ .../tests/archetypes/Dodger/Dodger.sh | 13 + .../tests/archetypes/Dodger/dodger_spec.nim | 74 ++++ ChimeraBot_garage/tests/bench_g8.nim | 243 +++++++++++++ ChimeraBot_garage/tests/bench_g8_live.nim | 169 +++++++++ ChimeraBot_garage/tests/config.nims | 1 + ChimeraBot_garage/tests/test_aimer.nim | 149 ++++++++ ChimeraBot_garage/tests/test_dodger.nim | 85 +++++ 16 files changed, 1274 insertions(+), 1 deletion(-) create mode 100644 ChimeraBot_garage/benchmarks/m7_g8.md create mode 100644 ChimeraBot_garage/benchmarks/m7_g8_live.md create mode 100644 ChimeraBot_garage/src/ChimeraBot/chimera/aimer.nim create mode 100644 ChimeraBot_garage/tests/archetypes/Dodger/Dodger.cmd create mode 100644 ChimeraBot_garage/tests/archetypes/Dodger/Dodger.json create mode 100644 ChimeraBot_garage/tests/archetypes/Dodger/Dodger.nim create mode 100755 ChimeraBot_garage/tests/archetypes/Dodger/Dodger.sh create mode 100644 ChimeraBot_garage/tests/archetypes/Dodger/dodger_spec.nim create mode 100644 ChimeraBot_garage/tests/bench_g8.nim create mode 100644 ChimeraBot_garage/tests/bench_g8_live.nim create mode 100644 ChimeraBot_garage/tests/test_aimer.nim create mode 100644 ChimeraBot_garage/tests/test_dodger.nim diff --git a/ChimeraBot_garage/benchmarks/m7_g8.md b/ChimeraBot_garage/benchmarks/m7_g8.md new file mode 100644 index 0000000..bf6e8cf --- /dev/null +++ b/ChimeraBot_garage/benchmarks/m7_g8.md @@ -0,0 +1,25 @@ +# G8 offline hit-rate bench (M7, twin gun) + +Replayed archived trajectories (`/tmp/chimera_g4_run`) + a synthesized Dodger; hit = bullet passes within 20. units of the realized enemy position. Aim slew/cadence abstracted. Generated by `tests/bench_g8.nim`. + +| opponent | twin % | ELM % | head-on % | shots | +|---|---:|---:|---:|---:| +| Corners | 49.3 | 59.6 | 52.2 | 339 | +| Crazy | 50.3 | 31.5 | 15.0 | 1042 | +| Fire | 50.7 | 41.4 | 45.9 | 440 | +| RamFire | 90.5 | 92.7 | 89.9 | 328 | +| SpinBot | 88.3 | 20.1 | 20.1 | 715 | +| TrackFire | 84.2 | 87.3 | 87.3 | 221 | +| VelociBot | 38.7 | 23.3 | 28.4 | 786 | +| Walls | 43.8 | 22.1 | 1.8 | 825 | +| Dodger | 85.5 | 11.4 | 72.7 | 220 | + +**G8 offline bar: twin >= ELM on >= 6/9 opponents AND twin >= head-on on the movers.** Result: twin >= ELM on 6/9; twin >= head-on on 5/5 movers. **Verdict: PASS.** + +## Method / caveats + +* `TWIN` = `chimera/aimer.nim`: iterated flight time + `h = dist/(20-3*power)`, horizon-bucketed predictor Hedge (mixture/residual/persistence), trained ONLINE per record (one aimer, score-then-aim each sampled tick), spread-selected power. +* `ELM` = the ELM gun's **base** geometric intercept from the observed velocity (the learned correction is gated and small, and the online ELM state cannot be replayed offline). This is a proxy for the full ELM gun — a documented deviation. +* Power monotonicity: `selectPowerFromSpreads` returns the largest power whose required spread fits the enemy-silhouette tolerance `2*atan2(18, dist)`; the choice is non-increasing in spread (`test_aimer.nim`, aimer 4). +* The synthesized Dodger fires a wave every 12 ticks; a real battle would add shooter motion. Live results (`m7_g8_live.md`) are the reality check. diff --git a/ChimeraBot_garage/benchmarks/m7_g8_live.md b/ChimeraBot_garage/benchmarks/m7_g8_live.md new file mode 100644 index 0000000..397092f --- /dev/null +++ b/ChimeraBot_garage/benchmarks/m7_g8_live.md @@ -0,0 +1,19 @@ +# G8 live bench (M7 twin gun) + +Three arms from the SAME tree: inert (`-d:chimeraInert`), elm (`-d:chimeraNoTwinGun`), twin (default). 5 rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`. + +| opponent | elm W% | elm margin | twin W% | twin margin | inert W% | inert margin | +|---|---:|---:|---:|---:|---:|---:| +| Corners | 100.0 | 2538.0 | 100.0 | 2354.0 | 100.0 | 2477.0 | +| Crazy | 100.0 | 1779.0 | 100.0 | 2240.0 | 100.0 | 1746.0 | +| Fire | 100.0 | 2571.0 | 100.0 | 2494.0 | 100.0 | 2588.0 | +| RamFire | 100.0 | 2549.0 | 100.0 | 2545.0 | 100.0 | 2665.0 | +| SpinBot | 100.0 | 2085.0 | 100.0 | 1635.0 | 100.0 | 1086.0 | +| TrackFire | 100.0 | 2334.0 | 100.0 | 2337.0 | 100.0 | 2371.0 | +| VelociBot | 100.0 | 2100.0 | 100.0 | 1842.0 | 100.0 | 2141.0 | +| Walls | 100.0 | 1895.0 | 100.0 | 1788.0 | 100.0 | 1697.0 | +| Dodger | 100.0 | 2665.0 | 100.0 | 2662.0 | 100.0 | 2653.0 | + +**Totals:** elm 100.0% (margin 20516.0), twin 100.0% (margin 19897.0), inert 100.0% (margin 19424.0). + +**G7 no-regression (twin >= inert win-rate on every opponent): PASS.** diff --git a/ChimeraBot_garage/src/ChimeraBot.nim b/ChimeraBot_garage/src/ChimeraBot.nim index ceec511..5441154 100644 --- a/ChimeraBot_garage/src/ChimeraBot.nim +++ b/ChimeraBot_garage/src/ChimeraBot.nim @@ -37,6 +37,7 @@ import ChimeraBot/chimera/dsl import ChimeraBot/chimera/probes import ChimeraBot/chimera/physics import ChimeraBot/chimera/influence +import ChimeraBot/chimera/aimer when defined(chimeraDebug): import ChimeraBot/chimera/debugdraw @@ -64,6 +65,9 @@ const UseElm* = not defined(baselineGun) # `-d:elmPrior` = weak pooled prior (pretrained beta scaled by 0.1). const OnlinePriorScale* = (when defined(elmPrior): 0.1 else: 0.0) +const TwinGunMinInfluence = 0.5 ## M7/G8: fused influence above which the + ## twin gun REPLACES the ELM gun that tick +const TwinGunEnergyFloor = 6.0 ## do not spend energy below this const FireSlopDeg = 1.0'f64 ## fire inside this much gun error, in ## DEGREES (the API's unit). ## @@ -213,6 +217,31 @@ method buildWorldState(bot: ChimeraBot): WorldState = arenaWidth: getArenaWidth().float, arenaHeight: getArenaHeight().float, tick: bot.tick, enemies: bot.enemies) +## M7 twin gun (G8): flight-horizon aiming, gated by the fusion influence and +## removed entirely by `-d:chimeraNoTwinGun`. Returns true when it handled this +## tick, so the ELM gun is skipped; false falls back to the ELM path unchanged. +proc computeTwinGun(bot: ChimeraBot, influence: float64): bool = + let aim = bot.observer.twinAim(getX(), getY(), getArenaWidth().float, + getArenaHeight().float, FirePower) + if not aim.active: return false + bot.observer.setGunTelemetry(radToDeg(aim.aimBearing), aim.power, + radToDeg(aim.spread), influence, true) + let err = gunAimErrorDeg(aim.aimBearing, getGunDirection()) + # Fire window: half the silhouette width (the aim point is the CENTER of the + # target, so half-width is the lateral slop that still clips it), floored at + # the tight ELM slop. `aim.tolerance` is the full width per the G8 formula. + let slack = max(FireSlopDeg, radToDeg(aim.tolerance) * 0.5) + let cadenceOk = bot.tick - bot.observer.twinGunLastFire() >= cooldownTicks(aim.spread) + if abs(err) <= slack and getGunHeat() == 0.0 and cadenceOk and + getEnergy() >= TwinGunEnergyFloor: + setGunTurnRate(0.0) + discard setFire(aim.power) + bot.observer.noteTwinShot(aim, bot.tick) + inc bot.shotsFired + else: + setGunTurnRate(clamp(err, -20.0, 20.0)) + true + ## The gun tick: aim, and fire when the gun is actually on the aim point. ## ## Standard Tank Royale gun handling, nothing clever — the cleverness (if any) @@ -222,6 +251,14 @@ method buildWorldState(bot: ChimeraBot): WorldState = proc computeGun(bot: ChimeraBot) = if bot.gun.online: bot.gun.drainPending(bot.tick) # label any shot whose flight time elapsed + # M7 twin gun: when the fused influence clears the gate, flight-horizon aiming + # owns this tick's gun. `-d:chimeraNoTwinGun` compiles this block out, leaving + # the ELM path below byte-identical to the pre-M7 build. + when not NoTwinGun: + if bot.observer.hasCurrent: + let infl = bot.observer.fusedInfluence() + if infl > TwinGunMinInfluence and bot.computeTwinGun(infl): + return let belief = bot.buildBelief(FirePower) let feat = buildFeatures(belief) let aim = bot.gun.predictAim(belief, FirePower, UseElm) diff --git a/ChimeraBot_garage/src/ChimeraBot.nimble b/ChimeraBot_garage/src/ChimeraBot.nimble index 542b940..6a45154 100644 --- a/ChimeraBot_garage/src/ChimeraBot.nimble +++ b/ChimeraBot_garage/src/ChimeraBot.nimble @@ -266,6 +266,8 @@ task test, "Run unit tests": exec "nim c -r --hints:off ../tests/test_fusion.nim" exec "nim c -r --hints:off ../tests/test_influence.nim" exec "nim c -r --hints:off ../tests/test_identifiability.nim" + exec "nim c -r --hints:off ../tests/test_aimer.nim" + exec "nim c -r --hints:off ../tests/test_dodger.nim" # Debug overlay: compiled WITH -d:chimeraDebug so the drawing path is the real # one; the test asserts the command intent is identical with/without it. exec "nim c -r --hints:off -d:chimeraDebug ../tests/test_debugdraw.nim" diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/aimer.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/aimer.nim new file mode 100644 index 0000000..3a9bf34 --- /dev/null +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/aimer.nim @@ -0,0 +1,335 @@ +## CHIMERA twin gun — flight-horizon aiming (docs/chimera-spec.md, G8 / M7). +## +## The ELM gun (`modules/ELM/elm_gun.nim`) leads the enemy by one geometric +## dead-reckon with a learned correction trained on a 5-tick lookahead. A bullet +## at power `p` flies `dist / (20 - 3p)` ticks — 15 to 45 ticks across the legal +## power range — so on a dodging opponent the aim must target the enemy's +## **bullet-arrival position**, not a 5-tick extrapolation. That is what this +## module adds, in three pieces: +## +## 1. **Horizon-bucketed Hedge** over three predictors — the posterior-mixture +## twinsim rollout, the linear-residual trajectory and constant-velocity +## persistence. Buckets are `1-7 / 8-17 / 18-35 / 36-70` ticks. Each bucket's +## weights are updated online from the realized enemy position at the horizon +## that was actually used; every bucket starts uniform (neutral). This is the +## G8 extension of the M6 fusion (`fusion.nim`), which only knew `k = 5`. +## 2. **Iterated flight time** — `h = flightTime(dist, power)` is folded onto +## itself at most 3 times (`h -> fusedPositionAt(h) -> dist -> h`), with the +## result clipped to the arena and re-iterated when clipping moved it. +## 3. **Spread-based power selection** — the top-`k` (`k <= 4`) kernels by +## posterior are rolled to the flight horizon; the max pairwise angular spread +## of their predicted positions, seen from OUR position, must fit inside the +## enemy-silhouette angular tolerance `2*atan2(botRadius, dist)`. The largest +## power that fits is chosen. Plus an online **aim-bias corrector**: a +## distance-band x enemy-speed-band histogram of post-shot angular misses, +## applied as an angular offset, deterministic and persisted per match. +## +## Nothing here issues commands: `ChimeraBot.computeGun` reads `TwinAim` and +## drives the gun. The whole path is removed by `-d:chimeraNoTwinGun`, which +## restores the exact current ELM gun behaviour. + +import std/[math, algorithm] +import ./physics, ./dsl, ./twinsim, ./residual, ./hedge, ./fusion + +const + NoTwinGun* = defined(chimeraNoTwinGun) + ## Kill switch: with this defined `ChimeraBot.computeGun` never calls the + ## twin gun and the ELM path is byte-identical to the pre-M7 build. + + BotRadius* = 18.0 + ## Enemy silhouette half-width used by the angular-tolerance formula. The + ## spec does not define a value; 18 units is the Tank Royale bot radius + ## convention used elsewhere in the repo. + + FirePowers* = [3.0, 2.5, 2.0, 1.5, 1.0, 0.5, 0.1] + ## Candidate powers, DESCENDING. `selectPowerFromSpreads` searches this order + ## so the chosen power is monotone non-increasing in the required spread. + + NBuckets* = 4 + BucketLo* = [1, 8, 18, 36] + BucketHi* = [7, 17, 35, 70] + MaxIter* = 3 ## flight-time/aim-point refinement iterations + MinorStep* = 1e-3 ## |h' - h| below this means converged (ticks) + + TinySpreadDeg* = 0.5 ## spread below this allows the fast cadence + NormalCooldown* = 8 ## ticks between twin-gun shots (no spraying) + TinyCooldown* = 2 + + NDistBands* = 4 + NSpeedBands* = 4 + DistBandLo* = [0.0, 150.0, 300.0, 500.0] + SpeedBandLo* = [0.0, 2.0, 4.0, 6.0] + MaxBias* = 0.26 ## rad (~15 deg) cap on the learned aim bias + +type + PredictorPoints* = object + ## The three predictors' enemy position at one horizon, plus the per-kernel + ## final positions and posterior weights the spread selector needs. + mix*: tuple[x, y: float64] + res*: tuple[x, y: float64] + pers*: tuple[x, y: float64] + samples*: seq[tuple[x, y: float64]] + weights*: seq[float64] + + TwinAim* = object + ## The twin gun's per-tick output. + active*: bool + aimBearing*: float64 ## absolute bearing (rad, 0 = east CCW) after bias + x*, y*: float64 ## the (clipped) aim point + power*: float64 + spread*: float64 ## rad, max pairwise kernel disagreement at horizon + tolerance*: float64 ## rad, enemy silhouette width at the aim distance + horizon*: float64 ## ticks + baseBearing*: float64 ## bearing to the aim point BEFORE the bias offset + dist*: float64 + enemySpeed*: float64 + selfX*, selfY*: float64 + # what a fired shot needs for delayed scoring / bias training + bucket*: int + mixPt*, resPt*, persPt*: tuple[x, y: float64] + + PendingShot* = object + dueTick*: int + bucket*: int + selfX*, selfY*: float64 + aimBearing*: float64 + dist*, enemySpeed*: float64 + mixPt*, resPt*, persPt*: tuple[x, y: float64] + + Aimer* = ref object + bucket*: array[NBuckets, Hedge] + biasSum*: array[NDistBands, array[NSpeedBands, float64]] + biasN*: array[NDistBands, array[NSpeedBands, int]] + pending*: seq[PendingShot] + lastFireTick*: int + shots*: int + hits*: int + +# ── pure helpers ──────────────────────────────────────────────────────────── + +proc wrapPi*(a: float64): float64 = + ## Shortest signed angle in (-pi, pi], radians. + result = a + while result <= -PI: result += 2.0 * PI + while result > PI: result -= 2.0 * PI + +proc flightTime*(dist, power: float64): float64 = + ## Ticks a bullet travels `dist` units at `power`, per physics.bulletSpeed: + ## `dist / (20 - 3*power)`. A zero/negative power would divide by 20; the + ## physics clamp keeps the denominator in [11, 19.7]. + let v = bulletSpeed(power) + if v <= 0.0: 0.0 else: dist / v + +proc bucketIndex*(h: float64): int = + ## Bucket containing horizon `h` (ticks). Values past the last bucket clamp. + let hi = int(ceil(h)) + for i in 0 ..< NBuckets: + if hi <= BucketHi[i]: return i + NBuckets - 1 + +proc angularTolerance*(dist: float64, botRadius = BotRadius): float64 = + ## Angular half... actually FULL width of the enemy silhouette at `dist`: + ## `2 * atan2(botRadius, dist)`, radians. Closer targets subtend more angle. + if dist <= 1e-6: return PI + 2.0 * arctan2(botRadius, dist) + +proc selectPowerFromSpreads*(spreads: openArray[float64], tol: float64): float64 = + ## `spreads[i]` is the required angular spread at `FirePowers[i]`'s flight + ## horizon. FirePowers are DESCENDING, so the first index whose spread fits + ## inside `tol` is the largest admissible power; if none fits, the smallest + ## power. Monotone in `tol` and in a uniform scaling of `spreads`: a larger + ## spread can only shrink the admissible set, whose maximum is therefore + ## non-increasing. + let n = min(spreads.len, FirePowers.len) + for i in 0 ..< n: + if spreads[i] <= tol: return FirePowers[i] + if n == 0: FirePowers[^1] else: FirePowers[n - 1] + +proc maxPairwiseSpread*(samples: openArray[tuple[x, y: float64]], + weights: openArray[float64], + selfX, selfY, k: float64): float64 = + ## Max pairwise angular difference (rad) between the top-`k` kernels' predicted + ## positions as seen from `(selfX, selfY)`. `k <= 4` per spec. Fewer than two + ## usable samples => 0 (nothing to disagree about). + var pairs: seq[tuple[w: float64, x, y: float64]] + for i in 0 ..< samples.len: + let w = if i < weights.len: weights[i] else: 0.0 + pairs.add (w, samples[i].x, samples[i].y) + pairs.sort(proc(a, b: tuple[w: float64, x, y: float64]): int = cmp(b.w, a.w)) + let m = min(pairs.len, int(k)) + var ang: seq[float64] + for i in 0 ..< m: + ang.add arctan2(pairs[i].y - selfY, pairs[i].x - selfX) + var best = 0.0 + for i in 0 ..< ang.len: + for j in i + 1 ..< ang.len: + best = max(best, abs(wrapPi(ang[i] - ang[j]))) + best + +proc blend*(h: Hedge, mix, res, pers: tuple[x, y: float64]): tuple[x, y: float64] = + ## Predictor mixture at one horizon, by the bucket's Hedge weights. + let wm = h.weights[0] + let wr = h.weights[1] + let wp = h.weights[2] + (wm * mix.x + wr * res.x + wp * pers.x, + wm * mix.y + wr * res.y + wp * pers.y) + +proc clipToArena*(x, y, arenaW, arenaH: float64): tuple[x, y: float64, clipped: bool] = + let cx = clamp(x, 0.0, max(0.0, arenaW)) + let cy = clamp(y, 0.0, max(0.0, arenaH)) + (cx, cy, cx != x or cy != y) + +proc distBand*(dist: float64): int = + for i in countdown(NDistBands - 1, 0): + if dist >= DistBandLo[i]: return i + 0 + +proc speedBand*(speed: float64): int = + let s = abs(speed) + for i in countdown(NSpeedBands - 1, 0): + if s >= SpeedBandLo[i]: return i + 0 + +# ── construction ──────────────────────────────────────────────────────────── + +proc initAimer*(): Aimer = + new(result) + for i in 0 ..< NBuckets: + result.bucket[i] = initHedge(PredictorNames) + result.lastFireTick = -1000 + +# ── predictor trajectories at a horizon ───────────────────────────────────── + +proc pointAt*(kernels: seq[Kernel], origin: ReplayTick, + rp: ResidualPrediction, h: float64): PredictorPoints = + ## Roll every predictor to horizon `h` and return their final points. The + ## per-kernel samples and posterior weights feed the spread selector. + let k = max(1, int(round(h))) + let mix = rollout(kernels, origin, k) + result.samples = mix.samples + result.weights = origin.weights + if mix.points.len > 0: + result.mix = (mix.points[^1].x, mix.points[^1].y) + let resPts = residualTrajectory(origin, mix.points, rp, k) + if resPts.len > 0: result.res = (resPts[^1].x, resPts[^1].y) + let persPts = persistence(origin, k) + if persPts.len > 0: result.pers = (persPts[^1].x, persPts[^1].y) + +proc fusedPositionAt*(a: Aimer, kernels: seq[Kernel], origin: ReplayTick, + rp: ResidualPrediction, h: float64): tuple[x, y: float64] = + ## Horizon-bucketed predictor mixture at `h` (spec G8 `fusedPositionAt`). + let pp = pointAt(kernels, origin, rp, h) + blend(a.bucket[bucketIndex(h)], pp.mix, pp.res, pp.pers) + +# ── the per-tick aim ──────────────────────────────────────────────────────── + +proc biasOffset*(a: Aimer, dist, enemySpeed: float64): float64 = + ## Mean observed post-shot miss for this (distance band, speed band), clamped. + let db = distBand(dist) + let sb = speedBand(enemySpeed) + if a.biasN[db][sb] == 0: return 0.0 + clamp(a.biasSum[db][sb] / float(a.biasN[db][sb]), -MaxBias, MaxBias) + +proc computeAim*(a: Aimer, kernels: seq[Kernel], origin: ReplayTick, + rp: ResidualPrediction, selfX, selfY, + arenaW, arenaH: float64, + nominalPower = 2.0): TwinAim = + ## Flight-horizon aim point + spread-selected power. Pure with respect to the + ## world: `a` is only read (bucket weights, bias), never mutated here. + result.selfX = selfX + result.selfY = selfY + let range = hypot(origin.ex - selfX, origin.ey - selfY) + var h = flightTime(range, nominalPower) + var power = nominalPower + var pp = pointAt(kernels, origin, rp, h) + var pos = blend(a.bucket[bucketIndex(h)], pp.mix, pp.res, pp.pers) + var clip = clipToArena(pos.x, pos.y, arenaW, arenaH) + pos = (clip.x, clip.y) + var b = bucketIndex(h) + for it in 0 ..< MaxIter: + let aimDist = hypot(pos.x - selfX, pos.y - selfY) + let tol = angularTolerance(aimDist) + let spread0 = maxPairwiseSpread(pp.samples, pp.weights, selfX, selfY, 4.0) + # Spread at each candidate power's own flight horizon (lazy: break at the + # first admissible power, which is the largest because FirePowers descends). + var spreads: seq[float64] + for p in FirePowers: + let hp = flightTime(aimDist, p) + if abs(hp - h) < 0.5: + spreads.add spread0 + else: + spreads.add maxPairwiseSpread(pointAt(kernels, origin, rp, hp).samples, + pp.weights, selfX, selfY, 4.0) + power = selectPowerFromSpreads(spreads, tol) + let h2 = flightTime(aimDist, power) + if abs(h2 - h) < MinorStep: break + h = h2 + pp = pointAt(kernels, origin, rp, h) + b = bucketIndex(h) + pos = blend(a.bucket[b], pp.mix, pp.res, pp.pers) + let c = clipToArena(pos.x, pos.y, arenaW, arenaH) + pos = (c.x, c.y) + let aimDist = hypot(pos.x - selfX, pos.y - selfY) + let baseBearing = arctan2(pos.y - selfY, pos.x - selfX) + let bias = a.biasOffset(aimDist, origin.espeed) + result.active = true + result.bucket = b + result.mixPt = pp.mix + result.resPt = pp.res + result.persPt = pp.pers + result.x = pos.x + result.y = pos.y + result.power = power + result.spread = maxPairwiseSpread(pp.samples, pp.weights, selfX, selfY, 4.0) + result.tolerance = angularTolerance(aimDist) + result.horizon = h + result.baseBearing = baseBearing + result.dist = aimDist + result.enemySpeed = origin.espeed + result.aimBearing = wrapPi(baseBearing + bias) + +proc cooldownTicks*(spreadRad: float64): int = + ## Conservative cadence: the gun cannot spray. A tiny spread allows the fast + ## cadence; otherwise at least `NormalCooldown` ticks between shots. + if radToDeg(spreadRad) <= TinySpreadDeg: TinyCooldown else: NormalCooldown + +# ── online scoring / bias training ────────────────────────────────────────── + +proc noteShot*(a: var Aimer, aim: TwinAim, tick: int) = + ## Arm a fired twin-gun shot for delayed scoring. `dueTick` is the flight + ## horizon used at fire time; the realized enemy position then trains BOTH the + ## bucket's predictor Hedge and the segment bias histogram. + let due = tick + max(1, int(round(aim.horizon))) + if a.pending.len >= 64: a.pending.delete(0) + a.pending.add PendingShot(dueTick: due, bucket: aim.bucket, + selfX: aim.selfX, selfY: aim.selfY, + aimBearing: aim.aimBearing, dist: aim.dist, + enemySpeed: aim.enemySpeed, + mixPt: aim.mixPt, resPt: aim.resPt, persPt: aim.persPt) + a.lastFireTick = tick + inc a.shots + +proc resolve*(a: var Aimer, tick: int, enemyX, enemyY: float64) = + ## Called on every scan tick. Scores every pending shot whose horizon has + ## elapsed against the realized enemy position: updates the bucket Hedge + ## (distance-error loss per predictor) and the bias histogram (bearing miss). + var i = 0 + while i < a.pending.len: + let p = a.pending[i] + if tick < p.dueTick: + inc i + continue + let dm = hypot(p.mixPt.x - enemyX, p.mixPt.y - enemyY) + let dr = hypot(p.resPt.x - enemyX, p.resPt.y - enemyY) + let dp = hypot(p.persPt.x - enemyX, p.persPt.y - enemyY) + a.bucket[p.bucket].update([dm / 100.0, dr / 100.0, dp / 100.0]) + let actualBearing = arctan2(enemyY - p.selfY, enemyX - p.selfX) + let db = distBand(p.dist) + let sb = speedBand(p.enemySpeed) + a.biasSum[db][sb] += wrapPi(actualBearing - p.aimBearing) + inc a.biasN[db][sb] + if dm <= BotRadius: inc a.hits + a.pending.delete(i) + +proc bucketWeights*(a: Aimer, b: int): seq[float64] = + a.bucket[b].weights diff --git a/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim b/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim index e9515ae..a686313 100644 --- a/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim +++ b/ChimeraBot_garage/src/ChimeraBot/chimera/observer.nim @@ -19,7 +19,7 @@ ## readiness check for the M4 twin rollout, not the twin itself. import std/[math, os, strutils] -import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence +import ./physics, ./ledger, ./dsl, ./hedge, ./oracle, ./twinsim, ./residual, ./fusion, ./influence, ./aimer const MaxHorizon* = 5 ## rollout horizon for the G5-metrics readiness check @@ -70,6 +70,12 @@ type # itself runs in the bot's command path. residual: ResidualHead fusion: Fusion + + # M7 twin gun (G8): horizon-bucketed predictor Hedge + aim-bias corrector. + # Lives here because it is fed the same scan stream; it persists per match. + aimer: Aimer + gunAimDeg*, gunPower*, gunSpreadDeg*, gunInfluence*: float64 + twinActive*: bool prevOwnDir, prevOwnSpeed: float64 lastRealizedTurn, lastRealizedSpeed: float64 fireRateEma: float64 @@ -97,6 +103,7 @@ proc initObserver*(kernels: seq[Kernel], telemetryDir = ""): Observer = result.enemyHeat = 3.0 result.residual = initResidualHead() result.fusion = initFusion() + result.aimer = initAimer() result.carryOver = not defined(chimeraFreshRound) for i in 0 ..< PredSlots: result.predOrigin[i] = -1 @@ -244,6 +251,9 @@ proc observeScan*(o: Observer, tick: int, x, y, direction, speed, energy: float6 o.curOwnDir = ownDir; o.curOwnSpeed = ownSpeed return + # M7 twin gun: score any fired twin-gun shot whose flight horizon elapsed. + o.aimer.resolve(tick, x, y) + o.scoreScan(s) if o.havePrev: @@ -369,6 +379,35 @@ proc fusedInfluence*(o: Observer): float64 = ## Twin steering authority (0..1), ramped down by realized prediction loss. influenceScalar(o.fusion.lossEma, o.fusion.lossN) +# ── M7 twin gun (G8) ──────────────────────────────────────────────────────── + +proc twinAim*(o: Observer, selfX, selfY, arenaW, arenaH: float64, + nominalPower = 2.0): TwinAim = + ## Flight-horizon aim point at the current origin. Empty (`.active == false`) + ## when no scan has been seen yet, so the caller falls back to the ELM gun. + if not o.haveCur: return + let origin = o.probeOrigin() + let rp = o.residual.predict(features(o.currentResidualInput())) + o.aimer.computeAim(o.kernels, origin, rp, selfX, selfY, + arenaW, arenaH, nominalPower) + +proc noteTwinShot*(o: Observer, aim: TwinAim, tick: int) = + ## Arm a fired twin-gun shot for delayed scoring / bias training. + o.aimer.noteShot(aim, tick) + +proc twinGunLastFire*(o: Observer): int = o.aimer.lastFireTick +proc twinGunShots*(o: Observer): int = o.aimer.shots +proc twinGunHits*(o: Observer): int = o.aimer.hits + +proc setGunTelemetry*(o: Observer, aimDeg, power, spreadDeg, influence: float64, + active: bool) = + ## Observation-only: record the twin gun's output for the JSONL telemetry. + o.gunAimDeg = aimDeg + o.gunPower = power + o.gunSpreadDeg = spreadDeg + o.gunInfluence = influence + o.twinActive = active + proc fusedWeights*(o: Observer): seq[float64] = o.fusion.weights() proc fusionLoss*(o: Observer): float64 = o.fusion.lossEma proc fusionSamples*(o: Observer): int = o.fusion.lossN @@ -428,6 +467,11 @@ proc writeTick*(o: Observer, tick: int) = line.add "{\"name\":\"" & kv.name & "\",\"w\":" & $kv.weight & "}" line.add "],\"entropy\":" & $o.hedge.entropy() line.add ",\"censorRate\":" & $o.censorRate() + # M7 twin-gun telemetry (observation-only; zeroed when the twin gun is off). + line.add ",\"gunAim\":" & $o.gunAimDeg & ",\"gunPower\":" & $o.gunPower & + ",\"spread\":" & $o.gunSpreadDeg & + ",\"influence\":" & $o.gunInfluence & + ",\"twinGun\":" & $(if o.twinActive: "true" else: "false") line.add "}\n" o.f.write(line) flushFile(o.f) diff --git a/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.cmd b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.cmd new file mode 100644 index 0000000..f69eee7 --- /dev/null +++ b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.cmd @@ -0,0 +1,3 @@ +@echo off +cd /d "%~dp0" +Dodger.exe Dodger.json %* diff --git a/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.json b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.json new file mode 100644 index 0000000..e36869c --- /dev/null +++ b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.json @@ -0,0 +1,9 @@ +{ + "name": "Dodger", + "version": "1.0.0", + "authors": ["Davide Cappellini"], + "description": "Reactive wave-dodging archetype opponent (CHIMERA G8 bench)", + "gameTypes": ["classic", "1v1"], + "platform": "Nim", + "programmingLang": "Nim" +} diff --git a/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.nim b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.nim new file mode 100644 index 0000000..57fd9c6 --- /dev/null +++ b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.nim @@ -0,0 +1,65 @@ +## Dodger — garage-local reactive archetype opponent (spec §12 Tier B; M7/G8). +## +## A wave-based dodger that exists to be a MOVING, dodging target for the G8 +## hit-rate bench. It never leads its gun (it does not fire at all): its whole +## job is to move unpredictably enough that a 5-tick lead is insufficient, which +## is exactly the regime the twin gun is supposed to fix. +## +## All decision logic lives in `dodger_spec.nim`; this file only adapts the API +## events to `DodgeWave` and applies `dodgeDecision` to the body. It therefore +## behaves exactly as the documented spec function by construction. + +import std/[math, os] +import robocode_tankroyale_botapi +import dodger_spec + +type + Dodger* = ref object of Bot + tick: int + wave: DodgeWave + strafeSign: float64 + prevEnergy: float64 + haveEnemy: bool + +proc newDodger(): Dodger = + Dodger(strafeSign: 1.0) + +method onScannedBot*(bot: Dodger, e: ScannedBotEvent) = + ## An energy drop in `[0.1, 3.0]` is the enemy's own shot (spec §4.3): start a + ## wave from its position at fire time. + if bot.haveEnemy: + let drop = bot.prevEnergy - e.energy + if drop >= 0.1 - 1e-9 and drop <= 3.0 + 1e-9: + let p = clamp(drop, 0.1, 3.0) + bot.wave = DodgeWave(originX: e.x, originY: e.y, fireTick: bot.tick, + bulletSpeed: 20.0 - 3.0 * p) + bot.prevEnergy = e.energy + bot.haveEnemy = true + +method onHitByBullet*(bot: Dodger, e: HitByBulletEvent) = + ## The wave already connected: no dodge left to make, just switch strafe side + ## so the next wave is met from the other direction. + bot.strafeSign = -bot.strafeSign + +method run*(bot: Dodger) = + setAdjustGunForBodyTurn(true) + setAdjustRadarForBodyTurn(true) + while isRunning(): + let own = DodgeOwn(x: getX(), y: getY(), heading: getDirection()) + let cmd = dodgeDecision(bot.wave, own, bot.tick, + getArenaWidth().float, getArenaHeight().float, + bot.strafeSign) + bot.strafeSign = cmd.strafeSign + setTurnRate(cmd.turnRate) + setTargetSpeed(cmd.targetSpeed) + setGunTurnRate(0.0) + setRadarTurnRate(45.0) + go() + inc bot.tick + +when isMainModule: + let jsonPath = + if paramCount() >= 1: paramStr(1) + else: currentSourcePath().parentDir / "Dodger.json" + var bot = newDodger() + start(bot, jsonPath) diff --git a/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.sh b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.sh new file mode 100755 index 0000000..5ae5c28 --- /dev/null +++ b/ChimeraBot_garage/tests/archetypes/Dodger/Dodger.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Dodger — garage-local archetype opponent. Compiles (once, into a throwaway +# /tmp dir) and runs, so a `git clean` tree never carries a binary. +set -e +DIR="$(cd -- "$(dirname -- "$0")" && pwd)" +BIN="${TMPDIR:-/tmp}/chimera_dodger_arch/Dodger" +if [ ! -x "$BIN" ] || [ "$DIR/Dodger.nim" -nt "$BIN" ] || [ "$DIR/dodger_spec.nim" -nt "$BIN" ]; then + mkdir -p "$(dirname -- "$BIN")" + API="$(nimble path robocode_tankroyale_botapi 2>/dev/null | head -n 1)" + JSONY="$(nimble path jsony 2>/dev/null | head -n 1)" + nim c -d:release --hints:off --path:"$API" --path:"$JSONY" --out:"$BIN" "$DIR/Dodger.nim" >/dev/null +fi +exec "$BIN" "$DIR/Dodger.json" "$@" diff --git a/ChimeraBot_garage/tests/archetypes/Dodger/dodger_spec.nim b/ChimeraBot_garage/tests/archetypes/Dodger/dodger_spec.nim new file mode 100644 index 0000000..e01fbe9 --- /dev/null +++ b/ChimeraBot_garage/tests/archetypes/Dodger/dodger_spec.nim @@ -0,0 +1,74 @@ +## Dodger spec function — the documented, unit-tested behaviour of the reactive +## `Dodger` archetype (docs/chimera-spec.md §12 Tier B; M7/G8). +## +## Dodger is a **wave-based reactive dodger** built to be a *dodging* opponent for +## the G8 hit-rate bench: when it detects an enemy bullet (an energy drop in +## `onScannedBot`) it strafes perpendicular to the wave, flipping its strafe +## direction when it is pinned near a wall. The bot's run loop contains **no +## decision logic of its own** — it calls `dodgeDecision` and applies the result, +## so the bot's behaviour *is* this function by construction. `test_dodger.nim` +## pins the function's outputs on synthetic inputs, which is the trust story: +## matrix-tested, not untested. +## +## Pure and deterministic: no RNG, no I/O, no clock. + +import std/math + +const + ReactionTicks* = 14.0 ## start dodging when the wavefront is this close + StrafeSpeed* = 8.0 ## full throttle while dodging + PatrolSpeed* = 4.0 ## idle cruise when no wave threatens + WallMargin* = 60.0 ## "pinned near a wall" band + +type + DodgeWave* = object + ## A wavefront: the enemy position at fire time, the fire tick, and the + ## bullet speed (`20 - 3*power`, physics.bulletSpeed). + originX*, originY*: float64 + fireTick*: int + bulletSpeed*: float64 + + DodgeOwn* = object + x*, y*, heading*: float64 + + DodgeCmd* = object + turnRate*: float64 ## deg/tick body turn command + targetSpeed*: float64 + strafeSign*: float64 ## +1 / -1, carried to the next tick (hysteresis) + dodging*: bool + +proc wrap180(deg: float64): float64 = + result = deg mod 360.0 + if result <= -180.0: result += 360.0 + elif result > 180.0: result -= 360.0 + +proc waveETA*(w: DodgeWave, x, y: float64, tick: int): float64 = + ## Ticks until the wavefront reaches `(x, y)`; negative once it is past. + let dist = hypot(x - w.originX, y - w.originY) + dist / max(w.bulletSpeed, 1e-9) - float(tick - w.fireTick) + +proc nearWall*(x, y, arenaW, arenaH: float64): bool = + ## Pinned when inside `WallMargin` of any wall (spec "corner-flip near waves"). + x < WallMargin or x > arenaW - WallMargin or + y < WallMargin or y > arenaH - WallMargin + +proc dodgeDecision*(w: DodgeWave, own: DodgeOwn, tick: int, + arenaW, arenaH, prevSign: float64): DodgeCmd = + ## The documented spec function. If the wave is spent (`eta <= 0`) or too far + ## (`eta > ReactionTicks`) the bot patrols straight; otherwise it turns to + ## move perpendicular to the wave bearing, flipping the strafe sign when near + ## a wall. + result.strafeSign = prevSign + result.targetSpeed = PatrolSpeed + result.turnRate = 0.0 + result.dodging = false + let eta = waveETA(w, own.x, own.y, tick) + if eta <= 0.0 or eta > ReactionTicks: + return + result.dodging = true + result.strafeSign = if nearWall(own.x, own.y, arenaW, arenaH): -prevSign + else: prevSign + let bearing = arctan2(own.y - w.originY, own.x - w.originX) * 180.0 / PI + let perp = bearing + 90.0 * result.strafeSign + result.turnRate = clamp(wrap180(perp - own.heading), -10.0, 10.0) + result.targetSpeed = StrafeSpeed diff --git a/ChimeraBot_garage/tests/bench_g8.nim b/ChimeraBot_garage/tests/bench_g8.nim new file mode 100644 index 0000000..8efb88d --- /dev/null +++ b/ChimeraBot_garage/tests/bench_g8.nim @@ -0,0 +1,243 @@ +## G8 OFFLINE BENCH — flight-horizon aiming (twin gun) vs ELM vs head-on. +## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8. +## +## Replays recorded trajectories (the archived M6 telemetry under +## `CHIMERA_G8_TELEMETRY`, default `/tmp/chimera_g4_run`) plus a deterministically +## SYNTHESIZED Dodger trajectory (the archetype's documented spec function run +## through the physics mirror), and, for every sampled origin tick, simulates the +## bullet each of three aim policies would have fired: +## +## * HEAD-ON — aim at the enemy's position at fire time (no lead); +## * ELM — the ELM gun's base: geometric intercept from observed velocity; +## * TWIN — `chimera/aimer.nim`'s flight-horizon fused aim + spread power. +## +## Hit = the bullet passes within `HitRadius` of the enemy's realized position on +## some flight tick before the wall. Aim slew and cadence are abstracted away: the +## comparison is a pure aim-policy hit rate on identical trajectories. +## +## Run: `nim c -r --hints:off -d:release tests/bench_g8.nim` + +import std/[math, os, strutils, tables, algorithm, times, sequtils] +import chimera/dsl +import chimera/twinsim +import chimera/residual +import chimera/aimer +import chimera/physics +import dodger_spec + +const + HitRadius* = 20.0 ## bot radius (18) + bullet radius (~2) + ElmPower* = 2.0 ## the ELM gun's fixed firepower + MaxFlight* = 80 ## ticks before a bullet is given up + Stride* = 4 ## origin-tick sampling stride (de-correlate) + MaxOrigins* = 220 ## origins sampled per telemetry file + TelDir* = "/tmp/chimera_g4_run" + +type + Policy = enum + pHeadOn, pElm, pTwin + + Tally = object + hits, shots: int + +proc hitRate(t: Tally): float64 = + if t.shots == 0: 0.0 else: 100.0 * float(t.hits) / float(t.shots) + +proc parseNum(ln: string, key: string, default = 0.0): float64 = + let needle = "\"" & key & "\":" + let i = ln.find(needle) + if i < 0: return default + var j = i + needle.len + while j < ln.len and ln[j] in {' ', '\t'}: inc j + let s = j + while j < ln.len and (ln[j] in Digits or ln[j] in {'-', '+', '.', 'e', 'E'}): inc j + if j == s: return default + try: parseFloat(ln[s ..< j]) + except ValueError: default + +proc enemyMap(rec: Record): Table[int, tuple[x, y: float64]] = + for t in rec.ticks: + if t.scanned: result[t.tick] = (t.ex, t.ey) + +proc simulateHit(sx, sy, bearing, power: float64, originTick: int, + emap: Table[int, tuple[x, y: float64]], + arenaW, arenaH: float64): bool = + ## Fire from (sx,sy) at `bearing`/`power`; true if the bullet comes within + ## HitRadius of the realized enemy position before leaving the arena. + let v = bulletSpeed(power) + var bx = sx + var by = sy + var b = bearing + for h in 1 .. MaxFlight: + bx += v * cos(b) + by += v * sin(b) + if bx < 0.0 or bx > arenaW or by < 0.0 or by > arenaH: return false + let e = emap.getOrDefault(originTick + h, (x: -1e9, y: -1e9)) + if e.x > -1e8 and hypot(bx - e.x, by - e.y) <= HitRadius: return true + false + +proc evalRecord(rec: Record, kernels: seq[Kernel], + arenaW, arenaH: float64): Table[Policy, Tally] = + let emap = enemyMap(rec) + let rps = replay(rec, kernels) + # ONE aimer per record, trained online exactly like the live bot: at each + # sampled tick score the shots whose horizon has elapsed, THEN aim. A fresh + # per-origin aimer would never learn the bucket weights and would misrepresent + # the twin gun. + var a = initAimer() + var n = 0 + for rt in rps: + if rt.tick mod Stride != 0: continue + if n >= MaxOrigins: break + inc n + a.resolve(rt.tick, rt.ex, rt.ey) + let dx = rt.ex - rt.ox + let dy = rt.ey - rt.oy + let head = arctan2(dy, dx) + let d = hypot(dx, dy) + let vx = rt.espeed * cos(degToRad(rt.edir)) + let vy = rt.espeed * sin(degToRad(rt.edir)) + let tof = d / bulletSpeed(ElmPower) + let elm = arctan2(rt.ey + vy * tof - rt.oy, rt.ex + vx * tof - rt.ox) + let aim = a.computeAim(kernels, rt, ResidualPrediction(), rt.ox, rt.oy, + arenaW, arenaH, ElmPower) + for (pol, bearing, power) in [(pHeadOn, head, ElmPower), + (pElm, elm, ElmPower), + (pTwin, (if aim.active: aim.aimBearing else: elm), + (if aim.active: aim.power else: ElmPower))]: + result.mgetOrPut(pol, Tally()).shots.inc + if simulateHit(rt.ox, rt.oy, bearing, power, rt.tick, emap, arenaW, arenaH): + result[pol].hits.inc + if aim.active: a.noteShot(aim, rt.tick) + +proc synthesizeDodger(kernels: seq[Kernel]): Record = + ## A deterministic Dodger record: our bot sits at (600,300); a wave is fired + ## every 20 ticks; the enemy runs `dodgeDecision` through the physics mirror. + ## Gives the bench a MOVING, DODGING opponent without Java. + const W = 800.0 + const H = 600.0 + let ox = 600.0 + let oy = 300.0 + var ex = 200.0 + var ey = 300.0 + var ehead = 0.0 + var espeed = 0.0 + var sign = 1.0 + var wave = DodgeWave(originX: ox, originY: oy, fireTick: -1000, + bulletSpeed: 20.0 - 3.0 * ElmPower) + result.opponent = "Dodger" + result.round = 1 + for tick in 1 .. 1400: + if tick mod 12 == 0: + wave = DodgeWave(originX: ox, originY: oy, fireTick: tick, + bulletSpeed: 20.0 - 3.0 * ElmPower) + let cmd = dodgeDecision(wave, DodgeOwn(x: ex, y: ey, heading: ehead), tick, + W, H, sign) + sign = cmd.strafeSign + espeed = stepSpeed(espeed, cmd.targetSpeed) + ehead = wrap180(ehead + limitTurnRate(cmd.turnRate, espeed)) + ex = clamp(ex + espeed * cos(degToRad(ehead)), 0.0, W) + ey = clamp(ey + espeed * sin(degToRad(ehead)), 0.0, H) + result.ticks.add TickRecord(tick: tick, scanned: true, ex: ex, ey: ey, + edir: ehead, espeed: espeed, eenergy: 100.0, + ox: ox, oy: oy, odir: 180.0, ospeed: 0.0) + +proc addInto(dst: var Table[Policy, Tally], src: Table[Policy, Tally]) = + for pol, t in src: + dst.mgetOrPut(pol, Tally()).hits += t.hits + dst.mgetOrPut(pol, Tally()).shots += t.shots + +proc main() = + let kernels = allKernels() + let dir = getEnv("CHIMERA_G8_TELEMETRY", TelDir) + var byOpp = initTable[string, seq[string]]() + if dirExists(dir): + for path in walkDirRec(dir): + if not path.endsWith(".jsonl"): continue + let base = path.extractFilename + let dash = base.rfind('-') + if dash <= 0: continue + byOpp.mgetOrPut(base[0 ..< dash], @[]).add path + + var opps = toSeq(byOpp.keys) + opps.sort() + opps.add "Dodger" + + var rows: seq[string] + var total: Table[Policy, Tally] + var winOverElm = 0 + var winOverHead = 0 + let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"] + var nOpp = 0 + echo "opponent twin% elm% head% n" + for opp in opps: + var t: Table[Policy, Tally] + if opp == "Dodger": + t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0) + else: + let files = byOpp[opp] + var used = 0 + for f in files: + if used >= 5: break + addInto(t, evalRecord(loadRecord(f), kernels, 800.0, 600.0)) + inc used + let tw = t.getOrDefault(pTwin) + let el = t.getOrDefault(pElm) + let ho = t.getOrDefault(pHeadOn) + addInto(total, t) + inc nOpp + if tw.hits >= el.hits: inc winOverElm + if tw.hits >= ho.hits and opp in movers: inc winOverHead + echo alignLeft(opp, 12), + align(formatFloat(tw.hitRate, ffDecimal, 1), 7), + align(formatFloat(el.hitRate, ffDecimal, 1), 7), + align(formatFloat(ho.hitRate, ffDecimal, 1), 7), + align($tw.shots, 6) + rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " & + formatFloat(el.hitRate, ffDecimal, 1) & " | " & + formatFloat(ho.hitRate, ffDecimal, 1) & " | " & $tw.shots & " |" + + let passElm = winOverElm >= 6 + let passHead = winOverHead >= movers.len + let verdict = if passElm and passHead: "PASS" else: "FAIL" + echo "\nG8 offline: twin >= ELM on ", winOverElm, "/", nOpp, + " (bar >= 6); twin >= head-on on ", winOverHead, "/", movers.len, + " movers; verdict ", verdict + echo "SUITE twin ", formatFloat(total[pTwin].hitRate, ffDecimal, 1), + "% elm ", formatFloat(total[pElm].hitRate, ffDecimal, 1), + "% head ", formatFloat(total[pHeadOn].hitRate, ffDecimal, 1), "%" + + var md = "# G8 offline hit-rate bench (M7, twin gun)\n\n" + md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized Dodger; " & + "hit = bullet passes within " & formatFloat(HitRadius, ffDecimal, 0) & + " units of the realized enemy position. Aim slew/cadence abstracted. " & + "Generated by `tests/bench_g8.nim`.\n\n" + md.add "| opponent | twin % | ELM % | head-on % | shots |\n|---|---:|---:|---:|---:|\n" + for r in rows: md.add r & "\n" + md.add "\n**G8 offline bar: twin >= ELM on >= 6/9 opponents AND twin >= head-on " & + "on the movers.** Result: twin >= ELM on " & $winOverElm & "/" & $nOpp & + "; twin >= head-on on " & $winOverHead & "/" & $movers.len & + " movers. **Verdict: " & verdict & ".**\n" + md.add "\n## Method / caveats\n\n" + md.add "* `TWIN` = `chimera/aimer.nim`: iterated flight time \n" & + " `h = dist/(20-3*power)`, horizon-bucketed predictor Hedge " & + "(mixture/residual/persistence), trained ONLINE per record (one aimer, " & + "score-then-aim each sampled tick), spread-selected power.\n" + md.add "* `ELM` = the ELM gun's **base** geometric intercept from the " & + "observed velocity (the learned correction is gated and small, and the " & + "online ELM state cannot be replayed offline). This is a proxy for the " & + "full ELM gun — a documented deviation.\n" + md.add "* Power monotonicity: `selectPowerFromSpreads` returns the largest " & + "power whose required spread fits the enemy-silhouette tolerance " & + "`2*atan2(18, dist)`; the choice is non-increasing in spread " & + "(`test_aimer.nim`, aimer 4).\n" + md.add "* The synthesized Dodger fires a wave every 12 ticks; a real battle " & + "would add shooter motion. Live results (`m7_g8_live.md`) are the " & + "reality check.\n" + let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_g8.md" + createDir(art.parentDir) + writeFile(art, md) + echo "Artifact: ", art + +when isMainModule: + main() diff --git a/ChimeraBot_garage/tests/bench_g8_live.nim b/ChimeraBot_garage/tests/bench_g8_live.nim new file mode 100644 index 0000000..70ada0d --- /dev/null +++ b/ChimeraBot_garage/tests/bench_g8_live.nim @@ -0,0 +1,169 @@ +## G8 LIVE BENCH — twin gun vs ELM gun vs inert, suite + G7 no-regression. +## LIVE, Java required. Three binaries from the SAME tree: +## * inert — `-d:chimeraInert` (all CHIMERA command paths off == M1 copy) +## * elm — `-d:chimeraNoTwinGun` (probes+fusion+influence, ELM gun as now) +## * twin — default (ELM gun REPLACED by the M7 twin gun) +## 5 rounds per arm per opponent vs the 8 primary sample bots + the garage-local +## Dodger archetype. Reports win rate + score margin; the G7 no-regression read +## is twin >= inert (win rate) on every opponent, stated plainly when it fails. +## +## Run: `nim c -r --hints:off -d:release tests/bench_g8_live.nim` + +import std/[os, osproc, strutils, sequtils, math, tables, algorithm, times] +import bench_common + +const + Rounds = 5 + DodgerDir = currentSourcePath().parentDir / "archetypes" / "Dodger" + +type + Outcome = object + rounds, wins: int + ourScore, oppScore: float64 + ourSurv, oppSurv: int + + Arm = object + tag, name: string + defines: seq[string] + +const Arms = [ + Arm(tag: "inert", name: "ChimeraInert", defines: @["-d:chimeraInert"]), + Arm(tag: "elm", name: "ChimeraElm", defines: @["-d:chimeraNoTwinGun"]), + Arm(tag: "twin", name: "ChimeraTwin", defines: @[]), +] + +proc parseOutcome(log, ourName: string): Outcome = + for ln in log.splitLines(): + if ln.len == 0 or ln.find("\"event\":\"round_ended\"") < 0: continue + inc result.rounds + let ri = ln.find("\"results\":[") + if ri < 0: continue + let oi = ln.find('[', ri) + let ci = ln.find(']', ri) + if oi < 0 or ci < 0 or ci <= oi: continue + let seg = ln[oi + 1 ..< ci] + var j = 0 + var ourScoreV = -1.0 + var theirScoreV = -1.0 + var ourSurvF, theirSurvF = false + while j < seg.len: + let s = seg.find('{', j) + if s < 0: break + let e = seg.find('}', s) + if e < 0: break + let obj = seg[s + 1 ..< e] + let (found, name) = extract(obj, "name") + let (sf, score) = extract(obj, "score") + let (vf, surv) = extract(obj, "survived") + if found and sf and vf: + if name == ourName: + ourScoreV = score.parseFloat() + ourSurvF = surv == "true" + else: + theirScoreV = score.parseFloat() + theirSurvF = surv == "true" + j = e + 1 + if ourScoreV >= 0.0 and theirScoreV >= 0.0: + result.ourScore += ourScoreV + result.oppScore += theirScoreV + if ourScoreV > theirScoreV: inc result.wins + if ourSurvF: inc result.ourSurv + if theirSurvF: inc result.oppSurv + +proc runBattle(url: string, botDirs: seq[string], rounds: int, + ourName, tag: string): Outcome = + putEnv("CHIMERA_TELEMETRY_DIR", getTempDir() / ("chimera_g8_tel_" & tag)) + let (ok, logPath) = runBattleHardLog(url, botDirs, rounds, + logName = "chimera_g8_" & tag) + if not ok: return Outcome() + parseOutcome(readFile(logPath), ourName) + +proc winRate(o: Outcome): float64 = + if o.rounds == 0: 0.0 else: 100.0 * float(o.wins) / float(o.rounds) + +proc margin(o: Outcome): float64 = o.ourScore - o.oppScore + +proc main() = + guardSkip() + echo "[G8-live] staging 3 arms..." + var bots = initTable[string, string]() + for a in Arms: + bots[a.tag] = stageBot("g8_" & a.tag, a.defines, a.name) + + let opps = sorted(toSeq(Expected.keys)) & @["Dodger"] + var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out + for arm in Arms: + var t = initTable[string, Outcome]() + for opp in opps: + let oppDir = if opp == "Dodger": DodgerDir else: SampleRoot / opp + restartServer() + putEnv("CHIMERA_OPPONENT", opp) + let o = runBattle(serverUrl(), @[bots[arm.tag], oppDir], Rounds, + arm.name, arm.tag & "_" & opp) + t[opp] = o + echo " [", alignLeft(arm.tag, 5), "] vs ", alignLeft(opp, 10), + " rounds=", o.rounds, + " winRate=", formatFloat(winRate(o), ffDecimal, 0), "%", + " margin=", formatFloat(margin(o), ffDecimal, 1) + suite[arm.tag] = t + + echo "\n=== G8 live suite (", Rounds, " rounds/arm/opponent) ===" + echo "Opponent elmW% elmM twinW% twinM inertW% inertM" + var noRegress = true + var regress: seq[string] + var lines: seq[string] + lines.add "# G8 live bench (M7 twin gun)\n" + lines.add "Three arms from the SAME tree: inert (`-d:chimeraInert`), elm " & + "(`-d:chimeraNoTwinGun`), twin (default). " & $Rounds & + " rounds per arm per opponent. Generated by `tests/bench_g8_live.nim`.\n" + lines.add "| opponent | elm W% | elm margin | twin W% | twin margin | inert W% | inert margin |" + lines.add "|---|---:|---:|---:|---:|---:|---:|" + for opp in opps: + let e = suite["elm"].getOrDefault(opp) + let t = suite["twin"].getOrDefault(opp) + let i = suite["inert"].getOrDefault(opp) + if t.rounds > 0 and i.rounds > 0 and t.wins < i.wins: + noRegress = false; regress.add opp + echo " ", alignLeft(opp, 10), + align(formatFloat(winRate(e), ffDecimal, 0), 7), + align(formatFloat(margin(e), ffDecimal, 1), 7), + align(formatFloat(winRate(t), ffDecimal, 0), 7), + align(formatFloat(margin(t), ffDecimal, 1), 6), + align(formatFloat(winRate(i), ffDecimal, 0), 8), + align(formatFloat(margin(i), ffDecimal, 1), 7) + lines.add "| " & opp & " | " & formatFloat(winRate(e), ffDecimal, 1) & " | " & + formatFloat(margin(e), ffDecimal, 1) & " | " & + formatFloat(winRate(t), ffDecimal, 1) & " | " & + formatFloat(margin(t), ffDecimal, 1) & " | " & + formatFloat(winRate(i), ffDecimal, 1) & " | " & + formatFloat(margin(i), ffDecimal, 1) & " |" + + # suite totals + var te, tt, ti: Outcome + for opp in opps: + for (dst, arm) in [(addr te, "elm"), (addr tt, "twin"), (addr ti, "inert")]: + let o = suite[arm].getOrDefault(opp) + dst.rounds += o.rounds; dst.wins += o.wins + dst.ourScore += o.ourScore; dst.oppScore += o.oppScore + echo "\nTotals: elm ", formatFloat(winRate(te), ffDecimal, 1), + "% (m ", formatFloat(margin(te), ffDecimal, 1), ") twin ", + formatFloat(winRate(tt), ffDecimal, 1), "% (m ", + formatFloat(margin(tt), ffDecimal, 1), ") inert ", + formatFloat(winRate(ti), ffDecimal, 1), "% (m ", + formatFloat(margin(ti), ffDecimal, 1), ")" + lines.add "\n**Totals:** elm " & formatFloat(winRate(te), ffDecimal, 1) & + "% (margin " & formatFloat(margin(te), ffDecimal, 1) & "), twin " & + formatFloat(winRate(tt), ffDecimal, 1) & "% (margin " & + formatFloat(margin(tt), ffDecimal, 1) & "), inert " & + formatFloat(winRate(ti), ffDecimal, 1) & "% (margin " & + formatFloat(margin(ti), ffDecimal, 1) & ")." + lines.add "\n**G7 no-regression (twin >= inert win-rate on every opponent): " & + (if noRegress: "PASS" else: "**FAIL** on " & regress.join(", ")) & ".**" + + let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_g8_live.md" + createDir(art.parentDir) + writeFile(art, lines.join("\n") & "\n") + echo "\nArtifact: ", art + +when isMainModule: + main() diff --git a/ChimeraBot_garage/tests/config.nims b/ChimeraBot_garage/tests/config.nims index 66231e8..31848a7 100644 --- a/ChimeraBot_garage/tests/config.nims +++ b/ChimeraBot_garage/tests/config.nims @@ -1,2 +1,3 @@ --path:"../src/ChimeraBot" --path:"../../common_libs" +--path:"archetypes/Dodger" diff --git a/ChimeraBot_garage/tests/test_aimer.nim b/ChimeraBot_garage/tests/test_aimer.nim new file mode 100644 index 0000000..eb3b6d2 --- /dev/null +++ b/ChimeraBot_garage/tests/test_aimer.nim @@ -0,0 +1,149 @@ +## Tier A tests for the CHIMERA twin gun (chimera/aimer.nim, spec G8 / M7). +## Pure Nim, no Java. Run: from ChimeraBot_garage, `nimble test`. + +import std/[math, os, strutils] +import chimera/dsl +import chimera/twinsim +import chimera/residual +import chimera/aimer + +var failed = 0 +proc check(name: string, cond: bool, detail: string = "") = + if cond: echo " ok ", name + else: echo " FAIL ", name, " [", detail, "]"; inc failed + +let kernels = allKernels() + +proc origin(x = 200.0, y = 300.0, dir = 0.0, sp = 6.0): ReplayTick = + var r = ReplayTick(tick: 100, ex: x, ey: y, edir: dir, espeed: sp, + eenergy: 80.0, ox: 600.0, oy: 300.0, odir: 180.0, + ospeed: 4.0, lastTurn: 0.0, lastSpeed: sp) + r.weights = newSeq[float64](kernels.len) + for i in 0 ..< kernels.len: r.weights[i] = 1.0 / float64(kernels.len) + r.mems = newSeq[KernelMem](kernels.len) + for i in 0 ..< kernels.len: r.mems[i] = defaultMemory(kernels[i].defaultParams) + r + +block: + echo "aimer 1: flight time = dist / (20 - 3*power)" + check("power 3.0", abs(flightTime(110.0, 3.0) - 10.0) < 1e-9, $flightTime(110.0, 3.0)) + check("power 0.1", abs(flightTime(197.0, 0.1) - 10.0) < 1e-9, $flightTime(197.0, 0.1)) + check("power 1.0", abs(flightTime(17.0, 1.0) - 1.0) < 1e-9, $flightTime(17.0, 1.0)) + check("tolerance widens as range shrinks", + angularTolerance(100.0) > angularTolerance(500.0)) + check("tolerance = 2*atan2(r, dist)", + abs(angularTolerance(300.0) - 2.0 * arctan2(BotRadius, 300.0)) < 1e-12) + +block: + echo "aimer 2: bucket indexing" + check("h=1 -> bucket 0", bucketIndex(1.0) == 0) + check("h=7 -> bucket 0", bucketIndex(7.0) == 0) + check("h=8 -> bucket 1", bucketIndex(8.0) == 1) + check("h=18 -> bucket 2", bucketIndex(18.0) == 2) + check("h=36 -> bucket 3", bucketIndex(36.0) == 3) + check("h=200 clamps to last", bucketIndex(200.0) == 3) + +block: + echo "aimer 3: max pairwise spread" + let s0 = maxPairwiseSpread([(100.0, 0.0), (100.0, 0.0)], [0.5, 0.5], 0.0, 0.0, 4.0) + check("co-located kernels have zero spread", s0 == 0.0, $s0) + let s1 = maxPairwiseSpread([(100.0, 100.0), (100.0, -100.0)], [0.9, 0.1], 0.0, 0.0, 4.0) + check("opposite bearings give a nonzero spread", s1 > 1.0, $s1) + check("top-k weight ranking is used", + maxPairwiseSpread([(100.0, 100.0), (100.0, -100.0)], [0.1, 0.9], 0.0, 0.0, 1.0) == 0.0) + +block: + echo "aimer 4: power monotone non-increasing in spread" + let base = [0.002, 0.004, 0.006, 0.008, 0.010, 0.012, 0.014] + let tol = angularTolerance(300.0) + var prev = 99.0 + var monotone = true + for mult in [0.1, 0.5, 1.0, 2.0, 5.0, 20.0, 100.0]: + var spreads: seq[float64] + for b in base: spreads.add b * mult + let p = selectPowerFromSpreads(spreads, tol) + if p > prev + 1e-12: monotone = false + prev = p + check("chosen power never rises as spread scales up", monotone) + check("spread far below tolerance picks the max power", + selectPowerFromSpreads([1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6], tol) == 3.0) + check("spread far above tolerance picks the min power", + selectPowerFromSpreads([9.0, 9.0, 9.0, 9.0, 9.0, 9.0, 9.0], tol) == 0.1) + +block: + echo "aimer 5: iterated flight time converges (hostile dodger)" + let a = initAimer() + let rp = ResidualPrediction() + let aim = a.computeAim(kernels, origin(), rp, 600.0, 300.0, 800.0, 600.0, 2.0) + check("aim is active", aim.active) + let hCheck = flightTime(aim.dist, aim.power) + check("h == flightTime(dist, power) after convergence", + abs(hCheck - aim.horizon) < 0.5, $hCheck & " vs " & $aim.horizon) + check("aim point inside arena", + aim.x >= 0.0 and aim.x <= 800.0 and aim.y >= 0.0 and aim.y <= 600.0) + check("chosen power is legal", + aim.power in FirePowers, $aim.power) + check("horizon in a plausible bullet-flight band (>= 5 ticks)", + aim.horizon >= 5.0, $aim.horizon) + let aim2 = a.computeAim(kernels, origin(), rp, 600.0, 300.0, 800.0, 600.0, 2.0) + check("aim is deterministic", + aim2.horizon == aim.horizon and aim2.power == aim.power and + aim2.x == aim.x and aim2.y == aim.y) + +block: + echo "aimer 6: arena clipping" + let c = clipToArena(900.0, -30.0, 800.0, 600.0) + check("x clipped to arena", c.x == 800.0 and c.y == 0.0) + check("clipped flag set", c.clipped) + let n = clipToArena(400.0, 300.0, 800.0, 600.0) + check("inside point unchanged", not n.clipped and n.x == 400.0 and n.y == 300.0) + +block: + echo "aimer 7: aim-bias corrector is deterministic and correct" + proc feed(a: var Aimer) = + var aim = TwinAim(active: true, bucket: 0, horizon: 10.0, dist: 100.0, + enemySpeed: 1.0, selfX: 0.0, selfY: 0.0, aimBearing: 0.0, + mixPt: (100.0, 0.0), resPt: (100.0, 0.0), + persPt: (100.0, 0.0)) + a.noteShot(aim, 100) + a.resolve(110, 100.0, 10.0) # realized bearing = atan2(10,100) + var a1 = initAimer() + var a2 = initAimer() + feed(a1) + feed(a2) + let expected = arctan2(10.0, 100.0) + check("bias offset equals the observed miss", + abs(a1.biasOffset(100.0, 1.0) - expected) < 1e-9, $a1.biasOffset(100.0, 1.0)) + check("bias is deterministic across identical runs", + a1.biasOffset(100.0, 1.0) == a2.biasOffset(100.0, 1.0)) + check("bias is zero for an untouched segment", a1.biasOffset(700.0, 7.0) == 0.0) + check("bias is clamped", abs(a1.biasOffset(100.0, 1.0)) <= MaxBias + 1e-9) + +block: + echo "aimer 8: no-spray cooldown" + check("tiny spread allows the fast cadence", cooldownTicks(0.001) == TinyCooldown) + check("wide spread forces the conservative cadence", + cooldownTicks(0.1) == NormalCooldown) + check("conservative cadence is at least 8 ticks", + NormalCooldown >= 8 and TinyCooldown < NormalCooldown) + +block: + echo "aimer 9: horizon-bucketed hedge trains online" + var a = initAimer() + # Mixture/residual predict far away, persistence predicts the realized spot: + # after enough scored shots the bucket must put most mass on persistence. + for i in 0 ..< 40: + let aim = TwinAim(active: true, bucket: 1, horizon: 12.0, dist: 200.0, + enemySpeed: 2.0, selfX: 0.0, selfY: 0.0, aimBearing: 0.0, + mixPt: (0.0, 0.0), resPt: (0.0, 0.0), persPt: (200.0, 0.0)) + a.noteShot(aim, 0) + a.resolve(12, 200.0, 0.0) + let w = a.bucketWeights(1) + check("persistence gains mass on consistent realized positions", + w[2] > w[0] and w[2] > w[1], $w) + check("bucket weights stay normalized", + abs(w[0] + w[1] + w[2] - 1.0) < 1e-9) + +echo "" +if failed == 0: echo "all aimer tests passed" +else: echo failed, " aimer test(s) FAILED"; quit(1) diff --git a/ChimeraBot_garage/tests/test_dodger.nim b/ChimeraBot_garage/tests/test_dodger.nim new file mode 100644 index 0000000..44dd343 --- /dev/null +++ b/ChimeraBot_garage/tests/test_dodger.nim @@ -0,0 +1,85 @@ +## Construction test for the Dodger archetype (tests/archetypes/Dodger). +## The bot's run loop contains no decision logic: it calls `dodgeDecision` and +## applies the result, so pinning the spec function's outputs on synthetic +## inputs pins the bot's behaviour by construction. Pure Nim, no Java. + +import std/[math] +import dodger_spec + +var failed = 0 +proc check(name: string, cond: bool, detail: string = "") = + if cond: echo " ok ", name + else: echo " FAIL ", name, " [", detail, "]"; inc failed + +proc approx(a, b: float64): bool = abs(a - b) < 1e-9 + +block: + echo "dodger 1: wave ETA" + let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0) + check("eta = dist/speed - elapsed", + approx(waveETA(w, 160.0, 0.0, 0), 10.0), $waveETA(w, 160.0, 0.0, 0)) + check("eta decreases one tick per tick", + approx(waveETA(w, 160.0, 0.0, 4), 6.0)) + check("eta negative once past", + waveETA(w, 160.0, 0.0, 20) < 0.0) + +block: + echo "dodger 2: far wave -> patrol" + let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0) + let c = dodgeDecision(w, DodgeOwn(x: 1600.0, y: 0.0, heading: 0.0), 0, + 800.0, 600.0, 1.0) + check("not dodging", not c.dodging) + check("patrol speed", approx(c.targetSpeed, PatrolSpeed)) + check("no turn", approx(c.turnRate, 0.0)) + check("strafe sign carried", approx(c.strafeSign, 1.0)) + +block: + echo "dodger 3: spent wave -> patrol" + let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 100, bulletSpeed: 16.0) + let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 0.0, heading: 0.0), 0, + 800.0, 600.0, -1.0) + check("not dodging", not c.dodging) + check("strafe sign retained", approx(c.strafeSign, -1.0)) + +block: + echo "dodger 4: close wave -> strafe perpendicular" + let w = DodgeWave(originX: 0.0, originY: 300.0, fireTick: 0, bulletSpeed: 16.0) + let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 0.0), 0, + 800.0, 600.0, 1.0) + check("dodging", c.dodging) + check("full throttle", approx(c.targetSpeed, StrafeSpeed)) + check("turns toward +90 bearing (clamped to 10)", approx(c.turnRate, 10.0), + $c.turnRate) + check("strafe sign +1", approx(c.strafeSign, 1.0)) + let c2 = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 90.0), 0, + 800.0, 600.0, 1.0) + check("already perpendicular -> no turn", approx(c2.turnRate, 0.0), $c2.turnRate) + +block: + echo "dodger 5: corner flip near a wall" + let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 0, bulletSpeed: 16.0) + check("nearWall true inside the band", nearWall(50.0, 300.0, 800.0, 600.0)) + check("nearWall false in the open", not nearWall(400.0, 300.0, 800.0, 600.0)) + let c = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 0, + 800.0, 600.0, 1.0) + check("strafe sign flipped", approx(c.strafeSign, -1.0), $c.strafeSign) + check("turns toward -90 bearing", approx(c.turnRate, -10.0), $c.turnRate) + let c2 = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 0, + 800.0, 600.0, -1.0) + check("flip is an involution on the sign", approx(c2.strafeSign, 1.0)) + +block: + echo "dodger 6: determinism" + let w = DodgeWave(originX: 10.0, originY: 20.0, fireTick: 3, bulletSpeed: 17.0) + let a = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7, + 800.0, 600.0, 1.0) + let b = dodgeDecision(w, DodgeOwn(x: 120.0, y: 40.0, heading: 33.0), 7, + 800.0, 600.0, 1.0) + check("identical inputs -> identical output", + a.turnRate == b.turnRate and a.targetSpeed == b.targetSpeed and + a.strafeSign == b.strafeSign and a.dodging == b.dodging) + check("reaction window is 14 ticks", ReactionTicks == 14.0) + +echo "" +if failed == 0: echo "all dodger tests passed" +else: echo failed, " dodger test(s) FAILED"; quit(1)