DevControlBot 1.2.0: TFIL survival movement + universal battle runner

Ported "the floor is lava" (TFIL) movement into DevControlBot as a
self-contained module, DevControlBot/modules/tfil.nim. It has no runtime
dependency on common_libs/: the port is a standalone implementation,
parity-verified against the common_libs original over 2000 differential
ticks with zero divergences. Do not re-introduce the dependency and do
not edit the original to match.

Debug graphics (per-tile lava heat, tracked bullets and their danger
corridors, enemy core/aura, reachable hull, committed tile) are OFF by
default and compile-time gated behind -d:tfilDebug; see README.md for
the plain `nim c` invocation, since nimble runBot does not forward
compile flags.

Wired into DevControlBot.nim: movement computed between commandRadar()
and go(), fire-event tracking wired up, staleness handling for scanned
enemies, and body colour set to BLACK at init (movement and radar both
claim colour now).

Also adds tools/test_runner, a shared battle-test runner usable by any
garage, with an Observer adversary for quick floor checks.
This commit is contained in:
2026-10-04 18:16:24 +02:00
parent de0dd50d6e
commit 67d185880d
17 changed files with 1666 additions and 25 deletions
+21 -8
View File
@@ -70,14 +70,22 @@ an existing commit or tag.
garages to make this bot work, and do not reuse another bot's game logic garages to make this bot work, and do not reuse another bot's game logic
without explicit permission; shared, bot-agnostic code belongs in without explicit permission; shared, bot-agnostic code belongs in
`common_libs/`, and only with permission. `common_libs/`, and only with permission.
- Team colour convention: **white = not programmed, black = radar active**. - The bot **moves** (bullet-avoidance mover, see "Layout of this folder") but
still **does not fire**: hit tracking exists, the gun does not.
- Team colour convention: **white = not programmed, black = programmed and
running**. The bot is **fully black**: movement (initTFIL) claims body, turret
and gun, the radar (initRadar) claims the radar and its scan arc.
- Provenance: ModularBot / common_libs (Davide Cappellini, Apache-2.0). - Provenance: ModularBot / common_libs (Davide Cappellini, Apache-2.0).
### Constraints worth remembering ### Constraints worth remembering
Not explanations — real invariants that broke things when violated: Not explanations — real invariants that broke things when violated:
- **Command the radar BEFORE `go()`** — a real bug the other way round. - **Command the radar BEFORE `go()`** — a real bug the other way round. Movement is
computed in the same slot, between `commandRadar()` and `go()`.
- **Movement is self-contained.** `modules/tfil.nim` is a port of
`common_libs/movements/the_floor_is_lava.nim` with **no runtime dependency on
`common_libs/`** — do not add one, and do not edit the original to match.
- All radar logic is `modules/radar.nim`, in one piece. Do not split it back into - All radar logic is `modules/radar.nim`, in one piece. Do not split it back into
harness/lock/melee modules. harness/lock/melee modules.
@@ -96,7 +104,8 @@ DevControlBot_garage/
│ ├── DevControlBot.sh # BotLauncher entry point (thin wrapper) │ ├── DevControlBot.sh # BotLauncher entry point (thin wrapper)
│ ├── .env # OPTIONAL local config; secrets, never commit │ ├── .env # OPTIONAL local config; secrets, never commit
│ └── modules/ │ └── modules/
│ └── radar.nim # all radar logic │ ├── radar.nim # all radar logic
│ └── tfil.nim # all movement logic ("the floor is lava")
└── tests/ # INTENDED, does not exist yet — create it on └── tests/ # INTENDED, does not exist yet — create it on
# the first real test # the first real test
``` ```
@@ -139,6 +148,9 @@ Or via the wrapper, which works from any cwd:
overrides the path) is local-runs-only and **never overrides a variable already overrides the path) is local-runs-only and **never overrides a variable already
present in the environment** — the BotLauncher's values always win. Never print present in the environment** — the BotLauncher's values always win. Never print
its values, never `set -x`, never commit it. its values, never `set -x`, never commit it.
- **Debug graphics are OFF by default** and compile-time gated behind
`-d:tfilDebug`; `nimble runBot` does **not** forward compile flags, so draw them
with a plain `nim c -d:tfilDebug ...` (into a `/tmp` output path) and run that.
- Dependency setup is `nimble install robocode_tankroyale_botapi`; dependencies - Dependency setup is `nimble install robocode_tankroyale_botapi`; dependencies
come from the global nimble store. Do not vendor, do not add come from the global nimble store. Do not vendor, do not add
`nimble.paths` / `nimble develop`. `nimble.paths` / `nimble develop`.
@@ -175,10 +187,11 @@ Source: https://robocode.dev/articles/coordinates-and-angles.html (Tank Royale d
**CURRENT STATE, not a design sketch.** These describe the code as it is today. **CURRENT STATE, not a design sketch.** These describe the code as it is today.
**Diagram 1 — one tick. Owned by `DevControlBot/DevControlBot.nim` (`run`, lines **Diagram 1 — one tick. Owned by `DevControlBot/DevControlBot.nim` (`run`, lines
34-40) and `DevControlBot/modules/radar.nim` (`onScan`, `commandRadar`) — update 34-40), `DevControlBot/modules/radar.nim` (`onScan`, `commandRadar`) and
this diagram when either file changes.** The ordering is the whole point: the `DevControlBot/modules/tfil.nim` (`computeMove`) — update this diagram when any of
command is issued BEFORE `go()` so it travels with this tick's intent, and those files changes.** The ordering is the whole point: the commands are issued
events arrive AFTER, so a scan can only ever steer the NEXT tick. BEFORE `go()` so they travel with this tick's intent, and events arrive AFTER, so
a scan or an incoming bullet can only ever steer the NEXT tick.
```mermaid ```mermaid
sequenceDiagram sequenceDiagram
@@ -189,7 +202,7 @@ sequenceDiagram
Run->>Radar: commandRadar<br/># one command, every tick, no idle branch Run->>Radar: commandRadar<br/># one command, every tick, no idle branch
Radar-->>Bot: setRadarTurnRate<br/>LOCK turn + 5deg overshoot,<br/>or +45deg sweep Radar-->>Bot: setRadarTurnRate<br/>LOCK turn + 5deg overshoot,<br/>or +45deg sweep
Run->>Bot: go<br/># intent sent here, FIRST Run->>Bot: go<br/># intent sent here, FIRST
Bot->>Srv: tick intent<br/>radar turn only,<br/>no move, no fire Bot->>Srv: tick intent<br/>radar turn + move,<br/>no fire
Srv-->>Bot: tick result<br/>+ pending ScannedBotEvent Srv-->>Bot: tick result<br/>+ pending ScannedBotEvent
Bot->>Radar: onScannedBot -> onScan x, y<br/># AFTER go: remembers only Bot->>Radar: onScannedBot -> onScan x, y<br/># AFTER go: remembers only
Radar-->>Radar: target position stored,<br/>tick counter reset Radar-->>Radar: target position stored,<br/>tick counter reset
@@ -1,6 +1,6 @@
{ {
"name": "DevControlBot", "name": "DevControlBot",
"version": "1.1.0", "version": "1.2.0",
"authors": ["Davide Cappellini"], "authors": ["Davide Cappellini"],
"description": "Control skeleton bot — does nothing, bright colors", "description": "Control skeleton bot — does nothing, bright colors",
"gameTypes": ["classic", "1v1"], "gameTypes": ["classic", "1v1"],
@@ -1,11 +1,11 @@
## DevControlBot — control skeleton: boots, stands still, and drives nothing but ## DevControlBot — control skeleton: boots, drives the radar every tick and keeps
## the radar. It never moves and it never fires. ## itself alive with the TFIL survival movement. It never fires.
## ##
## Team convention: white means "not programmed yet". At startup body, turret, gun ## Team convention: white means "not programmed yet". Each module claims its own
## and radar are all plain WHITE. The radar then claims its OWN colours when it ## colours when its init runs, and nothing paints white after that: initTFIL()
## starts working: initRadar() paints the radar and the scan arc BLACK, leaving ## (constructor) paints body, turret and gun BLACK — movement is programmed —
## body/turret/gun white (this bot never moves and never fires, so they stay ## and initRadar() (first line of run) paints the radar and the scan arc BLACK.
## "not programmed"). Colors are applied once, never per tick. ## 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 ## 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. ## below). All radar logic lives in modules/radar.nim; the bot keeps no state.
@@ -15,32 +15,96 @@
## The order matters — go() sends the intent first and dispatches the pending ## The order matters — go() sends the intent first and dispatches the pending
## events last, so onScannedBot only feeds the NEXT tick. ## 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). ## API: robocode_tankroyale_botapi 1.0.7 (the renamed tankroyale_botapi package).
import std/[os] import std/[os, sequtils]
import robocode_tankroyale_botapi import robocode_tankroyale_botapi
import modules/radar import modules/radar
import modules/tfil
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
type DevControlBot* = ref object of Bot type DevControlBot* = ref object of Bot
mover: TfilModule
tick: int
enemies: seq[EnemyInfo] ## fed by onScannedBot, cleared on round end
proc newDevControlBot*(): DevControlBot = proc newDevControlBot*(): DevControlBot =
result = DevControlBot() result = DevControlBot()
setBodyColor(WHITE) result.mover = initTFIL() # movement is programmed -> body/turret/gun BLACK
setTurretColor(WHITE) setRadarColor(WHITE) # overwritten by initRadar() before the first tick
setGunColor(WHITE)
setRadarColor(WHITE)
method onScannedBot*(bot: DevControlBot, e: ScannedBotEvent) = method onScannedBot*(bot: DevControlBot, e: ScannedBotEvent) =
onScan(e.x, e.y) # remembered; commandRadar() re-aims every tick onScan(e.x, e.y) # remembered; commandRadar() re-aims every tick
# (e.scannedBotId, schemas.nim:305, is the # (e.scannedBotId, schemas.nim:305, is the
# scanned bot's identity; unused here) # scanned bot's identity)
# ...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) =
bot.enemies = @[]
bot.mover.resetRound()
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)
method run*(bot: DevControlBot) = method run*(bot: DevControlBot) =
initRadar() # once: radar + scan turn BLACK = programmed initRadar() # once: radar + scan turn BLACK = programmed
while isRunning(): while isRunning():
# One radar command per tick, unconditionally, BEFORE go() — so the command # One radar command and one movement command per tick, unconditionally,
# is part of this tick's intent and no tick is ever left without one. # BEFORE go() — so both are part of this tick's intent.
commandRadar() commandRadar()
bot.ageEnemies() # stale scans dropped before they paint heat
let (speed, turnRate) = bot.mover.computeMove(bot.buildWorldState())
setTargetSpeed(speed)
setTurnRate(turnRate)
go() go()
inc bot.tick
when isMainModule: when isMainModule:
# argv[1] may override the metadata file (used by DevControlBot/DevControlBot.sh); # argv[1] may override the metadata file (used by DevControlBot/DevControlBot.sh);
@@ -1,5 +1,5 @@
# Package # Package
version = "1.1.0" version = "1.2.0"
author = "Davide Cappellini" author = "Davide Cappellini"
description = "DevControlBot — control-skeleton bot that does nothing but show up bright" description = "DevControlBot — control-skeleton bot that does nothing but show up bright"
license = "MIT" license = "MIT"
@@ -0,0 +1,786 @@
## TFIL — "The Floor Is Lava" survival movement, vendored into DevControlBot.
##
## Ported from `common_libs/movements/the_floor_is_lava.nim` (the authoritative
## implementation) with its DEFAULT behaviour, kept byte-for-byte. Self-contained
## on purpose: this bot folder never imports from `common_libs`, so the harness
## types (WorldState / EnemyInfo / MoveCommand) and the enemy-fire detector are
## inlined here rather than imported.
##
## WHAT WAS DROPPED (all of it default-OFF or diagnostic-only in the source, so
## the shipped decision path is unchanged):
## * the whole `TR_TFIL_*` / `TR_FIRE_*` env-port surface (knobs baked in as
## consts below with the source's defaults): TILE_REPLAN, COMMIT_TICKS, NO_REV,
## COMMIT_LOG, COMMIT_ARRIVAL, COMMIT_MARGIN, NOREV_SPEED, TURN_BIAS,
## TURN_REF_DEG, DANGER_THRESHOLD, DIAG, GEO_MODE/GEO_TAU, ARRIVE_TICKS,
## HOLD_WHEN_TRAPPED, HOLD_MAX_TICKS, HEAT_TIME/TAU/POWER_GAIN,
## CORRIDOR_TICKS, CORRIDOR_HEAT, WALL_HOTNESS/RADIANCE, BULLET_CORE/AURA,
## PILLAR_ON, FIRE_DIAG, FIRE_FIX (always on here), FIRE_LAG (always 0 here).
## Consequences, all of them no-ops at the defaults: the time-indexed heat
## model and the damage-proportional magnitude scale are OFF (every heat is
## exactly the flat one), corridors run to the wall, the virtual centre pillar
## is absent (0/0), the pick is a UNIFORM draw (no turn / no-rev / geometry
## tilt), no arrival bound, no bounded hold, no commit diagnostics.
## * debug graphics — restored below, but behind `-d:tfilDebug` (off by default,
## since the SVG payload costs time every tick).
## * the pure bookkeeping fields (loss histogram, lastPick*, log-only vars).
##
## ANGLES: 0 deg = east, counter-clockwise positive (Tank Royale standard).
import std/[math, random]
import robocode_tankroyale_botapi
import robocode_tankroyale_botapi/graphics
import robocode_tankroyale_botapi/color
## ── Debug graphics ──────────────────────────────────────────────────────────
## OFF by default: the drawing is a real per-tick cost (an SVG buffer sent to
## the server) and nothing else needs it. Turn it ON at compile time:
## nim c -d:tfilDebug ...
## or `nimble runBot -d:tfilDebug`. Everything below is inside
## `when defined(tfilDebug)`, so the OFF build contains none of it.
##
## The API has no Graphics object to hand around: the procs are global, the SVG
## buffer is drained and flushed by the API after every tick. `computeMove` runs
## before `go()`, which is exactly where drawing belongs.
# ── Harness types (vendored from gun_harness/movement_interface) ─────────────
type
EnemyInfo* = object
id*: int
x*, y*: float
heading*, speed*, energy*: float
lastSeenTick*: int
WorldState* = object
enemyX*, enemyY*: float
enemySpeed*, enemyHeading*: float
selfX*, selfY*: float
selfSpeed*, selfHeading*: float
selfRadarHeading*: float
selfEnergy*: float
enemyEnergy*: float
arenaWidth*, arenaHeight*: float
tick*: int
enemies*: seq[EnemyInfo]
MoveCommand* = tuple[speed: float, turnRate: float]
## speed: target speed in px/tick (clamped to +-8 by the bot API);
## turnRate: body turn rate in degrees/tick.
# ── Tunables (source defaults, baked in) ────────────────────────────────────
const
GridSize = 36.0
MaxSpeed = 8.0
BulletCoreRadiusMin = 9.0 ## core radius at power 0.1
BulletCoreRadiusMax = 54.0 ## core radius at power 3.0
BulletAuraExtMin = 36.0 ## aura extension at power 3.0 (slow)
BulletAuraExtMax = 54.0 ## aura extension at power 0.1 (fast)
BulletCoreHeat = 10.0 ## lava per bullet-overlapping tile
BulletAuraHeat = 5.0 ## lava for aura ring tiles
EnemyCoreRadius = 18.0 ## half of 36px body
EnemyAuraRadius = 54.0 ## 18 + 36
EnemyCoreHeat = 40.0 ## lava per tile overlapping the enemy body circle
EnemyAuraHeat = 10.0 ## lava per tile in the enemy aura ring
CorridorHeat = 20.0 ## lava per corridor-overlapping tile
WallHotness = 30.0 ## peak wall radiance
WallRadiance = 10.0 ## wall radiance falloff
CommitTicks = 15 ## ticks to commit to a dodge point
MinCommitTicks = 5 ## must commit this long before a danger replan
DangerReplanThreshold = 25.0 ## replan on serious threats only (bullet core)
CoolestLevels = 2 ## how many distinct lava values count as "cool"
MaxTrackedBullets = 20 ## hard cap on tracked bullets
PathSampleStep = 18.0 ## ~half a tile
PathDangerThreshold = 10.0 ## max lava on path; above = unsafe
ArriveRadius = 18.0 ## "we are on the committed tile"
HullTicks = 50 ## reachable-hull planning horizon
FireFix = true ## corrected energy-drop detection
proc bulletRadii(power: float): tuple[core, aura: float] =
let t = (power - 0.1) / 2.9
let core = BulletCoreRadiusMin + t * (BulletCoreRadiusMax - BulletCoreRadiusMin)
let auraExt = BulletAuraExtMax - t * (BulletAuraExtMax - BulletAuraExtMin)
(core, core + auraExt)
# ── Enemy-fire detector (vendored from movement_harness/fire_tracker) ────────
#
# One enemy energy reading in, the confirmed fire powers out. Two server facts
# are corrected for: `BULLET_HIT_ENERGY_GAIN_FACTOR = 3` (an ENEMY bullet hitting
# US raises the SHOOTER's energy by 3*power and masks its own shot) and our own
# same-tick damage to the enemy (pushes the delta above the power cap). The
# corrections are staged one scan late because the server emits the hit event on
# turn N but applies the energy change to the reading of turn N+1.
type
FireTracker = object
prevEnergy*: seq[tuple[id: int, energy: float]]
hitBonusPending: float
dealtPending: float
hitBonusIncoming: float
dealtIncoming: float
proc initFireTracker*(): FireTracker =
FireTracker(prevEnergy: @[])
proc reset*(t: var FireTracker) =
t.prevEnergy = @[]
t.hitBonusPending = 0.0
t.dealtPending = 0.0
t.hitBonusIncoming = 0.0
t.dealtIncoming = 0.0
proc prevEnergyGet(t: FireTracker, id: int): float =
for e in t.prevEnergy:
if e.id == id: return e.energy
100.0
proc prevEnergySet(t: var FireTracker, id: int, energy: float) =
for i in 0..<t.prevEnergy.len:
if t.prevEnergy[i].id == id:
t.prevEnergy[i].energy = energy
return
t.prevEnergy.add((id: id, energy: energy))
proc noteEnemyBulletHit*(t: var FireTracker, power: float) {.inline.} =
## `onHitByBullet` -> `e.bullet.power`.
t.hitBonusIncoming += 3.0 * power
proc noteDamageDealt*(t: var FireTracker, damage: float) {.inline.} =
## `onBulletHit` -> `e.damage`.
t.dealtIncoming += damage
proc detect*(t: var FireTracker, id: int, energy: float, lo, hi: float): seq[float] =
let prev = t.prevEnergyGet(id)
let raw = prev - energy
var drop = raw + t.hitBonusPending - t.dealtPending
t.prevEnergySet(id, energy)
if drop > hi:
# Never silently drop a too-large delta: split it into the fewest waves each
# <= 3.0 — some heat beats none.
let n = int(ceil(drop / 3.0))
let p = drop / n.float
result = newSeq[float](n)
for i in 0..<n: result[i] = p
elif drop >= lo and drop <= hi:
result = @[drop]
proc endScan*(t: var FireTracker) =
## Rotate the event corrections one slot: the events noted since the previous
## `endScan` become the corrections applied by the NEXT scan.
t.hitBonusPending = t.hitBonusIncoming
t.dealtPending = t.dealtIncoming
t.hitBonusIncoming = 0.0
t.dealtIncoming = 0.0
# ── The mover ───────────────────────────────────────────────────────────────
type
TrackedBullet = object
x, y: float
velX, velY: float ## speed * cos(heading), speed * sin(heading)
power: float
age: int ## ticks alive; die if > 200
ScoredTile = tuple[col, row: int; pathMaxHeat: float]
CorridorGeom = object
dx, dy: float ## unit heading
px, py: float ## unit perpendicular
tMin: float ## distance to wall
bx, by: float ## bullet origin
TfilModule* = object
cols, rows: int
marginX, marginY: float
arenaWidth, arenaHeight: float
lava: seq[float] ## flat row-major, index = row*cols + col
bullets: seq[TrackedBullet]
fire: FireTracker
commitTarget: tuple[x, y: float] ## world coords of the committed dodge point
commitTicks: int ## ticks remaining on the commitment
commitLava: float ## lava at commit time (spike detection)
blockedTile: tuple[col, row: int; active: bool] ## excluded from the next pick
cachedHull: seq[tuple[x, y: float]]
cachedInsideTiles: seq[tuple[col, row: int]]
callCount: int ## computeMove call count; 0 = never called
lastBotX, lastBotY: float ## position at the last call (gap detection)
lastTileCol, lastTileRow: int ## grid tile at the last call (tile replan)
proc initTFIL*(): TfilModule =
# COLOUR CONVENTION: white = "not programmed yet", black = "programmed and
# running". Survival movement IS programmed, so this init claims the body's
# own colours: body, turret and gun go BLACK (radar claims its own pair in
# radar.nim). Set once here, never per tick.
setBodyColor(BLACK)
setTurretColor(BLACK)
setGunColor(BLACK)
TfilModule(cols: 0, rows: 0, fire: initFireTracker())
proc resetRound*(m: var TfilModule) =
m.bullets = @[]
m.fire.reset()
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
m.blockedTile = (col: 0, row: 0, active: false)
m.callCount = 0
m.lastBotX = 0.0
m.lastBotY = 0.0
m.lastTileCol = 0
m.lastTileRow = 0
proc removeBulletNear*(m: var TfilModule, x, y: float) =
## Mark the tracked bullet closest to (x,y) within one tile as dead (used when
## OUR bullet destroys one of theirs before we see it).
var bestIdx = -1
var bestD2 = GridSize * GridSize ## tolerance squared
for i, b in m.bullets:
let dx = b.x - x
let dy = b.y - y
let d2 = dx * dx + dy * dy
if d2 < bestD2:
bestD2 = d2
bestIdx = i
if bestIdx >= 0:
m.bullets.del(bestIdx)
proc initGrid(m: var TfilModule, arenaWidth, arenaHeight: float) =
m.cols = int(arenaWidth / GridSize)
m.rows = int(arenaHeight / GridSize)
m.marginX = (arenaWidth - m.cols.float * GridSize) / 2.0
m.marginY = (arenaHeight - m.rows.float * GridSize) / 2.0
m.arenaWidth = arenaWidth
m.arenaHeight = arenaHeight
m.lava = newSeq[float](m.cols * m.rows)
proc lavaAt(m: TfilModule, col, row: int): float {.inline.} =
m.lava[row * m.cols + col]
proc tileAt(m: TfilModule, wx, wy: float): tuple[col, row: int] =
(col: clamp(int((wx - m.marginX) / GridSize), 0, m.cols - 1),
row: clamp(int((wy - m.marginY) / GridSize), 0, m.rows - 1))
proc noteEnemyBulletHit*(m: var TfilModule, power: float) =
## `onHitByBullet` -> the shooter's `3*power` bonus correction.
when FireFix:
m.fire.noteEnemyBulletHit(power)
proc noteDamageDealt*(m: var TfilModule, damage: float) =
## `onBulletHit` -> our same-tick damage to the enemy correction.
when FireFix:
m.fire.noteDamageDealt(damage)
proc spawnTrackedWave(m: var TfilModule, ws: WorldState, ei: EnemyInfo, power: float) =
## One tracked bullet for a confirmed fire of `power`: linear prediction of our
## position at arrival becomes the aim heading.
let speed = 20.0 - 3.0 * power
let dx = ws.selfX - ei.x
let dy = ws.selfY - ei.y
let travelTime = sqrt(dx * dx + dy * dy) / speed
let hRad = ws.selfHeading * PI / 180.0
let predX = ws.selfX + ws.selfSpeed * cos(hRad) * travelTime
let predY = ws.selfY + ws.selfSpeed * sin(hRad) * travelTime
let heading = arctan2(predY - ei.y, predX - ei.x)
if m.bullets.len >= MaxTrackedBullets:
m.bullets.del(0) ## ponytail: drop the oldest; fine for a 20-bullet cap
m.bullets.add TrackedBullet(x: ei.x, y: ei.y,
velX: speed * cos(heading),
velY: speed * sin(heading),
power: power, age: 0)
proc detectFires(m: var TfilModule, ws: WorldState) =
## Check every enemy for an energy drop; spawn a tracked wave per confirmed fire.
for ei in ws.enemies:
for p in m.fire.detect(ei.id, ei.energy, 0.09, 3.01):
m.spawnTrackedWave(ws, ei, p)
m.fire.endScan()
proc advanceBullets(m: var TfilModule, selfX, selfY: float) =
## Advance positions and reap bullets that passed us, left the arena, or are
## too old.
var i = 0
while i < m.bullets.len:
var b = m.bullets[i]
b.x += b.velX
b.y += b.velY
b.age += 1
let dx = selfX - b.x
let dy = selfY - b.y
let passed = b.velX * dx + b.velY * dy < 0.0 ## dot < 0: moving away
let outOfBounds =
b.x < 0.0 or b.x > m.arenaWidth or b.y < 0.0 or b.y > m.arenaHeight
if passed or outOfBounds or b.age > 200:
m.bullets.del(i)
else:
m.bullets[i] = b
inc i
proc corridorGeom(b: TrackedBullet, arenaWidth, arenaHeight: float): CorridorGeom =
## `tMin` is the corridor length: the distance to the wall along the heading.
## Unset (0.0) -> zero-speed bullet, skipped by the caller.
let speed = sqrt(b.velX * b.velX + b.velY * b.velY)
if speed < 0.001: return
let dx = b.velX / speed
let dy = b.velY / speed
var tMin = Inf
if dx > 0.0: tMin = min(tMin, (arenaWidth - b.x) / dx)
elif dx < 0.0: tMin = min(tMin, (0.0 - b.x) / dx)
if dy > 0.0: tMin = min(tMin, (arenaHeight - b.y) / dy)
elif dy < 0.0: tMin = min(tMin, (0.0 - b.y) / dy)
CorridorGeom(dx: dx, dy: dy, px: -dy, py: dx, tMin: tMin, bx: b.x, by: b.y)
proc pointInHull(px, py: float, hull: seq[(float, float)]): bool =
## Crossing-number test against the hull polygon.
var inside = false
var j = hull.high
for i in 0..hull.high:
if ((hull[i][1] > py) != (hull[j][1] > py)) and
(px < (hull[j][0] - hull[i][0]) * (py - hull[i][1]) / (hull[j][1] - hull[i][1]) + hull[i][0]):
inside = not inside
j = i
inside
proc computeReachableHull(x0, y0, heading0, speed0,
arenaW, arenaH: float, ticks: int): seq[(float, float)] =
## Simulate `ticks` ticks at various turn rates / target speeds, then gift-wrap
## the convex hull of the final positions.
const TargetSpeeds = [8.0, 4.0, -4.0, -8.0]
const NumRates = 11
var pts: seq[(float, float)]
pts.add (x0, y0) ## always reachable: stay
for tSpeed in TargetSpeeds:
let mtr = 10.0 - 0.75 * abs(tSpeed) ## max turn rate at the target speed
for ri in 0..<NumRates:
let turnRate = -mtr + (2.0 * mtr / (NumRates - 1).float) * ri.float
var x = x0
var y = y0
var h = heading0
var spd = speed0
for _ in 0..<ticks:
if spd < tSpeed: spd = min(spd + 1.0, tSpeed)
elif spd > tSpeed: spd = max(spd - 1.0, tSpeed)
spd = clamp(spd, -MaxSpeed, MaxSpeed)
let curMtr = 10.0 - 0.75 * abs(spd)
h += clamp(turnRate, -curMtr, curMtr)
let hr = h * PI / 180.0
x = clamp(x + spd * cos(hr), 0.0, arenaW)
y = clamp(y + spd * sin(hr), 0.0, arenaH)
pts.add (x, y)
# Gift-wrap from the leftmost (then lowest) point.
var startIdx = 0
for i in 1..<pts.len:
if pts[i][0] < pts[startIdx][0] or
(pts[i][0] == pts[startIdx][0] and pts[i][1] < pts[startIdx][1]):
startIdx = i
var hull: seq[(float, float)]
var cur = startIdx
while true:
hull.add pts[cur]
var next = 0
for i in 1..<pts.len:
if next == cur:
next = i
continue
let ax = pts[next][0] - pts[cur][0]
let ay = pts[next][1] - pts[cur][1]
let bx = pts[i][0] - pts[cur][0]
let by = pts[i][1] - pts[cur][1]
if ax * by - ay * bx < 0.0: ## i is more counterclockwise
next = i
cur = next
if cur == startIdx: break
hull
proc pathMaxHeat(m: TfilModule, fx, fy, tx, ty: float): float =
## MAX lava on the straight-line segment (fx,fy) -> (tx,ty), sampled every ~half
## a tile. A single hot tile on the path (corridor, bullet core, enemy aura)
## makes the whole path unsafe.
let ddx = tx - fx
let ddy = ty - fy
let lineDist = sqrt(ddx * ddx + ddy * ddy)
if lineDist <= 0.1: return 0.0
let steps = max(1, int(lineDist / PathSampleStep))
var h = 0.0
for si in 0..steps:
let frac = si.float / steps.float
let (sc, sr) = m.tileAt(fx + ddx * frac, fy + ddy * frac)
h = max(h, m.lavaAt(sc, sr))
h
proc paintBulletHeat(m: var TfilModule, b: TrackedBullet) =
## Core circle and aura ring around one tracked bullet.
let (coreR, auraR) = bulletRadii(b.power)
let bx = b.x
let by = b.y
let coreR2 = coreR * coreR
let auraR2 = auraR * auraR
let colMin = max(0, int(floor((bx - auraR - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((bx + auraR - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((by - auraR - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((by + auraR - m.marginY) / GridSize)))
for row in rowMin..rowMax:
let y0 = m.marginY + row.float * GridSize
let nearY = clamp(by, y0, y0 + GridSize)
let dy = nearY - by
let dy2 = dy * dy
for col in colMin..colMax:
let x0 = m.marginX + col.float * GridSize
let dx = clamp(bx, x0, x0 + GridSize) - bx
let d2 = dx * dx + dy2
let idx = row * m.cols + col
if d2 <= coreR2: m.lava[idx] += BulletCoreHeat
elif d2 <= auraR2: m.lava[idx] += BulletAuraHeat
proc paintCorridorHeat(m: var TfilModule, b: TrackedBullet) =
## The rotated rectangle from the bullet to the arena wall, auraR wide.
let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight)
if cg.tMin == 0.0: return ## zero-speed bullet
let (_, auraR) = bulletRadii(b.power)
let wx = cg.bx + cg.dx * cg.tMin
let wy = cg.by + cg.dy * cg.tMin
let c0x = cg.bx + cg.px * auraR; let c0y = cg.by + cg.py * auraR
let c1x = cg.bx - cg.px * auraR; let c1y = cg.by - cg.py * auraR
let c2x = wx - cg.px * auraR; let c2y = wy - cg.py * auraR
let c3x = wx + cg.px * auraR; let c3y = wy + cg.py * auraR
let colMin = max(0, int(floor((min(min(c0x, c1x), min(c2x, c3x)) - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((max(max(c0x, c1x), max(c2x, c3x)) - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((min(min(c0y, c1y), min(c2y, c3y)) - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((max(max(c0y, c1y), max(c2y, c3y)) - m.marginY) / GridSize)))
for row in rowMin..rowMax:
let cy = m.marginY + (row.float + 0.5) * GridSize
let relY = cy - cg.by
let along0 = relY * cg.dy
let perp0 = relY * cg.py
for col in colMin..colMax:
let cx = m.marginX + (col.float + 0.5) * GridSize
let relX = cx - cg.bx
let along = along0 + relX * cg.dx
let perp = perp0 + relX * cg.px
if along >= 0.0 and along <= cg.tMin and perp >= -auraR and perp <= auraR:
m.lava[row * m.cols + col] += CorridorHeat
proc paintEnemyHeat(m: var TfilModule, ei: EnemyInfo) =
## Enemy core (18px) and aura ring (54px), same pattern as the bullets.
let ex = ei.x
let ey = ei.y
let colMin = max(0, int(floor((ex - EnemyAuraRadius - m.marginX) / GridSize)))
let colMax = min(m.cols - 1, int(floor((ex + EnemyAuraRadius - m.marginX) / GridSize)))
let rowMin = max(0, int(floor((ey - EnemyAuraRadius - m.marginY) / GridSize)))
let rowMax = min(m.rows - 1, int(floor((ey + EnemyAuraRadius - m.marginY) / GridSize)))
let coreR2 = EnemyCoreRadius * EnemyCoreRadius
let auraR2 = EnemyAuraRadius * EnemyAuraRadius
for row in rowMin..rowMax:
let y0 = m.marginY + row.float * GridSize
let dy = clamp(ey, y0, y0 + GridSize) - ey
let dy2 = dy * dy
for col in colMin..colMax:
let x0 = m.marginX + col.float * GridSize
let dx = clamp(ex, x0, x0 + GridSize) - ex
let d2 = dx * dx + dy2
let idx = row * m.cols + col
if d2 <= coreR2: m.lava[idx] += EnemyCoreHeat
elif d2 <= auraR2: m.lava[idx] += EnemyAuraHeat
proc paintWallHeat(m: var TfilModule) =
## Additive wall radiance: hottest along the border, falling off inwards.
for row in 0..<m.rows:
let vert = max(0.0, WallHotness - row.float * WallRadiance) +
max(0.0, WallHotness - (m.rows - 1 - row).float * WallRadiance)
for col in 0..<m.cols:
let heat = vert +
max(0.0, WallHotness - col.float * WallRadiance) +
max(0.0, WallHotness - (m.cols - 1 - col).float * WallRadiance)
m.lava[row * m.cols + col] += heat
proc collectCoolestTiles(m: var TfilModule): seq[tuple[col, row: int]] =
## The tiles inside the reachable hull whose lava is one of the `CoolestLevels`
## coolest DISTINCT values present there.
var distinctVals: seq[float]
for t in m.cachedInsideTiles:
let v = m.lavaAt(t.col, t.row)
var found = false
for dv in distinctVals:
if dv == v:
found = true
break
if not found:
distinctVals.add v
# ascending insertion sort — N is small
for i in 1..<distinctVals.len:
let key = distinctVals[i]
var j = i - 1
while j >= 0 and distinctVals[j] > key:
distinctVals[j + 1] = distinctVals[j]
dec j
distinctVals[j + 1] = key
result = @[]
let numLevels = min(CoolestLevels, distinctVals.len)
for t in m.cachedInsideTiles:
let v = m.lavaAt(t.col, t.row)
for li in 0..<numLevels:
if v == distinctVals[li]:
result.add t
break
proc drawHeatField(m: TfilModule, ws: WorldState) =
## The lava field per tile (colour ramp + value text), the tracked bullets'
## core/aura circles, their danger corridors and the enemies' core/aura.
var maxLava = 0.0
for v in m.lava:
if v > maxLava: maxLava = v
setFont("Arial", 10.0)
for row in 0..<m.rows:
for col in 0..<m.cols:
let val = m.lava[row * m.cols + col]
if val == 0.0: continue
let t = if maxLava > 0.0: val / maxLava else: 0.0
let heatColor = fromRgb(255'u8, uint8(255.0 * (1.0 - t)), 0'u8)
let x0 = m.marginX + col.float * GridSize
let y0 = m.marginY + row.float * GridSize
setStrokeColor(heatColor)
setStrokeWidth(1.0)
drawRectangle(x0, y0, GridSize, GridSize)
setFillColor(heatColor)
drawText($int(val), x0 + 12.0, y0 + 22.0)
# Tracked bullets: red core outline + filled centre, orange aura ring.
for b in m.bullets:
let (coreR, auraR) = bulletRadii(b.power)
setStrokeColor(RED)
setStrokeWidth(1.0)
setFillColor(RED)
drawCircle(b.x, b.y, coreR)
fillCircle(b.x, b.y, 3.0)
setStrokeColor(fromHex("#FF8800"))
drawCircle(b.x, b.y, auraR)
# Danger corridor: the rotated rectangle from each bullet to the arena wall.
setStrokeColor(fromHex("#AAAAAA"))
setStrokeWidth(1.0)
for b in m.bullets:
let (_, auraR) = bulletRadii(b.power)
let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight)
if cg.tMin == 0.0: continue
let wx = cg.bx + cg.dx * cg.tMin
let wy = cg.by + cg.dy * cg.tMin
drawPolygon(@[
(cg.bx + cg.px * auraR, cg.by + cg.py * auraR),
(cg.bx - cg.px * auraR, cg.by - cg.py * auraR),
(wx - cg.px * auraR, wy - cg.py * auraR),
(wx + cg.px * auraR, wy + cg.py * auraR),
])
# Enemies: cyan body core, green aura ring.
setStrokeColor(fromHex("#00FFFF"))
setStrokeWidth(1.5)
for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyCoreRadius)
setStrokeColor(fromHex("#00CC00"))
setStrokeWidth(1.0)
for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyAuraRadius)
proc drawDecision(m: TfilModule, ws: WorldState,
scoredTiles, safeTiles: seq[ScoredTile]) =
## What the planner actually did: reachable hull, the tiles whose path is
## blocked, the safe set, the tile it committed to, its own tile, and the
## committed-target line.
if m.cachedHull.len >= 3:
let hullPts = block:
var s: seq[(float, float)]
for p in m.cachedHull: s.add (p.x, p.y)
s
setStrokeColor(fromHex("#336699"))
setStrokeWidth(1.0)
drawPolygon(hullPts)
setStrokeColor(fromHex("#006666"))
setStrokeWidth(1.0)
for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: continue
if t in safeTiles: continue ## promoted into the safe set: drawn cyan below
drawRectangle(m.marginX + t.col.float * GridSize,
m.marginY + t.row.float * GridSize, GridSize, GridSize)
setStrokeColor(fromHex("#00FFFF"))
setStrokeWidth(2.0)
for t in safeTiles:
drawRectangle(m.marginX + t.col.float * GridSize,
m.marginY + t.row.float * GridSize, GridSize, GridSize)
let (chosenCol, chosenRow) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
setStrokeColor(fromHex("#00FF00"))
setStrokeWidth(2.5)
drawRectangle(m.marginX + chosenCol.float * GridSize,
m.marginY + chosenRow.float * GridSize, GridSize, GridSize)
let (botCol, botRow) = m.tileAt(ws.selfX, ws.selfY)
setStrokeColor(fromHex("#0088FF"))
setStrokeWidth(2.5)
drawRectangle(m.marginX + botCol.float * GridSize,
m.marginY + botRow.float * GridSize, GridSize, GridSize)
setStrokeColor(fromHex("#00FF00"))
setStrokeWidth(1.5)
drawLine(ws.selfX, ws.selfY, m.commitTarget.x, m.commitTarget.y)
proc computeMove*(m: var TfilModule, ws: WorldState): MoveCommand =
if m.cols == 0:
m.initGrid(ws.arenaWidth, ws.arenaHeight)
# Soft reset: a position gap (a rammer moved us across ticks) invalidates the
# commitment, the cached hull and every tracked bullet. 12px is above the 8px
# single-tick maximum, so normal motion never trips it.
let jumpDist = sqrt((ws.selfX - m.lastBotX)^2 + (ws.selfY - m.lastBotY)^2)
let jumped = (m.callCount > 0) and (jumpDist > 12.0)
if jumped:
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
m.bullets = @[]
m.blockedTile = (col: 0, row: 0, active: false)
# Re-snapshot prevEnergy: energy changes during ramming are not fires.
m.fire.prevEnergy = @[]
for ei in ws.enemies:
m.fire.prevEnergySet(ei.id, ei.energy)
# Tile-change replan: crossing a tile boundary cancels the commitment.
if (not jumped) and (m.callCount > 0) and (m.commitTicks > 0):
let curTileCol = clamp(int((ws.selfX - m.marginX) / GridSize), 0, m.cols - 1)
let curTileRow = clamp(int((ws.selfY - m.marginY) / GridSize), 0, m.rows - 1)
if curTileCol != m.lastTileCol or curTileRow != m.lastTileRow:
m.commitTicks = 0
m.cachedHull = @[]
m.cachedInsideTiles = @[]
# Per-tick: advance existing bullets, detect new fires
m.advanceBullets(ws.selfX, ws.selfY)
m.detectFires(ws)
# Recompute the lava field from scratch
for i in 0..<m.lava.len: m.lava[i] = 0.0
for b in m.bullets: m.paintBulletHeat(b)
for b in m.bullets: m.paintCorridorHeat(b)
for ei in ws.enemies: m.paintEnemyHeat(ei)
m.paintWallHeat()
when defined(tfilDebug):
drawHeatField(m, ws)
# ── Tile-based dodge system ────────────────────────────────────────────────
# Hull + inside-tiles: recomputed only on a replan tick (commitTicks == 0).
if m.commitTicks == 0:
m.cachedHull = computeReachableHull(ws.selfX, ws.selfY, ws.selfHeading,
ws.selfSpeed, m.arenaWidth,
m.arenaHeight, HullTicks)
m.cachedInsideTiles = @[]
if m.cachedHull.len >= 3:
for row in 0..<m.rows:
let cy = m.marginY + (row.float + 0.5) * GridSize
for col in 0..<m.cols:
let cx = m.marginX + (col.float + 0.5) * GridSize
if pointInHull(cx, cy, m.cachedHull):
m.cachedInsideTiles.add (col: col, row: row)
# Score each cool tile by the MAX lava on the straight-line path from the bot.
var scoredTiles: seq[ScoredTile]
for t in m.collectCoolestTiles():
let tx = m.marginX + (t.col.float + 0.5) * GridSize
let ty = m.marginY + (t.row.float + 0.5) * GridSize
scoredTiles.add (col: t.col, row: t.row,
pathMaxHeat: pathMaxHeat(m, ws.selfX, ws.selfY, tx, ty))
# ascending by path heat — insertion sort, small N
for i in 1..<scoredTiles.len:
let key = scoredTiles[i]
var j = i - 1
while j >= 0 and scoredTiles[j].pathMaxHeat > key.pathMaxHeat:
scoredTiles[j + 1] = scoredTiles[j]
dec j
scoredTiles[j + 1] = key
# Absolute threshold filter: safe = path max lava <= PathDangerThreshold.
# Fallback: if fewer than two tiles survive, promote the least-hot blocked ones.
var safeTiles: seq[ScoredTile]
for t in scoredTiles:
if t.pathMaxHeat <= PathDangerThreshold: safeTiles.add t
if safeTiles.len < 2:
# Promote the least-hot blocked tiles until there are two (scoredTiles is
# sorted ascending, so the first hot ones are the coolest of the hot).
for t in scoredTiles:
if safeTiles.len >= 2: break
if t.pathMaxHeat > PathDangerThreshold: safeTiles.add t
# Commitment logic: a fixed 15-tick dwell, cancellable by our own tile crossing
# (above) or by the committed tile getting genuinely dangerous (the safety
# valve, only after the minimum dwell).
if m.commitTicks > 0:
if CommitTicks - m.commitTicks >= MinCommitTicks:
let (cc, cr) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
if m.lavaAt(cc, cr) > m.commitLava + DangerReplanThreshold:
m.blockedTile = (col: cc, row: cr, active: true)
m.commitTicks = 0
if m.commitTicks > 0:
dec m.commitTicks
if m.commitTicks == 0 and safeTiles.len > 0:
# Never re-pick the tile we just blocked ourselves with; if that empties the
# pool, the block is ignored (being cornered beats being stuck).
var candidates: seq[ScoredTile]
for t in safeTiles:
if m.blockedTile.active and t.col == m.blockedTile.col and t.row == m.blockedTile.row:
continue
candidates.add t
if candidates.len == 0: candidates = safeTiles
## A uniform draw: the randomness in this pick is load-bearing (a
## deterministic argmin measured worse).
let ct = candidates[rand(candidates.high)]
m.commitTarget = (x: m.marginX + (ct.col.float + 0.5) * GridSize,
y: m.marginY + (ct.row.float + 0.5) * GridSize)
m.commitTicks = CommitTicks
m.commitLava = m.lavaAt(ct.col, ct.row)
m.blockedTile.active = false
when defined(tfilDebug):
drawDecision(m, ws, scoredTiles, safeTiles)
# Update the position snapshot and call counter for next gap/tile detection
m.lastBotX = ws.selfX
m.lastBotY = ws.selfY
m.lastTileCol = clamp(int((ws.selfX - m.marginX) / GridSize), 0, m.cols - 1)
m.lastTileRow = clamp(int((ws.selfY - m.marginY) / GridSize), 0, m.rows - 1)
m.callCount += 1
# ── Steering ────────────────────────────────────────────────────────────────
# `speed: 0.0` is how this module says "stop": the already-at-target case below
# returns the same command. The gun is not here — `computeMove` never touches
# fire, so a held tick still fires exactly as every other tick.
let stepDx = m.commitTarget.x - ws.selfX
let stepDy = m.commitTarget.y - ws.selfY
let dist2 = stepDx * stepDx + stepDy * stepDy
if dist2 < ArriveRadius * ArriveRadius:
return (speed: 0.0, turnRate: 0.0)
let targetBearing = arctan2(stepDy, stepDx) * 180.0 / PI
var delta = targetBearing - ws.selfHeading
while delta > 180.0: delta -= 360.0
while delta < -180.0: delta += 360.0
let maxTurnRate = 10.0 - 0.75 * abs(ws.selfSpeed)
if abs(delta) <= 90.0:
result = (speed: MaxSpeed, turnRate: clamp(delta, -maxTurnRate, maxTurnRate))
else:
let flipped = if delta > 0.0: delta - 180.0 else: delta + 180.0
result = (speed: -MaxSpeed, turnRate: clamp(flipped, -maxTurnRate, maxTurnRate))
+15
View File
@@ -223,6 +223,21 @@ SERVER_URL=ws://host:1234 ./DevControlBot.sh # shell wins, .env ignored for SE
| `DevControlBot.sh …` (default) | `nim c -d:release --hints:off` | quiet: dependency lines, one `build ok (release)`, one `running` line | | `DevControlBot.sh …` (default) | `nim c -d:release --hints:off` | quiet: dependency lines, one `build ok (release)`, one `running` line |
| `DevControlBot.sh --debug …` | plain `nim c` | classic diagnostics: `Hint: used config file …`, dot-progress line, `DEBUG BUILD` hint | | `DevControlBot.sh --debug …` | plain `nim c` | classic diagnostics: `Hint: used config file …`, dot-progress line, `DEBUG BUILD` hint |
### Debug graphics (TFIL heat field & decisions)
Off in the default build. Turn on with the `tfilDebug` define:
```
cd DevControlBot && nim c -d:release -d:tfilDebug \
--path:"$(nimble path robocode_tankroyale_botapi | head -1)" \
--path:"$(nimble path jsony | head -1)" DevControlBot.nim
```
Drawn each tick as an SVG overlay by the client: per-tile lava heat (colour ramp
+ value), tracked bullets and their danger corridors, enemy core/aura, the
reachable hull, blocked vs safe tiles, the committed tile, the bot's own tile
and the target line.
`--debug` is stripped by the wrapper wherever it appears in the arguments (a `--debug` is stripped by the wrapper wherever it appears in the arguments (a
repeated `--debug` is harmless) and is handed to the `runBot` task via the repeated `--debug` is harmless) and is handed to the `runBot` task via the
exported env var `$DEVCONTROLBOT_DEBUG` (`debug` / `release`) rather than as a exported env var `$DEVCONTROLBOT_DEBUG` (`debug` / `release`) rather than as a
+154
View File
@@ -0,0 +1,154 @@
# tools/test_runner — universal battle-test runner
One command for **every** garage in the repo. Lives under `tools/` because root
`AGENTS.md` defines it as *"generic tools valid for all bots (battle runners,
scripts, etc.)"* — there is no root `test/` folder and none is allowed.
It **builds on** `common_libs/test_framework` — it does not reimplement it:
| Need | Reused from |
|---|---|
| server lifecycle, compile, runner subprocess | `runBattle()` in `test_framework.nim` |
| offline log parsing | `parseServerOutput()` in `battle_result.nim` |
| adversaries | `common_libs/test_framework/adversaries/` + `adversaries/Observer/` |
Nothing in `common_libs/` is modified, moved or deleted.
---
## Usage
```sh
nim c --path:common_libs tools/test_runner/runner.nim
./tools/test_runner/runner --bot DevControlBot_garage --opponents GAUNTLET
./tools/test_runner/runner --bot X_garage --rounds 5 --json out.json
./tools/test_runner/runner --bot X_garage --offline captured.jsonl # no Java
./tools/test_runner/runner --bot X_garage --dry-run # matrix only
```
`--help` prints the full option list.
### Exit codes
| Code | Meaning |
|---|---|
| 0 | pass **or SKIP** (JARs absent) |
| 1 | test failure (a matchup below threshold) |
| 2 | harness error — `OSError` (bot compile failed), `IOError` (runner exited non-zero / bad setup), `TimeoutError` (server startup, compile, or runner timeout); each prints its own message |
### Env gating (SKIP, not failure)
Reads `TR_SERVER_JAR` (default: `DefaultServerJar` in `server_manager.nim`) and
`TR_BATTLE_RUNNER` (default: same path as `runner_process.nim`). If either file
is missing, the runner prints a SKIP banner and **exits 0**. This is the pattern
root `AGENTS.md` prescribes and that no garage implemented. `--server-jar` /
`--runner-jar` override the env explicitly so a driver can force a run.
---
## `.battletest.json` — per-garage overrides
Drop next to the bot dir:
```json
{ "rounds": 20, "opponents": ["../GotoTest_garage"] }
```
Garages can act as opponents: `--opponents <path>` takes any directory, and
`--bot` accepts a garage (`X_garage`) or a bot dir.
---
## Why `stage.nim` exists (do not "simplify" this away)
`tools/battle_runner/TestBattleRunner.java:51` derives each bot's identity JSON
filename **from the directory name**:
```java
var jsonPath = path.resolve(path.getFileName() + ".json");
```
So a bot in `DevControlBot_garage/` is looked up as `DevControlBot_garage.json`,
which does not exist. The result is a **ghost**: the battle runs, no error is
reported, and the bot simply never boots. Confirmed live in `/tmp/dcbv/stage`
— `stage/Observer/` works (dir name == stem), `stage/DbgBot/` does not.
`stageOne()` therefore builds `<tmp>/<Stem>/` containing `<Stem>` and
`<Stem>.json` and asserts `dirName == stem` plus both files existing, raising a
message naming the exact reason otherwise. If the bot dir is *already* named
after its stem (e.g. `DevControlBot_garage/DevControlBot/`), it is used in
place and not staged.
Adversaries that ship a `<Stem>.sh` launcher get a regenerated one in the staged
dir — the original execs `./out/<Stem>`, which a staged flat dir does not have.
---
## Report
One row per matchup: `opponent | score | rank | 1st | survivedRounds/rounds | status`.
**PRIMARY metric = `survivalCount`** (these bots are survival movers), then
`firstPlaces`, then `score`. A matchup fails when the survival rate is below
`--survival-threshold` (default `0.6`), when fewer rounds were recorded than
requested, or when the bot's name is **absent from `r.results`** — searching by
name returns a zero-initialised `BotResult` with no error, the trap called out
in the test-framework README.
### ⚠ SittingDuck is DEGENERATE in this harness
A matchup against `SittingDuck` reports **score 0 / survival 0 for both bots
regardless of play**. Observed live: `DevControlBot vs SittingDuck` →
`score 1 vs 0, survivalCount 0`. Therefore:
- `survivalCount` against SittingDuck is **NO-SIGNAL** and is shown as
`n/a(no-signal)`.
- Such a matchup is **never able to fail the run** — it is flagged
`NO-SIGNAL (not a gate)` and its score differential is reported for
information only. A 0-0 draw must not be reported as a regression.
- Use `OscillatorBot` / `Observer` for real survival signal.
---
## `adversaries/Observer`
Promoted from `/tmp/dcbv/observer`. It never fires, only spins its radar at
45°/tick, and:
- appends every scan to `scans.csv` (turn, id, name, x, y),
- appends the opponent position to `obs.csv` (turn, x, y),
- accumulates the Euclidean distance the **opponent** travels between
consecutive scans, written to `obs_result.txt` on round end.
That travelled distance is the metric that actually proves a bot MOVES — score
and survival counters do not. A prior run measured ~6600 units across the
1200×1200 arena.
Output paths are parameters, not the old hardcoded `/tmp/dcbv/*.csv`:
| Env | Default | File |
|---|---|---|
| `OBS_OUT_DIR` | process cwd | directory for `scans.csv`, `obs.csv` |
| `OBS_FILE` | `$OBS_OUT_DIR/obs_result.txt` | one-line result |
```sh
OBS_OUT_DIR=/tmp/obs ./tools/test_runner/runner \
--bot DevControlBot_garage --opponents tools/test_runner/adversaries/Observer
```
---
## Files
| File | Role |
|---|---|
| `runner.nim` | CLI entry (main), wiring only |
| `resolve.nim` | stem derivation, `.battletest.json`, env gating |
| `stage.nim` | staging dir builder + dir-name assertion |
| `suites.nim` | `baseline` / `all` / `GAUNTLET` opponent matrices |
| `report.nim` | table renderer, JSON output, exit-code policy |
| `adversaries/Observer/` | promoted measurement bot |
`stage.nim` and `suites.nim` are self-checking (`nim c -r` runs assertions on
the dir-name invariant and the matrix logic).
@@ -0,0 +1,9 @@
{
"name": "Observer",
"version": "1.0.0",
"authors": ["SirGarage test_runner"],
"description": "Radar-only measurement adversary: logs scans as CSV and accumulates opponent travel distance",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
cd "$(dirname "$0")"
exec ./out/Observer 2>> "${OBS_OUT_DIR:-/tmp}/observer_stderr.log"
@@ -0,0 +1,2 @@
--path:"../../../.."
switch("outdir", "out")
@@ -0,0 +1,9 @@
{
"name": "Observer",
"version": "1.0.0",
"authors": ["SirGarage test_runner"],
"description": "Radar-only measurement adversary: logs scans as CSV and accumulates opponent travel distance",
"gameTypes": ["classic", "1v1"],
"platform": "Nim",
"programmingLang": "Nim"
}
@@ -0,0 +1,59 @@
## Observer — measurement adversary.
##
## Plays radar-only: spins its radar so it re-scans the opponent every tick,
## logs every scan as CSV and accumulates the Euclidean distance the OPPONENT
## travels between consecutive scans. That travelled distance is the metric that
## actually proves a bot MOVES (a prior run measured ~6600 units across the
## 1200x1200 arena); score and survival counters do not.
##
## Output location is a parameter, not a hardcoded /tmp path:
## OBS_OUT_DIR directory for scans.csv / obs.csv / obs_result.txt
## (default: the process working directory)
## OBS_FILE file for the one-line result (default: <OBS_OUT_DIR>/obs_result.txt)
import std/[os, math, strformat]
import robocode_tankroyale_botapi
type Observer = ref object of Bot
samples: int
dist: float
lastX, lastY: float
have: bool
proc appendLine(path, line: string) =
let f = open(path, fmAppend)
defer: f.close()
f.writeLine line
proc outDir(): string =
result = getEnv("OBS_OUT_DIR", getCurrentDir())
createDir(result)
method onScannedBot(bot: Observer, e: ScannedBotEvent) =
if e.scannedBotId == getMyId(): return # 2-bot battle: only the other bot matters
let d = outDir()
appendLine(d / "scans.csv",
&"{getTurn()} id={e.scannedBotId} name={getBotName(e.scannedBotId)} x={e.x} y={e.y}")
appendLine(d / "obs.csv", &"{getTurn()},{e.x},{e.y}")
inc bot.samples
if bot.have:
bot.dist += hypot(e.x - bot.lastX, e.y - bot.lastY)
bot.lastX = e.x; bot.lastY = e.y; bot.have = true
method onTick(bot: Observer, e: TickEventForBot) =
## Spin the radar so the opponent is re-scanned every tick — that cadence is
## what makes the accumulated travel distance meaningful.
setRadarTurnRate(45)
method onRoundEnded(bot: Observer, e: RoundEndedEventForBot) =
let d = outDir()
writeFile(getEnv("OBS_FILE", d / "obs_result.txt"),
&"OBS samples={bot.samples} dist={bot.dist:.3f}")
when isMainModule:
let jsonPath =
if paramCount() >= 1: paramStr(1)
else: currentSourcePath().parentDir / "Observer.json"
start(Observer(), jsonPath)
+127
View File
@@ -0,0 +1,127 @@
## Report rendering + exit-code policy.
##
## PRIMARY metric = survivalCount (these bots are survival movers), then
## firstPlaces, then score. SITTING-DUCK CAVEAT: survival vs SittingDuck is
## NO-SIGNAL (the harness reports 0/0 for both bots regardless of play), so it
## is flagged as such and never used for pass/fail.
import std/[strutils, json, sequtils, net] # net: TimeoutError
import ../../common_libs/test_framework/test_framework
var
survivalThreshold* = 0.6 ## CLI --survival-threshold
const
ExitOk* = 0 ## pass OR skip
ExitFail* = 1 ## a matchup failed its threshold
ExitHarness* = 2 ## OSError / IOError / TimeoutError — the harness itself broke
type
Matchup* = object
opponent*: string
myScore*, oppScore*: int
rank*: int
firstPlaces*, survivalCount*: int
survivedRounds*, rounds*: int
noSignal*: bool ## SittingDuck: survival column is meaningless
incomplete*: bool ## fewer rounds recorded than requested
missing*: bool ## bot name absent from r.results (zero-value trap)
passed*: bool
note*: string
proc buildMatchup*(r: BattleResult, myName, oppName: string, roundsWanted: int): Matchup =
result.opponent = oppName
result.rounds = r.rounds.len
result.incomplete = r.rounds.len < roundsWanted
var mine, theirs: BotResult
var foundMine = false
for b in r.results:
if b.name == myName: mine = b; foundMine = true
elif b.name == oppName: theirs = b
result.missing = not foundMine # zero-value BotResult trap guard
result.rank = mine.rank
result.firstPlaces = mine.firstPlaces
result.survivalCount = mine.survivalCount
result.myScore = mine.totalScore
result.oppScore = theirs.totalScore
for rd in r.rounds:
for br in rd.results:
if br.name == myName and br.survived: inc result.survivedRounds
result.noSignal = oppName == "SittingDuck"
if result.missing:
result.passed = false
result.note = "name '" & myName & "' absent from results — bot never booted?"
elif result.noSignal:
# Degenerate harness: both bots report ~0 regardless of play, so survival
# AND score are meaningless. Never fail on it — flag as no-signal only.
result.passed = true
result.note = "NO-SIGNAL vs SittingDuck (score " & $result.myScore &
" vs " & $result.oppScore & ") — informational, not a gate"
else:
let rate = if result.rounds == 0: 0.0
else: result.survivedRounds.float / result.rounds.float
result.passed = rate >= survivalThreshold and not result.incomplete
if result.incomplete:
result.note = "only " & $result.rounds & "/" & $roundsWanted & " rounds recorded"
else:
result.note = "survivalRate=" & formatFloat(rate, ffDecimal, 2)
proc pad(s: string, n: int): string =
if s.len >= n: s[0 ..< n] else: s & repeat(' ', n - s.len)
proc render*(m: seq[Matchup], myName: string): string =
var s = "\n== " & myName & " — battle-test report ==\n"
s.add pad("opponent", 20) & pad("score", 8) & pad("rank", 6) &
pad("1st", 6) & pad("surv", 16) & "status\n"
s.add repeat('-', 80) & "\n"
for x in m:
let survCol =
if x.noSignal: "n/a(no-signal)"
elif x.missing: "-"
else: $x.survivedRounds & "/" & $x.rounds
let status =
if x.missing: "FAIL (missing from results)"
elif x.noSignal: "NO-SIGNAL (not a gate)"
elif x.passed: "PASS"
else: "FAIL"
s.add pad(x.opponent, 20) & pad($x.myScore, 8) & pad($x.rank, 6) &
pad($x.firstPlaces, 6) & pad(survCol, 16) & status
if x.note.len > 0: s.add " (" & x.note & ")"
s.add "\n"
let failed = m.filterIt(not it.passed).len
s.add repeat('-', 80) & "\n"
s.add (if failed == 0: "ALL MATCHUPS PASSED\n" else: $failed & " MATCHUP(S) FAILED\n")
result = s
proc toJson*(m: seq[Matchup], myName: string): string =
var root = %*{"bot": myName, "survivalThreshold": survivalThreshold, "matchups": newJArray()}
for x in m:
root["matchups"].add %*{
"opponent": x.opponent, "score": x.myScore, "oppScore": x.oppScore,
"rank": x.rank, "firstPlaces": x.firstPlaces,
"survivalCount": x.survivalCount,
"survivedRounds": x.survivedRounds, "rounds": x.rounds,
"noSignal": x.noSignal, "incomplete": x.incomplete,
"missing": x.missing, "passed": x.passed, "note": x.note}
result = $root
proc exitCode*(m: seq[Matchup]): int =
if m.anyIt(not it.passed): ExitFail else: ExitOk
## Map framework exceptions to exit 2 with a message that says what actually
## broke (see test_framework README: OSError = compile, IOError = runner exit,
## TimeoutError = server startup / compile / runner timeout).
proc harnessExit*(e: ref CatchableError): int =
if e of OSError:
stderr.writeLine "HARNESS ERROR [bot compile failed]: " & e.msg
elif e of IOError:
stderr.writeLine "HARNESS ERROR [battle runner exited non-zero / bad setup]: " & e.msg
elif e of TimeoutError:
stderr.writeLine "HARNESS ERROR [timeout: server startup, bot compile, or battle runner]: " & e.msg
else:
stderr.writeLine "HARNESS ERROR [unexpected]: " & e.msg
ExitHarness
+95
View File
@@ -0,0 +1,95 @@
## Resolution + env gating for the universal battle-test runner.
##
## Deliberately thin: everything that already exists in common_libs/test_framework
## (compileBots) is imported, not reimplemented. We only add:
## - stem derivation (strip _garage, see bot_compiler.nim:9)
## - `.battletest.json` per-garage overrides
## - the SKIP-when-no-jars policy
import std/[os, strutils, json]
import ../../common_libs/test_framework/server_manager ## DefaultServerJar (import only, never modified)
type
Overrides* = object
rounds*: int ## 0 = not overridden
opponents*: seq[string] ## empty = not overridden
ResolvedBot* = object
dir*: string ## directory to hand to the battle runner (or stage)
stem*: string ## bot name, _garage stripped
rounds*: int ## effective rounds for this bot (0 = global)
opponents*: seq[string] ## per-garage override, empty = global matrix
const GarageSuffix* = "_garage"
const OverrideFile* = ".battletest.json"
proc stemOf*(path: string): string =
## Mirrors bot_compiler.nim:9 — last path component minus _garage.
result = lastPathPart(absolutePath(path))
if result.endsWith(GarageSuffix):
result = result[0 ..< result.len - GarageSuffix.len]
proc innerBotDir*(path: string): string =
## Some garages keep the actual bot in a nested `<Stem>/` subdir
## (e.g. DevControlBot_garage/DevControlBot/). Descend into it when the
## given dir has no src/ and no binary but has a same-named subdir.
let abs = absolutePath(path)
let stem = stemOf(abs)
if not dirExists(abs / "src") and not fileExists(abs / stem) and
dirExists(abs / stem):
return abs / stem
abs
proc readOverrides*(path: string): Overrides =
let f = absolutePath(path) / OverrideFile
if not fileExists(f): return
try:
let n = parseJson(readFile(f))
if n.hasKey("rounds"): result.rounds = n["rounds"].getInt()
if n.hasKey("opponents"):
for o in n["opponents"].getElems(): result.opponents.add o.getStr()
except JsonParsingError as e:
raise newException(ValueError, f & " is not valid JSON: " & e.msg)
proc resolveBot*(path: string): ResolvedBot =
## path may be a garage (`X_garage`) or a bot dir. Returns the dir the
## runner should use plus the bot's stem and any .battletest.json overrides.
if not dirExists(path):
raise newException(IOError, "bot path is not a directory: " & path)
result.dir = innerBotDir(path)
result.stem = stemOf(result.dir)
let ov = readOverrides(result.dir)
result.rounds = ov.rounds
result.opponents = ov.opponents
# --- env gating -------------------------------------------------------------
const
RepoRoot* = currentSourcePath().parentDir.parentDir.parentDir
AdversaryRoot* = currentSourcePath().parentDir / "adversaries"
const DefaultRunnerJarHint* =
"/home/davide/Projects/tank-royale/runner/examples/lib/robocode-tankroyale-runner.jar"
type
Gate* = object
ok*: bool ## false => SKIP (quit 0), not a failure
reason*: string
serverJar*: string
runnerJar*: string
proc gate*(serverOverride = "", runnerOverride = ""): Gate =
## SKIP (exit 0) when the JARs are missing — root AGENTS.md prescribes this
## and no garage implements it yet. Explicit overrides bypass the env.
result.serverJar =
if serverOverride.len > 0: serverOverride
else: getEnv("TR_SERVER_JAR", DefaultServerJar) ## same default as server_manager.nim
result.runnerJar =
if runnerOverride.len > 0: runnerOverride
else: getEnv("TR_BATTLE_RUNNER", DefaultRunnerJarHint)
if not fileExists(result.serverJar):
result.reason = "TR_SERVER_JAR does not exist: " & result.serverJar
elif not fileExists(result.runnerJar):
result.reason = "TR_BATTLE_RUNNER does not exist: " & result.runnerJar
else:
result.ok = true
+170
View File
@@ -0,0 +1,170 @@
## Universal battle-test runner — CLI entry point.
##
## One command for every garage in the repo:
## nim c -r --path:../../common_libs tools/test_runner/runner.nim -- --bot X_garage
##
## Exit codes: 0 = pass or SKIP, 1 = test failure, 2 = harness error.
import std/[os, strutils, parseopt, strformat]
import ../../common_libs/test_framework/test_framework
import ../../common_libs/test_framework/battle_result # parseServerOutput (offline mode)
import ./resolve, ./stage, ./suites, ./report
type Cfg = object
bots: seq[string]
oppSuite: string
rounds: int
timeout: int
jsonOut: string
offline: string
dryRun: bool
serverJar, runnerJar: string
const Usage = """
Universal battle-test runner (tools/test_runner)
Usage:
runner --bot <garageOrDir> [--bot ...] [options]
Options:
--bot <path> Bot garage (X_garage) or bot dir. Repeatable.
--opponents <set> baseline | all | GAUNTLET | <path> (default: baseline)
--rounds <N> Rounds per matchup (default: 10)
--timeout <MS> Battle runner timeout (default: 120000)
--survival-threshold <f> Fail a matchup below this survival rate (default: 0.6)
--json <out.json> Write the report as JSON
--offline <file.jsonl> Parse a captured battle log, no Java, no server
--server-jar <path> Override TR_SERVER_JAR (bypasses the env gate)
--runner-jar <path> Override TR_BATTLE_RUNNER (bypasses the env gate)
--dry-run Resolve and print the matrix, run nothing
-h, --help This text
Environment: TR_SERVER_JAR, TR_BATTLE_RUNNER (see common_libs/test_framework/README.md).
If the JARs are absent the runner prints a SKIP banner and exits 0 — that is a
skip, not a failure.
Exit codes: 0 pass|skip, 1 test failure, 2 harness error.
Caveat: survival vs SittingDuck is NO-SIGNAL (both bots score 0/survive 0 in this
harness regardless of play). It is flagged as such and judged on score
differential only. Use OscillatorBot/Observer for real survival signal.
"""
proc parseArgs(): Cfg =
result = Cfg(oppSuite: Baseline, rounds: 10, timeout: 120000)
var p = initOptParser(commandLineParams())
# ponytail: parseopt does not bind values to options — the value arrives as
# the NEXT cmdArgument, so we latch the key and fill it on the way by.
var pending = ""
for kind, key, val in p.getopt():
case kind
of cmdEnd: discard
of cmdArgument:
if pending.len > 0:
case pending
of "bot": result.bots.add key
of "opponents": result.oppSuite = key
of "rounds": result.rounds = parseInt(key)
of "timeout": result.timeout = parseInt(key)
of "survival-threshold": survivalThreshold = parseFloat(key)
of "json": result.jsonOut = key
of "offline": result.offline = key
of "server-jar": result.serverJar = key
of "runner-jar": result.runnerJar = key
else: stderr.writeLine "option --" & pending & " needs a value\n" & Usage; quit(ExitHarness)
pending = ""
elif key.len > 0 and key[0] != '-':
result.bots.add key
of cmdLongOption, cmdShortOption:
if key == "h" or key == "help":
echo Usage
quit(ExitOk)
elif key == "dry-run":
result.dryRun = true
elif key in ["bot", "opponents", "rounds", "timeout", "survival-threshold",
"json", "offline", "server-jar", "runner-jar"]:
pending = key
else:
stderr.writeLine "unknown option: --" & key & "\n" & Usage
quit(ExitHarness)
proc runOffline(cfg: Cfg, bots: seq[ResolvedBot]): int =
## No Java, no server: parse the captured JSON-lines log.
if not fileExists(cfg.offline):
stderr.writeLine "offline log not found: " & cfg.offline
return ExitHarness
let r = parseServerOutput(readFile(cfg.offline))
var m: seq[Matchup]
for b in bots:
var opponent = ""
for n in r.bots:
if n != b.stem: opponent = n
if opponent.len == 0:
stderr.writeLine "offline log has no opponent for " & b.stem
return ExitHarness
m.add buildMatchup(r, b.stem, opponent, cfg.rounds)
echo render(m, bots[0].stem)
if cfg.jsonOut.len > 0: writeFile(cfg.jsonOut, toJson(m, bots[0].stem))
exitCode(m)
proc main(): int =
let cfg = parseArgs()
if cfg.bots.len == 0:
stderr.writeLine "--bot is required\n" & Usage
return ExitHarness
var bots: seq[ResolvedBot]
for b in cfg.bots: bots.add resolveBot(b)
if cfg.offline.len > 0:
return runOffline(cfg, bots)
let g = gate(cfg.serverJar, cfg.runnerJar)
if not g.ok:
echo "========================================================"
echo " SKIP — integration battle tests not run"
echo " reason: ", g.reason
echo " set TR_SERVER_JAR / TR_BATTLE_RUNNER (or pass --server-jar"
echo " / --runner-jar) to enable. See common_libs/test_framework/README.md"
echo "========================================================"
return ExitOk
for b in bots: echo "bot: ", b.dir, " stem=", b.stem
let all = suite(cfg.oppSuite)
echo "opponent suite '", all.name, "':"
var matrix: seq[tuple[bot: ResolvedBot, opp: string]]
for b in bots:
var opps = all.opponents
if b.opponents.len > 0: opps = b.opponents # .battletest.json override
for o in opps:
echo " ", b.stem, " vs ", lastPathPart(o)
matrix.add (b, o)
if cfg.dryRun:
echo "\n--dry-run: ", matrix.len, " matchup(s), nothing executed."
return ExitOk
let stageRoot = getTempDir() / "test_runner_stage"
var m: seq[Matchup]
try:
for (b, oppPath) in matrix:
let o = resolveBot(oppPath)
let rounds = if b.rounds > 0: b.rounds else: cfg.rounds
let stMine = stageOne(stageRoot, b.dir, b.stem)
let stOpp = stageOne(stageRoot, o.dir, o.stem)
echo &"\n--- {b.stem} vs {o.stem} ({rounds} rounds) ---"
let r = runBattle(@[stMine.dir, stOpp.dir], rounds = rounds,
timeout = cfg.timeout)
m.add buildMatchup(r, b.stem, o.stem, rounds)
except CatchableError as e:
return harnessExit(e)
let primary = bots[0].stem
echo render(m, primary)
if cfg.jsonOut.len > 0: writeFile(cfg.jsonOut, toJson(m, primary))
exitCode(m)
when isMainModule:
quit(main())
+73
View File
@@ -0,0 +1,73 @@
## Staging builder.
##
## WHY THIS EXISTS (important, do not "simplify" it away):
## TestBattleRunner.java:51 derives each bot's identity JSON filename from the
## DIRECTORY NAME:
## var jsonPath = path.resolve(path.getFileName() + ".json");
## So a staging dir named anything other than the bot stem silently produces a
## missing-JSON bot. It does NOT error — the bot simply never boots and you get
## a ghost: a participant in the scoreboard that never fights. Confirmed live in
## /tmp/dcbv/stage (Observer/ = working, DbgBot/ = broken).
## Therefore: dirName == stem, always, and we assert it.
import std/[os, strformat]
import ../../common_libs/test_framework/bot_compiler
type
StagedBot* = object
dir*: string ## directory to hand to the battle runner
stem*: string
staged*: bool ## false => original dir already had the right name
proc locateJson*(botDir, stem: string): string =
## The .json can sit beside the binary or in src/ (adversaries ship both).
for c in [botDir / stem & ".json", botDir / "src" / stem & ".json"]:
if fileExists(c): return c
""
proc stageOne*(stageRoot, botDir, stem: string): StagedBot =
let dirName = lastPathPart(botDir)
if dirName == stem:
return StagedBot(dir: botDir, stem: stem, staged: false)
let bins = compileBots(@[botDir]) # raises OSError on compile failure
if bins.len != 1:
raise newException(IOError,
fmt"expected exactly 1 binary for {botDir}, got {bins.len}")
let bin = bins[0]
let js = locateJson(botDir, stem)
if not fileExists(bin):
raise newException(IOError, fmt"compiled binary missing: {bin}")
if js.len == 0:
raise newException(IOError,
fmt"identity JSON not found for '{stem}' in {botDir} " &
fmt"(looked for {stem}.json and src/{stem}.json)")
result.dir = stageRoot / stem
result.stem = stem
result.staged = true
createDir(result.dir)
copyFile(bin, result.dir / stem)
copyFile(js, result.dir / stem & ".json")
let sh = result.dir / stem & ".sh"
if fileExists(botDir / stem & ".sh"):
# Write, don't copy: the original launcher execs ./out/<stem>, which does
# not exist in a staged dir where the binary sits at the top level.
writeFile(sh, "#!/bin/sh\ncd \"$(dirname \"$0\")\"\nexec ./" & stem & "\n")
setFilePermissions(sh, {fpUserExec, fpUserRead, fpUserWrite})
# Assert the invariant that keeps ghosts from happening.
if lastPathPart(result.dir) != stem:
raise newException(IOError,
fmt"staging dir name '{lastPathPart(result.dir)}' != stem '{stem}'")
if not fileExists(result.dir / stem):
raise newException(IOError, fmt"staged binary missing: {result.dir / stem}")
if not fileExists(result.dir / stem & ".json"):
raise newException(IOError, fmt"staged JSON missing: {result.dir / stem}.json")
when isMainModule:
## Self-check: the dir-name invariant is the whole point of this module.
let tmp = getTempDir() / "stage_selftest" / "MyBot"
doAssert lastPathPart(tmp) == "MyBot"
doAssert lastPathPart(tmp / "x") != "MyBot"
echo "stage.nim self-check passed"
+62
View File
@@ -0,0 +1,62 @@
## Opponent matrices. Garages may also act as opponents (any --bot dir can be
## pulled in via `.battletest.json`), so "all" = shared adversaries + `extra`.
import std/os
import ./resolve
type
Suite* = object
name*: string
opponents*: seq[string] ## directories, not stems
const
Baseline* = "baseline"
All* = "all"
Gauntlet* = "GAUNTLET"
SharedAdversaries* = RepoRoot / "common_libs" / "test_framework" / "adversaries"
proc adversaryDirs*(): seq[string] =
## Every shared adversary: the ones in common_libs/test_framework/adversaries
## plus the runner's own adversaries/ (Observer). Lazily computed, so adding
## an adversary is just a new directory — no code change.
for root in [SharedAdversaries, AdversaryRoot]:
if not dirExists(root): continue
for kind, p in walkDir(root):
if kind == pcDir:
let stem = lastPathPart(p)
if fileExists(p / (stem & ".nim")) or fileExists(p / "src" / (stem & ".nim")):
result.add p
proc suite*(name: string, extra: openArray[string] = []): Suite =
## baseline = two cheap reference bots; all = every shared adversary;
## GAUNTLET = baseline ∪ all ∪ any extra opponents named in --opponents.
var dirs: seq[string]
if name == Baseline:
dirs = @[SharedAdversaries / "SittingDuck", SharedAdversaries / "OscillatorBot"]
elif name == All or name == Gauntlet:
dirs = adversaryDirs()
if name == Gauntlet:
dirs.add SharedAdversaries / "SittingDuck"
dirs.add SharedAdversaries / "OscillatorBot"
var uniq: seq[string]
for d in dirs:
if d notin uniq: uniq.add d
dirs = uniq
else:
dirs = @[name] # treated as a path (a garage acting as opponent)
for e in extra:
if e notin dirs: dirs.add e
result = Suite(name: name, opponents: dirs)
proc isDegenerate*(opponentStem: string): bool =
## CAVEAT: a SittingDuck matchup is DEGENERATE in this harness — both bots
## report score 0 / survival 0 regardless of play. Survival vs SittingDuck is
## NO-SIGNAL (its score differential is still valid). See README.
opponentStem == "SittingDuck"
when isMainModule:
doAssert suite(Baseline).opponents.len == 2
doAssert isDegenerate("SittingDuck")
doAssert not isDegenerate("OscillatorBot")
echo "suites.nim self-check passed: ", adversaryDirs().len, " adversaries"