ChimeraBot_garage: M7 twin gun — flight-horizon aiming, spread-based power, aim-bias corrector, Dodger archetype

This commit is contained in:
2026-10-07 08:44:37 +02:00
parent 53effb408c
commit 8bf7152512
16 changed files with 1274 additions and 1 deletions
@@ -0,0 +1,3 @@
@echo off
cd /d "%~dp0"
Dodger.exe 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"
}
@@ -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)
+13
View File
@@ -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" "$@"
@@ -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
+243
View File
@@ -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()
+169
View File
@@ -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()
+1
View File
@@ -1,2 +1,3 @@
--path:"../src/ChimeraBot"
--path:"../../common_libs"
--path:"archetypes/Dodger"
+149
View File
@@ -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)
+85
View File
@@ -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)