Rewrite elm_features.nim as a 32-D enemy-motion vector (7 scan-to-scan displacement legs, speed stats, heading/turn/curvature, plus the single-frame geometry). Add a WinCap=8 scan buffer to radar.nim and feed it through buildBelief. elm_gun.nim now uses the physical bullet speed for the feature (was the power*10 corpus artifact) and applies the trained correction only when |correction| > GATE_TAU; below it the gun keeps the exact geometric aim. Retrain and export weights (H=256, gate_tau=0.1).
231 lines
11 KiB
Nim
231 lines
11 KiB
Nim
## DevControlBot — control skeleton: boots, drives the radar every tick and keeps
|
|
## itself alive with the TFIL survival movement. It never fires.
|
|
##
|
|
## Team convention: white means "not programmed yet". Each module claims its own
|
|
## colours when its init runs, and nothing paints white after that: initTFIL()
|
|
## (constructor) paints body, turret and gun BLACK — movement is programmed —
|
|
## and initRadar() (first line of run) paints the radar and the scan arc BLACK.
|
|
## The bot therefore ends up fully BLACK. Colors are applied once, never per tick.
|
|
##
|
|
## This module is both the bot type and the program entry point (see isMainModule
|
|
## below). All radar logic lives in modules/radar.nim; the bot keeps no state.
|
|
##
|
|
## The run loop drives the radar: commandRadar() is called BEFORE go() every
|
|
## tick, so the command is part of the tick's intent and is sent by THIS go().
|
|
## The order matters — go() sends the intent first and dispatches the pending
|
|
## events last, so onScannedBot only feeds the NEXT tick.
|
|
##
|
|
## Movement: modules/tfil.nim ("The Floor Is Lava"), vendored into this folder so
|
|
## the bot depends on nothing but the API. It is asked for a command every tick,
|
|
## BEFORE go(), exactly like the radar, and the result is applied with
|
|
## setTargetSpeed/setTurnRate — same contract as ModularBot's mover.
|
|
##
|
|
## Debug graphics: TFIL's drawing needs NO plumbing here. The API's graphics
|
|
## procs are global; the SVG buffer is flushed and cleared by the API after every
|
|
## tick, so anything drawn before `go()` (i.e. inside computeMove) reaches the
|
|
## 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/[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
|
|
|
|
const EnemyStaleTicks* = 60 ## drop a scanned enemy not rescanned for this many
|
|
## 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 = 1.0'f64 ## fire inside this much gun error, in
|
|
## DEGREES (the API's unit).
|
|
##
|
|
## Was 3.0 but compared against radians
|
|
## (`degToRad(FireSlopDeg)` = 0.052 deg): fixing
|
|
## the unit made the gun fire mid-slew, up to
|
|
## 3 deg off, and cost hits. 1 deg is tight
|
|
## enough that the shot is on target while
|
|
## still firing the tick after a correction.
|
|
|
|
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:
|
|
if ei.id == e.scannedBotId:
|
|
bot.enemies[i].x = e.x
|
|
bot.enemies[i].y = e.y
|
|
bot.enemies[i].heading = e.direction
|
|
bot.enemies[i].speed = e.speed
|
|
bot.enemies[i].energy = e.energy
|
|
bot.enemies[i].lastSeenTick = bot.tick
|
|
return
|
|
if bot.enemies.len >= MaxScannedEnemies:
|
|
bot.enemies.delete(0)
|
|
bot.enemies.add EnemyInfo(id: e.scannedBotId, x: e.x, y: e.y,
|
|
heading: e.direction, speed: e.speed, energy: e.energy,
|
|
lastSeenTick: bot.tick)
|
|
|
|
method onHitByBullet*(bot: DevControlBot, e: HitByBulletEvent) =
|
|
# an enemy bullet hit us -> tell the fire tracker, else the same tick reads as
|
|
# "no fire" and the enemy's shot goes uncounted (see modules/tfil.nim, FireFix)
|
|
bot.mover.noteEnemyBulletHit(e.bullet.power)
|
|
|
|
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.winN = min(winN, WinCap)
|
|
for k in 0 ..< result.winN:
|
|
result.winX[k] = winX[k]
|
|
result.winY[k] = winY[k]
|
|
result.winTick[k] = winTick[k]
|
|
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
|
|
bot.enemies = bot.enemies.filterIt(it.lastSeenTick >= bot.tick - EnemyStaleTicks)
|
|
|
|
method buildWorldState(bot: DevControlBot): WorldState =
|
|
WorldState(selfX: getX(), selfY: getY(),
|
|
selfSpeed: getSpeed(), selfHeading: getDirection(),
|
|
selfRadarHeading: getRadarDirection(), selfEnergy: getEnergy(),
|
|
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())
|
|
# `err` is DEGREES: normalizeRelativeAngle returns degrees and the API speaks
|
|
# degrees. Comparing it against degToRad(FireSlopDeg) meant "within 0.052 deg",
|
|
# not 3 deg - the gun withheld fire long after it was on target. Compare in the
|
|
# same unit.
|
|
if abs(err) <= FireSlopDeg:
|
|
# Park the gun: the pending correction from the previous tick is applied
|
|
# AFTER firing (TurnProcessor fires before executeBotIntents), so it would
|
|
# only over-rotate the gun on the NEXT turn. Zeroing it keeps the gun on the
|
|
# aim point while it holds fire.
|
|
setGunTurnRate(0.0)
|
|
if getGunHeat() == 0.0:
|
|
# Non-blocking. `fire()` is the BLOCKING variant: it calls go() itself, so
|
|
# the outer loop's go() ran a second, empty turn - the bot double-stepped
|
|
# the server on every shot, desyncing tick/scan bookkeeping from the game.
|
|
discard setFire(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")
|
|
else:
|
|
setGunTurnRate(err)
|
|
|
|
method run*(bot: DevControlBot) =
|
|
setAdjustGunForBodyTurn(true) # turret ignores body rotation
|
|
setAdjustRadarForBodyTurn(true) # radar ignores body rotation
|
|
setAdjustRadarForGunTurn(true) # radar ignores turret rotation too
|
|
initRadar() # once: radar + scan turn BLACK = programmed
|
|
while isRunning():
|
|
# One radar command and one movement command per tick, unconditionally,
|
|
# BEFORE go() — so both are part of this tick's intent.
|
|
commandRadar()
|
|
bot.ageEnemies() # stale scans dropped before they paint heat
|
|
let (speed, turnRate) = bot.mover.computeMove(bot.buildWorldState())
|
|
setTargetSpeed(speed)
|
|
setTurnRate(turnRate)
|
|
bot.computeGun() # gun intent, also before go()
|
|
go()
|
|
inc bot.tick
|
|
|
|
when isMainModule:
|
|
# argv[1] may override the metadata file (used by DevControlBot/DevControlBot.sh);
|
|
# otherwise the JSON next to this source, resolved at compile time so any cwd works.
|
|
let jsonPath =
|
|
if paramCount() >= 1: paramStr(1)
|
|
else: currentSourcePath().parentDir / "DevControlBot.json"
|
|
var bot = newDevControlBot()
|
|
start(bot, jsonPath)
|