Files
SirRoboGarage/DevControlBot_garage/DevControlBot/DevControlBot.nim
T

253 lines
13 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)
# Online-start variant: default = neutral (zero output weights).
# `-d:elmPrior` = weak pooled prior (pretrained beta scaled by 0.1).
const OnlinePriorScale* = (when defined(elmPrior): 0.1 else: 0.0)
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(priorScale = OnlinePriorScale) # hidden layer loaded, online
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()) # history the gun needs
if bot.gun.online:
bot.gun.noteEnemyAt(bot.tick, e.x, e.y) # delayed-label trace
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 onGameStarted*(bot: DevControlBot, e: GameStartedEventForBot) =
## A new game = a new opponent. This is the ONLY reset point for the online
## model: within a battle the same opponent fights round after round with the
## same movement code, so RoundStartedEvent deliberately does NOT touch it.
## (The API fires onGameStarted once per battle and onRoundStarted per round.)
bot.gun.resetOnline()
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) =
if bot.gun.online:
bot.gun.drainPending(bot.tick) # label any shot whose flight time elapsed
let belief = bot.buildBelief(FirePower)
let feat = buildFeatures(belief)
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
if bot.gun.online:
# Enqueue a delayed label: the true impact position is only knowable
# once tof ticks of flight have passed (keyed by dueTick).
let d = hypot(belief.ex - belief.selfX, belief.ey - belief.selfY)
let tofTicks = max(1, int(round(d / belief.bulletSpeed)))
bot.gun.recordShot(feat, baseAim, belief.selfX, belief.selfY,
bot.tick + tofTicks)
when defined(gunLog):
# One line per shot. Columns:
# round,tick,predCorrection,baseAimDeg,finalAimDeg,gunDeg,
# nOnline,gateOpen,modelErr,zeroErr,<32 features>
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()) & "," & $bot.gun.nOnline & "," &
(if bot.gun.gateOpen: "1" else: "0") & "," &
$bot.gun.modelErr & "," & $bot.gun.zeroErr & "," &
feat.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)