ChimeraBot_garage: M7.5 — virtual-gun tournament, Dodger-v2, discriminating bench

This commit is contained in:
2026-10-07 09:16:54 +02:00
parent 4c98333a3c
commit 5b48ac980c
12 changed files with 865 additions and 150 deletions
@@ -1,13 +1,11 @@
## Dodger — garage-local reactive archetype opponent (spec §12 Tier B; M7/G8).
## Dodger — garage-local reactive archetype opponent (spec §12 Tier B; M7.5/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.
## hit-rate bench, and (M7.5) a real opponent that fires back with a head-on gun.
##
## 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.
## events to `DodgeWave` / `GunCmd` and applies the results to the body and gun.
## It therefore behaves exactly as the documented spec function by construction.
import std/[math, os]
import robocode_tankroyale_botapi
@@ -20,13 +18,19 @@ type
strafeSign: float64
prevEnergy: float64
haveEnemy: bool
enemyX, enemyY: float64
gunHeat: float64
proc newDodger(): Dodger =
Dodger(strafeSign: 1.0)
Dodger(strafeSign: 1.0,
wave: DodgeWave(originX: 0.0, originY: 0.0, fireTick: -1000,
bulletSpeed: 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.
## wave from its position at fire time. Always remember the enemy for the gun.
bot.enemyX = e.x
bot.enemyY = e.y
if bot.haveEnemy:
let drop = bot.prevEnergy - e.energy
if drop >= 0.1 - 1e-9 and drop <= 3.0 + 1e-9:
@@ -37,8 +41,8 @@ method onScannedBot*(bot: Dodger, e: ScannedBotEvent) =
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.
## The wave already connected: switch strafe side so the next wave is met from
## the other direction.
bot.strafeSign = -bot.strafeSign
method run*(bot: Dodger) =
@@ -52,7 +56,15 @@ method run*(bot: Dodger) =
bot.strafeSign = cmd.strafeSign
setTurnRate(cmd.turnRate)
setTargetSpeed(cmd.targetSpeed)
setGunTurnRate(0.0)
# Head-on gun: fire back. gunHeat is the API's own reported heat.
if bot.haveEnemy:
let g = gunDecision(bot.enemyX, bot.enemyY, getX(), getY(),
getGunDirection(), getGunHeat())
setGunTurnRate(g.turnRate)
if g.fire > 0.0:
discard setFire(g.fire)
else:
setGunTurnRate(0.0)
setRadarTurnRate(45.0)
go()
inc bot.tick
@@ -1,29 +1,52 @@
## Dodger spec function — the documented, unit-tested behaviour of the reactive
## `Dodger` archetype (docs/chimera-spec.md §12 Tier B; M7/G8).
## `Dodger` archetype (docs/chimera-spec.md §12 Tier B; M7.5/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.
## the G8 hit-rate bench. When it detects an enemy bullet (an energy drop in
## `onScannedBot`) it starts a wave; while the wavefront is within
## `ReactionTicks` it strafes **perpendicular to the wave bearing**, flipping the
## strafe side when it would otherwise drive into a wall. Two M7.5 upgrades make
## it a *real* dodger:
##
## Pure and deterministic: no RNG, no I/O, no clock.
## * when **not** dodging it steers toward the arena centre (it no longer
## patrols straight into its opponent), and a small `CenterPull` bias keeps
## the perpendicular strafe in open space instead of parking in a corner;
## * a **documented seed** (`DefaultSeed`) makes the strafe direction reverse
## on a deterministic pseudo-random schedule, so the path is not periodic.
##
## It also carries a **head-on gun** (`gunDecision`) so the archetype fights
## back instead of being a target dummy.
##
## The bot's run loop contains **no decision logic of its own** — it calls
## `dodgeDecision` / `gunDecision` and applies the results, so the bot's
## behaviour *is* these functions by construction. `test_dodger.nim` pins the
## outputs on synthetic inputs and, for the dodge rate, on an offline physics
## simulation: the bar is a **dodge rate >= 60%** of incoming head-on-gun shots.
##
## Pure and deterministic: no wall-clock, no global RNG, no I/O. The only
## "randomness" is the seedable 64-bit hash below, so a given (seed, tick)
## always yields the same decision.
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
PatrolSpeed* = 8.0 ## full throttle while patrolling too (never a sitting duck)
WallMargin* = 80.0 ## "would drive into a wall" band
CenterPull* = 0.2 ## blend toward the arena centre (0 = pure perpendicular)
SwitchTicks* = 20 ## seeded strafe reversal period, in ticks
DefaultSeed* = 0x5EED1307'u64 ## documented seed for the strafe jitter
GunPower* = 1.5 ## the archetype's head-on gun power
GunFireSlop* = 2.0 ## deg of alignment required to fire
GunMaxTurn* = 20.0 ## deg/tick gun slew (physics maximum)
type
DodgeWave* = object
## A wavefront: the enemy position at fire time, the fire tick, and the
## bullet speed (`20 - 3*power`, physics.bulletSpeed).
## bullet speed (`20 - 3*power`, physics.bulletSpeed). `fireTick == -1000`
## is the "no wave yet" sentinel.
originX*, originY*: float64
fireTick*: int
bulletSpeed*: float64
@@ -37,38 +60,83 @@ type
strafeSign*: float64 ## +1 / -1, carried to the next tick (hysteresis)
dodging*: bool
GunCmd* = object
turnRate*: float64 ## deg/tick gun turn command
fire*: float64 ## >0 => fire at this power this tick
aimed*: 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 hash64(seed: uint64, a: int): uint64 =
## SplitMix64-style avalanche: deterministic, seedable, no state.
var h = seed xor (uint64(a) * 0x9E3779B97F4A7C15'u64)
h = (h xor (h shr 30)) * 0xBF58476D1CE4E5B9'u64
h = (h xor (h shr 27)) * 0x94D049BB133111EB'u64
h xor (h shr 31)
proc seededBit*(seed: uint64, i: int): bool =
(hash64(seed, i) and 1) == 1
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").
## Pinned when inside `WallMargin` of any wall.
x < WallMargin or x > arenaW - WallMargin or
y < WallMargin or y > arenaH - WallMargin
proc intoWall(heading, x, y, arenaW, arenaH: float64): bool =
## True when moving along `heading` (deg) pushes us further into the wall we
## are already near.
let hx = cos(degToRad(heading))
let hy = sin(degToRad(heading))
(x < WallMargin and hx < 0.0) or (x > arenaW - WallMargin and hx > 0.0) or
(y < WallMargin and hy < 0.0) or (y > arenaH - WallMargin and hy > 0.0)
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
arenaW, arenaH, prevSign: float64,
seed: uint64 = DefaultSeed): DodgeCmd =
## The documented spec function. While a wave is within `ReactionTicks` the bot
## strafes perpendicular to the wave bearing (flipping away from walls); when
## no wave threatens it drives toward the arena centre. A small centre-pull
## bias keeps the strafe in open space, and the seeded reversal breaks up the
## periodic path.
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 dodging = eta > 0.0 and eta <= ReactionTicks
var sign = prevSign
if SwitchTicks > 0 and (tick mod SwitchTicks) == 0 and
seededBit(seed, tick div SwitchTicks):
sign = -sign
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
let centerBearing = arctan2(arenaH * 0.5 - own.y,
arenaW * 0.5 - own.x) * 180.0 / PI
var desired: float64
if dodging:
var perp = bearing + 90.0 * sign
if intoWall(perp, own.x, own.y, arenaW, arenaH):
sign = -sign
perp = bearing + 90.0 * sign
desired = perp
else:
desired = centerBearing
desired = desired + CenterPull * wrap180(centerBearing - desired)
result.strafeSign = sign
result.dodging = dodging
result.turnRate = clamp(wrap180(desired - own.heading), -10.0, 10.0)
result.targetSpeed = if dodging: StrafeSpeed else: PatrolSpeed
proc gunDecision*(ex, ey, sx, sy, gunHeading, gunHeat: float64,
power = GunPower): GunCmd =
## The archetype's head-on gun. Slew toward the enemy's current position and
## fire at `power` once aligned (within `GunFireSlop`) and cold. Head-on only:
## the archetype exists to dodge, not to lead.
let bearing = arctan2(ey - sy, ex - sx) * 180.0 / PI
let err = wrap180(bearing - gunHeading)
result.turnRate = clamp(err, -GunMaxTurn, GunMaxTurn)
result.aimed = abs(err) <= GunFireSlop
result.fire = if result.aimed and gunHeat <= 0.0: power else: 0.0
+82 -47
View File
@@ -1,15 +1,19 @@
## 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.
## G8 OFFLINE BENCH (M7.5) — virtual-gun tournament vs the single guns.
## Pure Nim, no Java. Source of truth: docs/chimera-spec.md G8 (M7 + M7.5).
##
## 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
## SYNTHESIZED Dodger-v2 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:
## bullet each aim policy 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.
## * TWIN — `chimera/aimer.nim`'s flight-horizon fused aim + spread power;
## * VGUN — `chimera/virtual_guns.nim`'s tournament: every sampled tick the
## TWIN/ELM/HEAD-ON candidates each launch a virtual bullet, the
## realized outcomes score them (tau=200 EMA), and VGUN fires the
## argmax under 0.1 hysteresis.
##
## 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
@@ -17,12 +21,13 @@
##
## Run: `nim c -r --hints:off -d:release tests/bench_g8.nim`
import std/[math, os, strutils, tables, algorithm, times, sequtils]
import std/[math, os, strutils, tables, algorithm, sequtils]
import chimera/dsl
import chimera/twinsim
import chimera/residual
import chimera/aimer
import chimera/physics
import chimera/virtual_guns
import dodger_spec
const
@@ -35,7 +40,7 @@ const
type
Policy = enum
pHeadOn, pElm, pTwin
pHeadOn, pElm, pTwin, pVgun
Tally = object
hits, shots: int
@@ -77,7 +82,8 @@ proc simulateHit(sx, sy, bearing, power: float64, originTick: int,
false
proc evalRecord(rec: Record, kernels: seq[Kernel],
arenaW, arenaH: float64): Table[Policy, Tally] =
arenaW, arenaH: float64,
v: var VirtualGunSet): 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
@@ -85,8 +91,15 @@ proc evalRecord(rec: Record, kernels: seq[Kernel],
# per-origin aimer would never learn the bucket weights and would misrepresent
# the twin gun.
var a = initAimer()
# The tournament persists PER OPPONENT (across the opponent's replay files) —
# that is what "per opponent with exponential forgetting" means. Only the
# in-flight virtual bullets are cleared at a record boundary.
v.bullets.setLen(0)
var n = 0
for rt in rps:
# Advance/resolve the live virtual bullets every tick (that is how the
# tournament scores realized outcomes), independent of the sampling stride.
v.vgTick(rt.ex, rt.ey, HitRadius, arenaW, arenaH)
if rt.tick mod Stride != 0: continue
if n >= MaxOrigins: break
inc n
@@ -101,18 +114,29 @@ proc evalRecord(rec: Record, kernels: seq[Kernel],
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)
let twinBearing = if aim.active: aim.aimBearing else: elm
let twinPower = if aim.active: aim.power else: ElmPower
# Launch the three candidates, then let the tournament pick.
v.launchVirtual(vgTwin, rt.ox, rt.oy, twinBearing, twinPower)
v.launchVirtual(vgElm, rt.ox, rt.oy, elm, ElmPower)
v.launchVirtual(vgHeadOn, rt.ox, rt.oy, head, ElmPower)
let chosen = v.selectGun()
let (vb, vp) =
case chosen
of vgTwin: (twinBearing, twinPower)
of vgElm: (elm, ElmPower)
of vgHeadOn: (head, 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))]:
(pTwin, twinBearing, twinPower),
(pVgun, vb, vp)]:
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.
## A deterministic Dodger-v2 record: our bot sits at (600,300); a wave is fired
## every 12 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
@@ -165,76 +189,87 @@ proc main() =
var rows: seq[string]
var total: Table[Policy, Tally]
var winOverBest = 0
var winOverElm = 0
var winOverHead = 0
let movers = ["Crazy", "SpinBot", "VelociBot", "Walls", "Dodger"]
var nOpp = 0
echo "opponent twin% elm% head% n"
echo "opponent twin% elm% head% vgun% n"
for opp in opps:
var t: Table[Policy, Tally]
var v = initVirtualGuns() # one tournament per opponent
if opp == "Dodger":
t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0)
t = evalRecord(synthesizeDodger(kernels), kernels, 800.0, 600.0, v)
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))
addInto(t, evalRecord(loadRecord(f), kernels, 800.0, 600.0, v))
inc used
let tw = t.getOrDefault(pTwin)
let el = t.getOrDefault(pElm)
let ho = t.getOrDefault(pHeadOn)
let vg = t.getOrDefault(pVgun)
addInto(total, t)
inc nOpp
if tw.hits >= el.hits: inc winOverElm
if tw.hits >= ho.hits and opp in movers: inc winOverHead
# vgun >= the best single gun on this opponent
if vg.hits >= max(tw.hits, max(el.hits, ho.hits)): inc winOverBest
if vg.hits >= el.hits and opp in movers: inc winOverElm
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)
align(formatFloat(vg.hitRate, ffDecimal, 1), 7),
align($vg.shots, 6)
rows.add "| " & opp & " | " & formatFloat(tw.hitRate, ffDecimal, 1) & " | " &
formatFloat(el.hitRate, ffDecimal, 1) & " | " &
formatFloat(ho.hitRate, ffDecimal, 1) & " | " & $tw.shots & " |"
formatFloat(ho.hitRate, ffDecimal, 1) & " | " &
formatFloat(vg.hitRate, ffDecimal, 1) & " | " & $vg.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,
let passBest = winOverBest >= 6
let passElm = winOverElm == movers.len
let verdict = if passBest and passElm: "PASS" else: "FAIL"
echo "\nG8.5 offline: vgun >= best single gun on ", winOverBest, "/", nOpp,
" (bar >= 6); vgun >= ELM-base on ", winOverElm, "/", 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), "%"
"% head ", formatFloat(total[pHeadOn].hitRate, ffDecimal, 1),
"% vgun ", formatFloat(total[pVgun].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"
var md = "# G8.5 offline hit-rate bench (M7.5, virtual-gun tournament)\n\n"
md.add "Replayed archived trajectories (`" & dir & "`) + a synthesized " &
"Dodger-v2; hit = bullet passes within " &
formatFloat(HitRadius, ffDecimal, 0) &
" units of the realized enemy position on its flight. Aim slew/cadence " &
"abstracted. Generated by `tests/bench_g8.nim`.\n\n"
md.add "| opponent | twin % | ELM % | head-on % | vgun % | 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**G8.5 offline bar: vgun >= max(twin, ELM-base, head-on) on >= 6/9 " &
"opponents AND vgun >= ELM-base on all movers (Crazy, SpinBot, " &
"VelociBot, Walls, Dodger).** Result: vgun >= best single gun on " &
$winOverBest & "/" & $nOpp & "; vgun >= ELM-base on " & $winOverElm &
"/" & $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 " &
md.add "* `VGUN` = `chimera/virtual_guns.nim`: per-tick virtual bullets for " &
"{TWIN, ELM, HEAD-ON}, a per-shot hit-rate EMA (tau=100) plus a " &
"damage-weighted accumulator with tau=200 exponential forgetting, " &
"argmax fired under 0.1 hysteresis. Classic Robocode Virtual Guns " &
"pattern (https://robowiki.net/wiki/Virtual_Guns).\n"
md.add "* `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.\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"
md.add "* The synthesized Dodger is Dodger-v2 (`tests/archetypes/Dodger`): " &
"wave-based perpendicular strafe, centre-pull, seeded reversals. It " &
"fires a wave every 12 ticks; a real battle adds shooter motion. Live " &
"results (`m7_5_g8_live.md`) are the reality check.\n"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8.md"
createDir(art.parentDir)
writeFile(art, md)
echo "Artifact: ", art
+68 -38
View File
@@ -1,11 +1,17 @@
## 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)
## G8.5 LIVE BENCH — virtual-gun tournament vs twin vs ELM vs inert.
## LIVE, Java required. FOUR 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 — `-d:chimeraNoVguns` (M7 influence-gated twin/ELM path)
## * vgun — default (M7.5 virtual-gun tournament: TWIN/ELM/HEAD-ON)
## 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.
## Dodger-v2 archetype. Reports win rate + score margin; the G7 no-regression read
## is vgun >= inert (win rate) on every opponent, stated plainly when it fails.
##
## The **discrimination test** is the Dodger-v2 row: M7 found the three arms
## ~equal there (~2660 each), i.e. the opponent was too weak to separate them.
## M7.5 reports the four Dodger margins and states plainly whether they now
## differ.
##
## Run: `nim c -r --hints:off -d:release tests/bench_g8_live.nim`
@@ -29,7 +35,8 @@ type
const Arms = [
Arm(tag: "inert", name: "ChimeraInert", defines: @["-d:chimeraInert"]),
Arm(tag: "elm", name: "ChimeraElm", defines: @["-d:chimeraNoTwinGun"]),
Arm(tag: "twin", name: "ChimeraTwin", defines: @[]),
Arm(tag: "twin", name: "ChimeraTwin", defines: @["-d:chimeraNoVguns"]),
Arm(tag: "vgun", name: "ChimeraVgun", defines: @[]),
]
proc parseOutcome(log, ourName: string): Outcome =
@@ -85,10 +92,10 @@ proc margin(o: Outcome): float64 = o.ourScore - o.oppScore
proc main() =
guardSkip()
echo "[G8-live] staging 3 arms..."
echo "[G8.5-live] staging 4 arms..."
var bots = initTable[string, string]()
for a in Arms:
bots[a.tag] = stageBot("g8_" & a.tag, a.defines, a.name)
bots[a.tag] = stageBot("g85_" & a.tag, a.defines, a.name)
let opps = sorted(toSeq(Expected.keys)) & @["Dodger"]
var suite = initTable[string, Table[string, Outcome]]() # arm -> opp -> out
@@ -107,60 +114,83 @@ proc main() =
" 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"
echo "\n=== G8.5 live suite (", Rounds, " rounds/arm/opponent) ==="
echo "Opponent elmW% elmM twinW% twinM vgunW% vgunM 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 "|---|---:|---:|---:|---:|---:|---:|"
lines.add "# G8.5 live bench (M7.5 virtual-gun tournament)\n"
lines.add "Four arms from the SAME tree: inert (`-d:chimeraInert`), elm " &
"(`-d:chimeraNoTwinGun`), twin (`-d:chimeraNoVguns`), vgun (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 | vgun W% | vgun margin | inert W% | inert margin |"
lines.add "|---|---:|---:|---:|---:|---:|---:|---:|---:|"
for opp in opps:
let e = suite["elm"].getOrDefault(opp)
let t = suite["twin"].getOrDefault(opp)
let v = suite["vgun"].getOrDefault(opp)
let i = suite["inert"].getOrDefault(opp)
if t.rounds > 0 and i.rounds > 0 and t.wins < i.wins:
if v.rounds > 0 and i.rounds > 0 and v.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(v), ffDecimal, 0), 7),
align(formatFloat(margin(v), 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(v), ffDecimal, 1) & " | " &
formatFloat(margin(v), ffDecimal, 1) & " | " &
formatFloat(winRate(i), ffDecimal, 1) & " | " &
formatFloat(margin(i), ffDecimal, 1) & " |"
# suite totals
var te, tt, ti: Outcome
var totals = initTable[string, 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): " &
for arm in Arms:
let o = suite[arm.tag].getOrDefault(opp)
totals.mgetOrPut(arm.tag, Outcome()).rounds += o.rounds
totals[arm.tag].wins += o.wins
totals[arm.tag].ourScore += o.ourScore
totals[arm.tag].oppScore += o.oppScore
var totLine = "Totals: "
for arm in Arms:
let t = totals[arm.tag]
totLine.add arm.tag & " " & formatFloat(winRate(t), ffDecimal, 1) &
"% (m " & formatFloat(margin(t), ffDecimal, 1) & ") "
echo "\n", totLine
lines.add "\n**" & totLine & "**"
# Discrimination read on the Dodger-v2 row.
var dm = ""
var dmin = Inf
var dmax = -Inf
for arm in Arms:
let o = suite[arm.tag].getOrDefault("Dodger")
dm.add arm.tag & " " & formatFloat(margin(o), ffDecimal, 1) & " "
dmin = min(dmin, margin(o))
dmax = max(dmax, margin(o))
let spread = dmax - dmin
echo "Dodger-v2 margins: ", dm, " spread=", formatFloat(spread, ffDecimal, 1)
lines.add "\n**Discrimination test (Dodger-v2 row).** Margins: " & dm &
"spread " & formatFloat(spread, ffDecimal, 1) & ". " &
(if spread >= 500.0:
"The arms DIFFER materially against the upgraded Dodger."
else:
"The arms remain ~equal against the upgraded Dodger — stated plainly as a finding.")
lines.add "\n**G7 no-regression (vgun >= inert win-rate on every opponent): " &
(if noRegress: "PASS" else: "**FAIL** on " & regress.join(", ")) & ".**"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_g8_live.md"
let art = currentSourcePath().parentDir.parentDir / "benchmarks" / "m7_5_g8_live.md"
createDir(art.parentDir)
writeFile(art, lines.join("\n") & "\n")
echo "\nArtifact: ", art
+131 -22
View File
@@ -1,9 +1,20 @@
## 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.
## Construction + behaviour tests for the Dodger archetype
## (tests/archetypes/Dodger; M7.5/G8).
##
## The bot's run loop contains no decision logic: it calls `dodgeDecision` /
## `gunDecision` and applies the result, so pinning the spec functions' outputs on
## synthetic inputs pins the bot's behaviour by construction. The last two blocks
## go further:
##
## * a **dodge-rate matrix** runs the documented decision through the physics
## mirror and fires head-on-gun shots at the resulting trajectory, asserting
## a dodge rate >= 60% for every (shooter, start) pair;
## * a **fire-back** check asserts the head-on gun fires when aligned and cold.
##
## Pure Nim, no Java.
import std/[math]
import std/[math, strutils]
import chimera/physics
import dodger_spec
var failed = 0
@@ -24,19 +35,20 @@ block:
waveETA(w, 160.0, 0.0, 20) < 0.0)
block:
echo "dodger 2: far wave -> patrol"
echo "dodger 2: far wave -> centre patrol (never charge the gun line)"
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,
let c = dodgeDecision(w, DodgeOwn(x: 1600.0, y: 0.0, heading: 0.0), 7,
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("turns toward the centre (not straight)", abs(c.turnRate) > 0.0,
$c.turnRate)
check("strafe sign carried", approx(c.strafeSign, 1.0))
block:
echo "dodger 3: spent wave -> patrol"
echo "dodger 3: spent wave -> centre patrol, sign retained"
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,
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, -1.0)
check("not dodging", not c.dodging)
check("strafe sign retained", approx(c.strafeSign, -1.0))
@@ -44,32 +56,36 @@ block:
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,
let c = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 0.0), 7,
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,
let c2 = dodgeDecision(w, DodgeOwn(x: 160.0, y: 300.0, heading: 90.0), 7,
800.0, 600.0, 1.0)
check("already perpendicular -> no turn", approx(c2.turnRate, 0.0), $c2.turnRate)
check("already perpendicular: centre-pull turns back toward the centre",
approx(c2.turnRate, -10.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)
let w = DodgeWave(originX: 0.0, originY: 0.0, fireTick: 5, 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))
# strafing SOUTH (into the bottom wall we are near) is flipped to NORTH
let c = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, -1.0)
check("wall-ward strafe sign flipped", approx(c.strafeSign, 1.0), $c.strafeSign)
check("turns toward +90 (away from the wall)", approx(c.turnRate, 10.0),
$c.turnRate)
# strafing NORTH (away from the wall) needs no flip
let c2 = dodgeDecision(w, DodgeOwn(x: 50.0, y: 0.0, heading: 0.0), 7,
800.0, 600.0, 1.0)
check("away-from-wall strafe is kept", approx(c2.strafeSign, 1.0))
block:
echo "dodger 6: determinism"
echo "dodger 6: determinism + documented seed"
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)
@@ -79,6 +95,99 @@ block:
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)
check("seed is documented", DefaultSeed == 0x5EED1307'u64)
check("seededBit is deterministic",
seededBit(DefaultSeed, 123) == seededBit(DefaultSeed, 123))
# the seed must actually vary across reversal periods, else it is pointless
var varied = false
for i in 0 ..< 8:
if seededBit(DefaultSeed, i) != seededBit(DefaultSeed, i + 1): varied = true
check("seededBit varies across periods", varied)
# ── offline dodge-rate matrix ───────────────────────────────────────────────
# Fire head-on-gun shots (no lead) at the Dodger's trajectory; the dodge rate is
# the fraction that miss (the bullet never comes within 20 units of the bot).
# Reproduces the archetype by running `dodgeDecision` + the physics mirror.
proc dodgeRate(shooterX, shooterY, startX, startY: float64,
ticks = 1400, stride = 4): float64 =
const W = 800.0
const H = 600.0
const HitR = 20.0
var ex = startX
var ey = startY
var ehead = 0.0
var espeed = 0.0
var sign = 1.0
var wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: -1000,
bulletSpeed: 14.0)
var pos: seq[tuple[x, y: float64]]
for tick in 1 .. ticks:
if tick mod 12 == 0:
wave = DodgeWave(originX: shooterX, originY: shooterY, fireTick: tick,
bulletSpeed: 14.0)
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)
pos.add (ex, ey)
var hits = 0
var n = 0
for i in countup(0, ticks - 1, stride):
let e = pos[i]
let bearing = arctan2(e.y - shooterY, e.x - shooterX)
var bx = shooterX
var by = shooterY
var didHit = false
for h in 1 .. 80:
bx += 14.0 * cos(bearing)
by += 14.0 * sin(bearing)
if bx < 0.0 or bx > W or by < 0.0 or by > H: break
let k = i + h
if k < pos.len and hypot(bx - pos[k].x, by - pos[k].y) <= HitR:
didHit = true
break
if didHit: inc hits
inc n
100.0 - 100.0 * float(hits) / float(n)
block:
echo "dodger 7: offline dodge-rate matrix (bar >= 60% vs head-on)"
let cases = [
(shooterX: 600.0, shooterY: 300.0, startX: 200.0, startY: 300.0),
(shooterX: 400.0, shooterY: 300.0, startX: 700.0, startY: 150.0),
(shooterX: 200.0, shooterY: 300.0, startX: 600.0, startY: 300.0),
(shooterX: 400.0, shooterY: 400.0, startX: 100.0, startY: 100.0),
(shooterX: 500.0, shooterY: 200.0, startX: 150.0, startY: 450.0),
]
for c in cases:
let d = dodgeRate(c.shooterX, c.shooterY, c.startX, c.startY)
check("dodge >= 60% (shooter " & $c.shooterX & "," & $c.shooterY & ")",
d >= 60.0, formatFloat(d, ffDecimal, 1) & "%")
echo " shooter(", c.shooterX, ",", c.shooterY, ") start(",
c.startX, ",", c.startY, ") dodge=", formatFloat(d, ffDecimal, 1), "%"
block:
echo "dodger 8: fires back (head-on gun)"
let aligned = gunDecision(ex = 100.0, ey = 0.0, sx = 0.0, sy = 0.0,
gunHeading = 0.0, gunHeat = 0.0)
check("aligned + cold -> fire", aligned.fire > 0.0, $aligned.fire)
check("aimed flag set", aligned.aimed)
let hot = gunDecision(100.0, 0.0, 0.0, 0.0, 0.0, 1.0)
check("aligned but hot -> no fire", hot.fire == 0.0)
let mis = gunDecision(0.0, 100.0, 0.0, 0.0, 0.0, 0.0)
check("90 deg off -> no fire, slews", mis.fire == 0.0 and mis.turnRate > 0.0)
# a short offline exchange: the gun fires repeatedly when it stays aligned
var fired = 0
var ghead = 0.0
for tick in 1 .. 60:
let g = gunDecision(100.0, 0.0, 0.0, 0.0, ghead, 0.0)
ghead = wrap180(ghead + limitTurnRate(g.turnRate, 0.0))
if g.fire > 0.0: inc fired
check("fires more than once in a 60-tick exchange", fired >= 2, $fired)
echo ""
if failed == 0: echo "all dodger tests passed"
@@ -0,0 +1,147 @@
## Tier A tests for the CHIMERA virtual-gun tournament
## (chimera/virtual_guns.nim, spec G8 / M7.5). Pure Nim, no Java.
## Run: from ChimeraBot_garage, `nimble test` (and once with
## `-d:chimeraNoVguns` to prove the kill switch compiles).
##
## Covers the four stated concerns: EMA scoring, hysteresis, determinism and the
## virtual-bullet mechanics, plus the kill-switch compile.
import std/math
import chimera/virtual_guns
var failed = 0
proc approx(a, b: float64): bool = abs(a - b) < 1e-9
proc check(name: string, cond: bool, detail: string = "") =
if cond: echo " ok ", name
else: echo " FAIL ", name, " [", detail, "]"; inc failed
# The kill switch must track the compile define. This file is also compiled with
# `-d:chimeraNoVguns` in the nimble task, so both branches are exercised.
when defined(chimeraNoVguns):
static: doAssert NoVguns
else:
static: doAssert not NoVguns
proc driveTo(v: var VirtualGunSet, g: VGun, density: float64, n = 400) =
## Drive `g`'s EMA toward a hit density in [0,1]. The hits are interleaved
## (37 is coprime with 100) so the EMA settles on the density rather than on
## the last run of a clustered pattern.
let target = int(density * 100.0)
for i in 0 ..< n:
v.observeShot(g, ((i * 37) mod 100) < target, 2.0)
block:
echo "vguns 1: EMA scoring (hit/miss)"
var v = initVirtualGuns()
check("no shots -> EMA 0", v.emaOf(vgTwin) == 0.0)
for i in 0 ..< 400: v.observeShot(vgTwin, true, 2.0)
check("all hits -> EMA near 1", v.emaOf(vgTwin) > 0.95, $v.emaOf(vgTwin))
for i in 0 ..< 400: v.observeShot(vgTwin, false, 2.0)
check("switched to misses -> EMA near 0", v.emaOf(vgTwin) < 0.05, $v.emaOf(vgTwin))
check("shot counter", v.shotsOf(vgTwin) == 800, $v.shotsOf(vgTwin))
# a hit must raise the EMA, a miss must lower it
var w = initVirtualGuns()
driveTo(w, vgElm, 0.5)
let before = w.emaOf(vgElm)
w.observeShot(vgElm, true, 2.0)
let afterHit = w.emaOf(vgElm)
check("a hit raises the EMA", afterHit > before)
w.observeShot(vgElm, false, 2.0)
check("a miss lowers the EMA", w.emaOf(vgElm) < afterHit)
block:
echo "vguns 2: damage-weighted accumulator"
var v = initVirtualGuns()
# same hit count, different power: the accumulator must reward damage.
for i in 0 ..< 50: v.observeShot(vgTwin, true, 3.0)
for i in 0 ..< 50: v.observeShot(vgElm, true, 0.5)
check("hit-rate EMA ties (same hit count)", approx(v.emaOf(vgTwin), v.emaOf(vgElm)))
check("damage accumulator favours the heavier gun",
v.decayedRate(vgTwin) > v.decayedRate(vgElm),
$v.decayedRate(vgTwin) & " vs " & $v.decayedRate(vgElm))
# 3.0 -> 4*3 + 2*2 = 16 damage; 0.5 -> 2.0
check("accumulator equals damage per shot",
abs(v.decayedRate(vgTwin) - 16.0) < 1e-9, $v.decayedRate(vgTwin))
block:
echo "vguns 3: hysteresis (0.1 EMA margin)"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.50)
discard v.selectGun() # make twin the incumbent
driveTo(v, vgElm, 0.55) # elm now leads, but only by ~0.05
check("incumbent twin kept while the rival leads by < 0.1",
v.selectGun() == vgTwin, $v.emaOf(vgTwin) & "/" & $v.emaOf(vgElm))
var w = initVirtualGuns()
driveTo(w, vgTwin, 0.50)
driveTo(w, vgElm, 0.70)
discard w.selectGun()
check("rival leading by > 0.1 switches to elm", w.selectGun() == vgElm)
# and the switch is sticky: once elm, a 0.05 lead does not hand it back
var u = initVirtualGuns()
driveTo(u, vgTwin, 0.70)
driveTo(u, vgElm, 0.75)
discard u.selectGun()
# first selection is whichever is best at that moment; assert the margin logic
let s1 = u.selectGun()
let s2 = u.selectGun()
check("selection is stable across repeated calls", s1 == s2)
block:
echo "vguns 4: twin influence gate"
var v = initVirtualGuns()
driveTo(v, vgTwin, 0.9)
driveTo(v, vgElm, 0.1)
discard v.selectGun() # incumbent twin
check("twin eligible -> twin chosen", v.selectGun(twinEligible = true) == vgTwin)
check("twin ineligible -> falls to the best legal gun",
v.selectGun(twinEligible = false) != vgTwin)
block:
echo "vguns 5: virtual-bullet mechanics"
var v = initVirtualGuns()
# head-on east at power 2 -> speed 14. Enemy at (14,0): the first step hits.
v.launchVirtual(vgHeadOn, 0.0, 0.0, 0.0, 2.0)
v.vgTick(14.0, 0.0, 20.0, 800.0, 600.0)
check("a hit resolves and scores", v.shotsOf(vgHeadOn) == 1 and v.emaOf(vgHeadOn) > 0.0)
check("no live bullets left after a hit", v.bullets.len == 0)
# a bullet aimed away from the enemy leaves the arena -> a scored miss
var w = initVirtualGuns()
w.launchVirtual(vgElm, 0.0, 0.0, PI, 2.0) # west, straight out of the arena
w.vgTick(500.0, 500.0, 20.0, 800.0, 600.0)
check("arena exit resolves as a miss", w.shotsOf(vgElm) == 1 and w.emaOf(vgElm) == 0.0)
# forgetting decays the accumulator but not the accumulated damage average
var x = initVirtualGuns()
for i in 0 ..< 10: x.observeShot(vgTwin, true, 2.0)
let r0 = x.decayedRate(vgTwin)
for i in 0 ..< 200: x.forgetTick()
check("forgetting lowers the accumulator weight",
x.score[vgTwin].weight < 5.0, $x.score[vgTwin].weight)
block:
echo "vguns 6: determinism"
var a = initVirtualGuns()
var b = initVirtualGuns()
for i in 0 ..< 120:
let hitA = (i mod 3) != 0
let hitB = (i mod 3) != 0
a.observeShot(vgTwin, hitA, 1.5)
b.observeShot(vgTwin, hitB, 1.5)
a.observeShot(vgElm, (i mod 5) == 0, 2.0)
b.observeShot(vgElm, (i mod 5) == 0, 2.0)
check("identical sequences -> identical EMAs",
a.emaOf(vgTwin) == b.emaOf(vgTwin) and a.emaOf(vgElm) == b.emaOf(vgElm))
check("identical sequences -> identical selection", a.selectGun() == b.selectGun())
check("gun names are stable", vgTwin.gunName() == "twin" and
vgElm.gunName() == "elm" and vgHeadOn.gunName() == "headon")
block:
echo "vguns 7: reset"
var v = initVirtualGuns()
for i in 0 ..< 30: v.observeShot(vgTwin, true, 2.0)
v.resetVguns()
check("reset clears the scores", v.emaOf(vgTwin) == 0.0 and
v.shotsOf(vgTwin) == 0)
echo ""
if failed == 0: echo "all virtual-gun tests passed"
else: echo failed, " virtual-gun test(s) FAILED"; quit(1)