DevControlBot: an ELM gun, its geometric baseline, and an honest null result

Firing wired in behind a compile-time A/B switch (-d:baselineGun): both guns go
through the same predictAim() call and differ only by the learned correction, so
the measured difference is attributable. radar.nim now keeps the two most recent
scans (velocity, scan age, own displacement).

Measured over 20 recorded rounds each vs DrussGT, CassiusClay, Komarious and
Phoenix: the ELM gun LOSES to the geometric baseline on three of four opponents
(Phoenix 51.0% vs 99.5% hit rate). README has the table, the diagnosis and the
two in-game-only bugs measuring exposed (degrees/radians, and features whose
in-game range lies outside the corpus).
This commit is contained in:
2026-10-05 23:48:58 +02:00
parent 818bad50fd
commit dacb650692
6 changed files with 670 additions and 2 deletions
@@ -26,10 +26,12 @@
## viewer. It is compiled only with `-d:tfilDebug`; see README "Debug graphics".
##
## API: robocode_tankroyale_botapi 1.0.7 (the renamed tankroyale_botapi package).
import std/[os, sequtils]
import std/[math, os, sequtils, strutils]
import robocode_tankroyale_botapi
import modules/radar
import modules/tfil
import modules/ELM/elm_gun
import modules/ELM/elm_features
const MaxScannedEnemies* = 16 ## movers see every alive enemy; the radar feeds
## only what it scans, so this is a cap, not a limit
@@ -38,20 +40,39 @@ const EnemyStaleTicks* = 60 ## drop a scanned enemy not rescanned for this m
## ticks (~1s at 60Hz): a bot seen once would keep
## painting its heat in the field forever
# A/B switch, compile time: `-d:baselineGun` builds the geometric-only gun, the
# default build is the ELM gun. Both go through the same predictAim() call, so
# the two binaries differ by exactly the learned correction and nothing else —
# which is what makes the measured difference attributable.
const UseElm* = not defined(baselineGun)
const FireSlopDeg = 3.0'f64 ## fire inside this much gun error. The gun turns
## at most MAX_GUN_TURN_RATE, so a tighter slop
## just means waiting a tick for no gain: at any
## real range 3 deg is well under the hit radius.
type DevControlBot* = ref object of Bot
mover: TfilModule
tick: int
enemies: seq[EnemyInfo] ## fed by onScannedBot, cleared on round end
gun: ElmGun ## the ELM gun (or the geometric baseline, see UseElm)
shotsFired: int ## diagnostics, reset on round end
roundNo: int ## bumped on every RoundEnded, so the shot log can be
## joined to a recording round
proc newDevControlBot*(): DevControlBot =
result = DevControlBot()
result.mover = initTFIL() # movement is programmed -> body/turret/gun BLACK
result.gun = initElmGun() # the gun loads its exported weights here, once
setRadarColor(WHITE) # overwritten by initRadar() before the first tick
method onScannedBot*(bot: DevControlBot, e: ScannedBotEvent) =
onScan(e.x, e.y) # remembered; commandRadar() re-aims every tick
# (e.scannedBotId, schemas.nim:305, is the
# scanned bot's identity)
# ...and the full history the gun needs: this tick, the position, and where WE
# were when we saw it (own displacement since the scan is a model feature).
onScanFull(bot.tick, e.x, e.y, getX(), getY())
# ...and remembered for the movement: the heat field paints every enemy it
# knows about. One entry per id, refreshed in place, oldest dropped past the cap.
for i, ei in bot.enemies:
@@ -78,9 +99,37 @@ method onBulletHit*(bot: DevControlBot, e: BulletHitBotEvent) =
bot.mover.noteDamageDealt(e.damage)
method onRoundEnded*(bot: DevControlBot, e: RoundEndedEventForBot) =
inc bot.roundNo
bot.enemies = @[]
bot.shotsFired = 0
bot.mover.resetRound()
method buildBelief(bot: DevControlBot, power: float): GunBelief =
## Assemble what the gun is allowed to know. Everything here comes from our
## own state or from modules/radar.nim's scan history — there is no oracle.
let (vx, vy) = targetVelocity()
let age = scanAge(scanTick)
result.everScanned = haveLast and age >= 0
result.selfX = getX()
result.selfY = getY()
# The API speaks DEGREES everywhere (getDirection, normalizeRelativeAngle,
# setGunTurnRate); the model speaks radians (every angle in the corpus). This
# conversion is the whole difference between a gun that aims and one that
# sprays bullets into the walls.
result.selfHeading = degToRad(getDirection())
result.selfSpeed = getSpeed()
result.ownDisp = ownDisp(getX(), getY())
result.scanAge = age
result.scanGap = scanGap()
result.vx = vx
result.vy = vy
# dead-reckon: last seen position advanced by the estimated velocity
result.ex = lastScan.x + vx * age
result.ey = lastScan.y + vy * age
result.power = power
result.bulletSpeed = 20.0 - 3.0 * power
result.gunHeat = getGunHeat()
method ageEnemies(bot: DevControlBot) =
# heat field is only as good as the freshest scans; stale entries stay
# plausible-looking but poison the grid, so they go
@@ -93,6 +142,46 @@ method buildWorldState(bot: DevControlBot): WorldState =
arenaWidth: getArenaWidth().float, arenaHeight: getArenaHeight().float,
tick: bot.tick, enemies: bot.enemies)
## 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)
## lives entirely inside predictAim(). Order is the API's: set the gun turn rate,
## fire only when the gun is both COOLED (getGunHeat() == 0) and ON the aim, and
## do it before go() so the shot is part of this tick's intent.
proc computeGun(bot: DevControlBot) =
let belief = bot.buildBelief(FirePower)
let aim = bot.gun.predictAim(belief, FirePower, UseElm)
let baseAim = bot.gun.heuristicAim(belief, FirePower)
if aim.aim.isNaN:
setGunTurnRate(0.0)
return
when defined(gunDebug):
if bot.tick mod 20 == 0:
echo "[gun] t=", bot.tick, " self=(", getX(), ",", getY(), ") lastScan=(", lastScan.x, ",", lastScan.y,
") age=", scanAge(scanTick), ") aimDeg=", radToDeg(aim.aim),
" corr=", aim.correction, " gunDeg=", getGunDirection()
let err = normalizeRelativeAngle(radToDeg(aim.aim) - getGunDirection())
if abs(err) <= degToRad(FireSlopDeg):
if getGunHeat() == 0.0:
fire(FirePower)
inc bot.shotsFired
when defined(gunLog):
# One line per shot: what the gun THOUGHT. The truth (the aim error it
# actually made) is computed offline from the observer recording, which
# is the only place ground truth exists. Format:
# round,tick,predCorrection,baseAimDeg,finalAimDeg,gunDeg
let path = getEnv("ELM_GUN_LOG", "")
if path.len > 0:
let f = open(path, fmAppend)
defer: f.close()
f.write($bot.roundNo & "," & $bot.tick & "," & $aim.correction & "," &
$(radToDeg(baseAim)) & "," & $(radToDeg(aim.aim)) & "," &
$(getGunDirection()) & "," &
buildFeatures(belief).mapIt($it).join(" ") & "\n")
setGunTurnRate(0.0)
else:
setGunTurnRate(err)
method run*(bot: DevControlBot) =
initRadar() # once: radar + scan turn BLACK = programmed
while isRunning():
@@ -103,6 +192,7 @@ method run*(bot: DevControlBot) =
let (speed, turnRate) = bot.mover.computeMove(bot.buildWorldState())
setTargetSpeed(speed)
setTurnRate(turnRate)
bot.computeGun() # gun intent, also before go()
go()
inc bot.tick