Bots: env reporting, TFIL movement, gun selector and docs refresh

DevControlBot   DevControlBot.sh env-file handling and defines, tfil.nim
                  survival-movement rework, README
  ModularBot      .env.example, ModularBot.nim, env_report.nim, vbullet_draw.nim
  PPO_Bot         enemy_tracker.nim
  common_libs     gun_harness/selector.nim
  tests           env_report, lead_gain_legacy, rack_membership,
                  rack_stat_width, tm_pattern_registration adjustments
  docs            env_reference.md, goto-controller-algorithm.md
This commit is contained in:
2026-10-05 22:43:30 +02:00
parent 7505fbf089
commit e2d1968a77
16 changed files with 309 additions and 142 deletions
@@ -7,11 +7,15 @@
# propagates the real exit code. Signals are forwarded to Nimble so the task's # propagates the real exit code. Signals are forwarded to Nimble so the task's
# own EXIT/INT/TERM cleanup always runs. # own EXIT/INT/TERM cleanup always runs.
# #
# Usage: DevControlBot.sh [--debug] [<metadata.json>] [extra args for the bot] # Usage: DevControlBot.sh [--debug] [-d:<define>[=<value>]]... [<metadata.json>] [extra args]
# #
# (no args) RELEASE build + run with the bundled DevControlBot.json # (no args) RELEASE build + run with the bundled DevControlBot.json
# (no flag) RELEASE build (nim c -d:release), quiet output # (no flag) RELEASE build (nim c -d:release), quiet output
# --debug classic DEBUG build (plain nim c): compiler hints + diagnostics # --debug classic DEBUG build (plain nim c): compiler hints + diagnostics
# -d:foo compile-time Nim define. ANY number, in any position, in EITHER
# build mode: --debug only changes optimisation/hints, defines are
# independent of it, so `-d:tfilDebug` debug graphics work in a
# release build too. Accepted forms: -d:foo and -d:foo=bar.
# #
# --debug is a build-mode flag for this wrapper only: it is stripped here and # --debug is a build-mode flag for this wrapper only: it is stripped here and
# never reaches the bot binary or nimble's task arguments. It travels to the # never reaches the bot binary or nimble's task arguments. It travels to the
@@ -19,6 +23,14 @@
# confused with a bot argument, cannot collide with the status file mechanism # confused with a bot argument, cannot collide with the status file mechanism
# and keeps the task's argument parsing untouched. Repeated --debug is harmless. # and keeps the task's argument parsing untouched. Repeated --debug is harmless.
# #
# -d: args travel the same way, as $DEVCONTROLBOT_DEFINES. They MUST be stripped
# here: the runBot task forwards its own argv to the BOT BINARY, so a -d: arg
# would otherwise become the bot's argv and never reach the compiler. Matching is
# the anchored glob `-d:*` (whole-argument, starts with -d:), so a value that
# merely contains "-d:" inside another word ("x-d:y", "--debug-d:x") is NOT a
# define and is forwarded verbatim. Anything that is neither --debug, -h/--help
# nor a -d: arg still reaches the bot binary exactly as before.
#
# Configuration (SERVER_URL, SERVER_SECRET, ...) is NOT handled here at all: the # Configuration (SERVER_URL, SERVER_SECRET, ...) is NOT handled here at all: the
# API's start() reads those from the environment, and the optional .env file is # API's start() reads those from the environment, and the optional .env file is
# loaded by the runBot task, so it also works with a direct `nimble runBot`. # loaded by the runBot task, so it also works with a direct `nimble runBot`.
@@ -30,11 +42,16 @@ cd "$SCRIPT_DIR"
usage() { usage() {
cat <<EOF cat <<EOF
Usage: $(basename "$0") [--debug] [<metadata.json>] [extra args for the bot] Usage: $(basename "$0") [--debug] [-d:<define>[=<value>]]... [<metadata.json>] [extra args for the bot]
--debug classic debug build: shows compiler hints and diagnostics --debug classic debug build: shows compiler hints and diagnostics
(default is a quiet RELEASE build, nim c -d:release) (default is a quiet RELEASE build, nim c -d:release)
-h,--help show this help -d:foo, -d:foo=bar Nim compile-time define, passed to `nim c`. Repeatable.
Independent of --debug: defines apply in BOTH build modes,
so `-d:tfilDebug` debug graphics also work in a release
build. Only whole args starting with -d: are treated as
defines; everything else is forwarded to the bot binary.
-h,--help show this help
Examples: Examples:
$(basename "$0") # release build + run, bundled DevControlBot.json $(basename "$0") # release build + run, bundled DevControlBot.json
@@ -42,15 +59,33 @@ Examples:
$(basename "$0") -h # this help $(basename "$0") -h # this help
$(basename "$0") --debug # debug build $(basename "$0") --debug # debug build
$(basename "$0") --debug my.json # debug build with custom metadata $(basename "$0") --debug my.json # debug build with custom metadata
$(basename "$0") -d:tfilDebug # release build with TFIL debug graphics
$(basename "$0") --debug -d:tfilDebug # debug build, also with debug graphics
$(basename "$0") -d:danger -d:logLevel=2 my.json
EOF EOF
} }
# Split caller args: everything except --debug is forwarded verbatim. # Split caller args: --debug and -d: defines are consumed here, everything else
# is forwarded verbatim. The defines end up in a single space-separated string
# because the compiler line is `eval`ed (like $DEPS) to survive paths with spaces.
BUILD_MODE=release BUILD_MODE=release
DEFINES=""
FORWARDED=() FORWARDED=()
for a in "$@"; do for a in "$@"; do
case "$a" in case "$a" in
--debug) BUILD_MODE=debug ;; --debug) BUILD_MODE=debug ;;
-d:*)
# TRUST BOUNDARY: the string is eval'ed by the runBot task, so a define
# carrying whitespace, quotes, $, ` or ; could inject shell. Reject it
# loudly instead of passing it on. Legal Nim defines (-d:foo, -d:foo=bar)
# contain none of these.
case "$a" in
*[[:space:]\"\'\$\;\`\\]*)
echo "$(basename "$0"): invalid define '$a'" >&2
echo " expected -d:name or -d:name=value with no spaces or shell characters" >&2
exit 1 ;;
esac
DEFINES="$DEFINES $a" ;;
*) FORWARDED+=("$a") ;; *) FORWARDED+=("$a") ;;
esac esac
done done
@@ -63,6 +98,9 @@ case "${1:-}" in
esac esac
export DEVCONTROLBOT_DEBUG="$BUILD_MODE" export DEVCONTROLBOT_DEBUG="$BUILD_MODE"
# Leading space trimmed: empty when the caller passed no -d: arg, and the runBot
# task's compile lines are then byte-identical to a run without this feature.
export DEVCONTROLBOT_DEFINES="${DEFINES# }"
# The runBot task's shell always exits 0 (otherwise Nimble raises a NimScript # The runBot task's shell always exits 0 (otherwise Nimble raises a NimScript
# exception with a stack trace and a dump of the whole script) and writes the # exception with a stack trace and a dump of the whole script) and writes the
@@ -20,7 +20,7 @@
## exactly the flat one), corridors run to the wall, the virtual centre pillar ## 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 ## 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. ## tilt), no arrival bound, no bounded hold, no commit diagnostics.
## * debug graphics — restored below, but behind `-d:tfilDebug` (off by default, ## * debug graphics — restored below, but behind ` ` (off by default,
## since the SVG payload costs time every tick). ## since the SVG payload costs time every tick).
## * the pure bookkeeping fields (loss histogram, lastPick*, log-only vars). ## * the pure bookkeeping fields (loss histogram, lastPick*, log-only vars).
## ##
@@ -28,8 +28,7 @@
import std/[math, random] import std/[math, random]
import robocode_tankroyale_botapi import robocode_tankroyale_botapi
import robocode_tankroyale_botapi/graphics import robocode_tankroyale_botapi/color # graphics comes re-exported by the import above
import robocode_tankroyale_botapi/color
## ── Debug graphics ────────────────────────────────────────────────────────── ## ── Debug graphics ──────────────────────────────────────────────────────────
## OFF by default: the drawing is a real per-tick cost (an SVG buffer sent to ## OFF by default: the drawing is a real per-tick cost (an SVG buffer sent to
@@ -534,107 +533,108 @@ proc collectCoolestTiles(m: var TfilModule): seq[tuple[col, row: int]] =
result.add t result.add t
break break
proc drawHeatField(m: TfilModule, ws: WorldState) = when defined(tfilDebug):
## The lava field per tile (colour ramp + value text), the tracked bullets' proc drawHeatField(m: TfilModule, ws: WorldState) =
## core/aura circles, their danger corridors and the enemies' core/aura. ## 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 var maxLava = 0.0
for v in m.lava: for v in m.lava:
if v > maxLava: maxLava = v if v > maxLava: maxLava = v
setFont("Arial", 10.0) setFont("Arial", 10.0)
for row in 0..<m.rows: for row in 0..<m.rows:
for col in 0..<m.cols: for col in 0..<m.cols:
let val = m.lava[row * m.cols + col] let val = m.lava[row * m.cols + col]
if val == 0.0: continue if val == 0.0: continue
let t = if maxLava > 0.0: val / maxLava else: 0.0 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 heatColor = fromRgb(255'u8, uint8(255.0 * (1.0 - t)), 0'u8)
let x0 = m.marginX + col.float * GridSize let x0 = m.marginX + col.float * GridSize
let y0 = m.marginY + row.float * GridSize let y0 = m.marginY + row.float * GridSize
setStrokeColor(heatColor) 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) setStrokeWidth(1.0)
drawRectangle(x0, y0, GridSize, GridSize) setFillColor(RED)
setFillColor(heatColor) drawCircle(b.x, b.y, coreR)
drawText($int(val), x0 + 12.0, y0 + 22.0) fillCircle(b.x, b.y, 3.0)
setStrokeColor(fromHex("#FF8800"))
drawCircle(b.x, b.y, auraR)
# Tracked bullets: red core outline + filled centre, orange aura ring. # Danger corridor: the rotated rectangle from each bullet to the arena wall.
for b in m.bullets: setStrokeColor(fromHex("#AAAAAA"))
let (coreR, auraR) = bulletRadii(b.power)
setStrokeColor(RED)
setStrokeWidth(1.0) setStrokeWidth(1.0)
setFillColor(RED) for b in m.bullets:
drawCircle(b.x, b.y, coreR) let (_, auraR) = bulletRadii(b.power)
fillCircle(b.x, b.y, 3.0) let cg = corridorGeom(b, m.arenaWidth, m.arenaHeight)
setStrokeColor(fromHex("#FF8800")) if cg.tMin == 0.0: continue
drawCircle(b.x, b.y, auraR) 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),
])
# Danger corridor: the rotated rectangle from each bullet to the arena wall. # Enemies: cyan body core, green aura ring.
setStrokeColor(fromHex("#AAAAAA")) setStrokeColor(fromHex("#00FFFF"))
setStrokeWidth(1.0) setStrokeWidth(1.5)
for b in m.bullets: for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyCoreRadius)
let (_, auraR) = bulletRadii(b.power) setStrokeColor(fromHex("#00CC00"))
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) setStrokeWidth(1.0)
drawPolygon(hullPts) for ei in ws.enemies: drawCircle(ei.x, ei.y, EnemyAuraRadius)
setStrokeColor(fromHex("#006666")) proc drawDecision(m: TfilModule, ws: WorldState,
setStrokeWidth(1.0) scoredTiles, safeTiles: seq[ScoredTile]) =
for t in scoredTiles: ## What the planner actually did: reachable hull, the tiles whose path is
if t.pathMaxHeat <= PathDangerThreshold: continue ## blocked, the safe set, the tile it committed to, its own tile, and the
if t in safeTiles: continue ## promoted into the safe set: drawn cyan below ## committed-target line.
drawRectangle(m.marginX + t.col.float * GridSize, if m.cachedHull.len >= 3:
m.marginY + t.row.float * GridSize, GridSize, GridSize) 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("#00FFFF")) setStrokeColor(fromHex("#006666"))
setStrokeWidth(2.0) setStrokeWidth(1.0)
for t in safeTiles: for t in scoredTiles:
drawRectangle(m.marginX + t.col.float * GridSize, if t.pathMaxHeat <= PathDangerThreshold: continue
m.marginY + t.row.float * GridSize, GridSize, GridSize) 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)
let (chosenCol, chosenRow) = m.tileAt(m.commitTarget.x, m.commitTarget.y) setStrokeColor(fromHex("#00FFFF"))
setStrokeColor(fromHex("#00FF00")) setStrokeWidth(2.0)
setStrokeWidth(2.5) for t in safeTiles:
drawRectangle(m.marginX + chosenCol.float * GridSize, drawRectangle(m.marginX + t.col.float * GridSize,
m.marginY + chosenRow.float * GridSize, GridSize, GridSize) m.marginY + t.row.float * GridSize, GridSize, GridSize)
let (botCol, botRow) = m.tileAt(ws.selfX, ws.selfY) let (chosenCol, chosenRow) = m.tileAt(m.commitTarget.x, m.commitTarget.y)
setStrokeColor(fromHex("#0088FF")) setStrokeColor(fromHex("#00FF00"))
setStrokeWidth(2.5) setStrokeWidth(2.5)
drawRectangle(m.marginX + botCol.float * GridSize, drawRectangle(m.marginX + chosenCol.float * GridSize,
m.marginY + botRow.float * GridSize, GridSize, GridSize) m.marginY + chosenRow.float * GridSize, GridSize, GridSize)
setStrokeColor(fromHex("#00FF00")) let (botCol, botRow) = m.tileAt(ws.selfX, ws.selfY)
setStrokeWidth(1.5) setStrokeColor(fromHex("#0088FF"))
drawLine(ws.selfX, ws.selfY, m.commitTarget.x, m.commitTarget.y) 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 = proc computeMove*(m: var TfilModule, ws: WorldState): MoveCommand =
if m.cols == 0: if m.cols == 0:
+6 -3
View File
@@ -175,7 +175,10 @@ in the bot's environment for local runs.
## Optional `.env` (a convenience for local runs only) ## Optional `.env` (a convenience for local runs only)
`DevControlBot/.env` is **optional**. If it is absent nothing happens: no error, `DevControlBot/.env` is **optional**, and in this checkout it is empty (0 bytes):
it sets no `SERVER_URL` and no port at all. So no `.env` disabling or editing is
needed to run against the Tank Royale GUI, whose default port is 7654 — the same
as the API default below. If it is absent nothing happens: no error,
no warning beyond one informational line, the run behaves exactly as before and no warning beyond one informational line, the run behaves exactly as before and
the API defaults apply. It is not required, not generated, and not committed. the API defaults apply. It is not required, not generated, and not committed.
@@ -276,9 +279,9 @@ not masked.
Each mode prints its own short line, e.g. Each mode prints its own short line, e.g.
``` ```
[start] Cannot connect to ws://localhost:4567: Connection refused [start] Cannot connect to ws://localhost:7654: Connection refused
[devcontrolbot] bot exited with code 1. [devcontrolbot] bot exited with code 1.
[devcontrolbot] No game server on ws://localhost:4567 (SERVER_URL). [devcontrolbot] No game server on ws://localhost:7654 (SERVER_URL).
[devcontrolbot] Start the Tank Royale server, or point SERVER_URL at a running one. [devcontrolbot] Start the Tank Royale server, or point SERVER_URL at a running one.
``` ```
+34 -2
View File
@@ -226,6 +226,8 @@ TR_RACK_TMSELECT=off # Tsetlin machine used as the shot selector
TR_RACK_TMPATTERN=off # Tsetlin machine used as a pattern matcher TR_RACK_TMPATTERN=off # Tsetlin machine used as a pattern matcher
TR_RACK_TMHORIZON=off # horizon Tsetlin automata gun TR_RACK_TMHORIZON=off # horizon Tsetlin automata gun
TR_RACK_LEADGAIN=off # per-range-band learned lead-gain corrector TR_RACK_LEADGAIN=off # per-range-band learned lead-gain corrector
TR_RACK_KNOWLEDGE=off # learned angular-residual corrector on the lead forecast
TR_RACK_WAVEELM=off # online-ELM learned (x,y) offset on the analytic intercept
# Give every named gun a fixed share of the turns instead of ranking them. # Give every named gun a fixed share of the turns instead of ranking them.
# e.g. TR_RACK_SHARE=PATTERN:60%,HEADON:40% (GUN:weight, comma separated, # e.g. TR_RACK_SHARE=PATTERN:60%,HEADON:40% (GUN:weight, comma separated,
# the % sign is optional). Empty = the ranking selector. GOTCHA: every gun you # the % sign is optional). Empty = the ranking selector. GOTCHA: every gun you
@@ -236,8 +238,9 @@ TR_RACK_SHARE=
# Drop whole guns by rack id (comma separated, e.g. 16). Empty = keep them all. # Drop whole guns by rack id (comma separated, e.g. 16). Empty = keep them all.
# Ids: 0 HEADON 1 LINEAR 2 TSETLIN 3 CIRCULAR 4 GUESSFACTOR 5 PATTERN # Ids: 0 HEADON 1 LINEAR 2 TSETLIN 3 CIRCULAR 4 GUESSFACTOR 5 PATTERN
# 6 WALLBOUNCE 7 ACCEL 8 STOPSHOT 9 DISPLACE 10 AVGLEAD 11 DECAYGF 12 KNN # 6 WALLBOUNCE 7 ACCEL 8 STOPSHOT 9 DISPLACE 10 AVGLEAD 11 DECAYGF 12 KNN
# 13 TMSELECT 14 TMPATTERN 15 TMHORIZON 16 LEADGAIN. A disabled gun never even # 13 TMSELECT 14 TMPATTERN 15 TMHORIZON 16 LEADGAIN 17 KNOWLEDGE 18 WAVEELM.
# spawns a virtual bullet, so its fitness stays empty and it cannot be picked. # A disabled gun never even spawns a virtual bullet, so its fitness stays empty
# and it cannot be picked.
GUN_RACK_DISABLE= GUN_RACK_DISABLE=
# ── gun selector (which admitted gun fires this tick) ─────────────────────── # ── gun selector (which admitted gun fires this tick) ───────────────────────
@@ -667,6 +670,35 @@ TR_LEADGAIN_ADAPT=32 # NO-OP: the old adapt interval, no longer used
TR_LEADGAIN_CALIB=512 # NO-OP: the old calibration interval, no longer used TR_LEADGAIN_CALIB=512 # NO-OP: the old calibration interval, no longer used
TR_LEADGAIN_SEED=20240921 # NO-OP: the old seed, no longer used TR_LEADGAIN_SEED=20240921 # NO-OP: the old seed, no longer used
# KNOWLEDGE (rack id 17) — the learned additive angular residual on top of the
# self-consistent lead forecast. It answers only the aim angle: no power, no
# fire decision, no target picking.
TR_KNOWLEDGE_MEM= # path of the learned table; EMPTY = memory only
# (nothing is ever written to disk). Set to e.g.
# /tmp/gun_knowledge.bin to persist across battles.
# WAVEELM (rack id 18) — the online-ELM gun. Analytic bullet/target intercept
# (self-consistent flight time) plus a learned (x, y) offset from a recursive
# least-squares ELM trained on the real-shot feedback. Admitted by the rack line
# above only; this gun has NO env knobs of its own — see below.
#
# OFF BY DEFAULT (shipped, like every gun except PATTERN). To enable:
# TR_RACK_WAVEELM=both (also: 1v1 | melee; aliases any/empty->both,
# single/lock->1v1, only1v1->1v1,
# multi/onlymelee->melee, none/disabled/disable->off)
# UNRECOGNISED value warns on stderr and falls back to `both` (GOTCHA: a typo
# ADDS the gun to the rack, it never turns it off).
# FORCED SHARE: TR_RACK_SHARE=WAVEELM:50,PATTERN:50 works, but only if
# WAVEELM is admitted above — a share naming an `off` gun is refused.
# NOTHING TO TUNE FROM HERE: WaveLambda (0.1 ridge), WaveRho (1.02 forgetting),
# WaveIters (20 intercept iterations), WaveMaxResidual, WaveMaxOffset,
# WaveTraceSlots and the ELM seed (42) are `const`s in
# common_libs/guns/waveelm.nim — changing them needs a REBUILD, not an env var.
# No TR_WAVEELME_* variable exists; there is no persisted memory path either
# (the ELM is rebuilt from scratch every battle, unlike KNOWLEDGE).
# Per-shot behaviour for every admitted gun is logged by the shared stats writer
# (GUN_STATS_PATH below).
# PATTERN — the shipped gun, the only one the rack admits. # PATTERN — the shipped gun, the only one the rack admits.
TR_PATTERN_LEN=10 # ticks of movement history used as the search key TR_PATTERN_LEN=10 # ticks of movement history used as the search key
TR_PATTERN_DEPTH=500 # how far back the history scan may reach TR_PATTERN_DEPTH=500 # how far back the history scan may reach
+52 -4
View File
@@ -1,5 +1,5 @@
## ModularBot — plugin gun architecture tracer bullet. ## ModularBot — plugin gun architecture tracer bullet.
## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5), WallBounceGun (6), AccelGun (7), StopShotGun (8), DisplacementGun (9), AveragedLeadGun (10), DecayGFGun (11), KNNGun (12), TmSelectorGun (13), TmPatternGun (14), TmHorizonGun (15), LeadGainGun (16), BitbrainNetGun (17) via GunHarness. ## Guns: HeadOnGun (0), LinearGun (1), TsetlinGun (2), CircularGun (3), GFGun (4), PatternMatcherGun (5), WallBounceGun (6), AccelGun (7), StopShotGun (8), DisplacementGun (9), AveragedLeadGun (10), DecayGFGun (11), KNNGun (12), TmSelectorGun (13), TmPatternGun (14), TmHorizonGun (15), LeadGainGun (16), KnowledgeGun (17), WaveElmGun (18) via GunHarness.
## Radar: RadarLockModule (1v1) / AdaptiveMeleeRadarModule (2+ enemies), auto-switched per tick. ## Radar: RadarLockModule (1v1) / AdaptiveMeleeRadarModule (2+ enemies), auto-switched per tick.
## Movement: OscillatorModule (perpendicular strafing). ## Movement: OscillatorModule (perpendicular strafing).
@@ -31,6 +31,8 @@ import guns/tm_selector
import guns/tm_pattern import guns/tm_pattern
import guns/tm_horizon import guns/tm_horizon
import guns/lead_gain import guns/lead_gain
import guns/gun_knowledge
import guns/waveelm
import movements/phantom_meteor import movements/phantom_meteor
import movements/rammer import movements/rammer
import movements/ram_decision import movements/ram_decision
@@ -158,7 +160,7 @@ let ResultLog* =
block: block:
let v = getEnv("TR_RESULT_LOG", "1").strip().toLowerAscii() let v = getEnv("TR_RESULT_LOG", "1").strip().toLowerAscii()
not (v == "0" or v == "false" or v == "no" or v == "off") not (v == "0" or v == "false" or v == "no" or v == "off")
const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern", "WallBounce", "Accel", "StopShot", "Displace", "AvgLead", "DecayGF", "KNN", "TMSelect", "TMPattern", "TMHorizon", "LeadGain"] const GunNames = ["HeadOn", "Linear", "Tsetlin", "Circular", "GuessFactor", "Pattern", "WallBounce", "Accel", "StopShot", "Displace", "AvgLead", "DecayGF", "KNN", "TMSelect", "TMPattern", "TMHorizon", "LeadGain", "Knowledge", "WaveElm"]
## Rack id of the new TM pattern gun. It defaults to `TR_RACK_TMPATTERN=off`; ## Rack id of the new TM pattern gun. It defaults to `TR_RACK_TMPATTERN=off`;
## unlike the other guns, its virtual-bullet spawn is gated on rack admission ## unlike the other guns, its virtual-bullet spawn is gated on rack admission
@@ -182,6 +184,25 @@ const TmHorizonId = 15
## (backward compatibility; see `gun_harness/selector`). ## (backward compatibility; see `gun_harness/selector`).
const LeadGainId = 16 const LeadGainId = 16
## Rack id of KNOWLEDGE, the learned additive angular residual on top of the
## self-consistent lead forecast (`common_libs/guns/gun_knowledge.nim`). It is
## APPENDED at the end of the rack, so no existing id moved and every
## `tools/ab/arms_*.txt` config still addresses the gun it was written for. It
## ships `TR_RACK_KNOWLEDGE=off`, like every gun except Pattern, and its
## virtual-bullet spawn is gated on rack admission (`vBulletAdmitted`), so the
## shipped default never spawns it and the shared tracker ring head — hence every
## other gun's learning order — is byte-for-byte unchanged. Unlike the rest of
## the rack it may also touch disk (`TR_KNOWLEDGE_MEM`), which is another reason
## it stays out of the default rack.
const KnowledgeId = 17
## Rack id of WAVEELM, the online-ELM gun (`common_libs/guns/waveelm.nim`): an
## analytic intercept plus a learned per-tick (x, y) offset trained by an
## online sequential ELM on its OWN virtual-bullet feedback. APPENDED at the end
## of the rack, so no existing id moved. Ships `TR_RACK_WAVEELM=off`, like every
## gun except Pattern, and its virtual-bullet spawn is gated on rack admission.
const WaveElmId = 18
## ── virtual-bullet debug overlay (TR_VBULLET_DEBUG*) ─────────────────────── ## ── virtual-bullet debug overlay (TR_VBULLET_DEBUG*) ───────────────────────
## OFF by default: the shipped bot draws nothing. When on, the tracker's ## OFF by default: the shipped bot draws nothing. When on, the tracker's
## virtual bullets are overlaid so the training signal the selector learns ## virtual bullets are overlaid so the training signal the selector learns
@@ -254,6 +275,8 @@ type
tmPattern: TmPatternGun tmPattern: TmPatternGun
tmHorizon: TmHorizonGun tmHorizon: TmHorizonGun
leadGain: LeadGainGun leadGain: LeadGainGun
knowledge: KnowledgeGun
waveElm: WaveElmGun
mover: TFILModule mover: TFILModule
ringMover: TFILRingModule ringMover: TFILRingModule
strafeMover: StrafeModule strafeMover: StrafeModule
@@ -1316,6 +1339,8 @@ method run*(bot: ModularBot) =
var tmpPreds: array[len(PowerBins), GunPrediction] var tmpPreds: array[len(PowerBins), GunPrediction]
var tmhPreds: array[len(PowerBins), GunPrediction] var tmhPreds: array[len(PowerBins), GunPrediction]
var lgPreds: array[len(PowerBins), GunPrediction] var lgPreds: array[len(PowerBins), GunPrediction]
var gkPreds: array[len(PowerBins), GunPrediction]
var wePreds: array[len(PowerBins), GunPrediction]
# ── TR_VBULLET_ADMIT_ONLY gate ────────────────────────────────────── # ── TR_VBULLET_ADMIT_ONLY gate ──────────────────────────────────────
# Rack membership used to filter only SELECTION, so every unselected gun # Rack membership used to filter only SELECTION, so every unselected gun
# still ran predict()+spawnBullets() each tick to feed a fitness table the # still ran predict()+spawnBullets() each tick to feed a fitness table the
@@ -1332,7 +1357,8 @@ method run*(bot: ModularBot) =
admit[gi] = ModuleVBullets and admit[gi] = ModuleVBullets and
vBulletAdmitted(gi, bot.rackMode, ActiveRackMembership, vBulletAdmitted(gi, bot.rackMode, ActiveRackMembership,
VBulletAdmitOnly or gi == TmPatternId or VBulletAdmitOnly or gi == TmPatternId or
gi == TmHorizonId or gi == LeadGainId) gi == TmHorizonId or gi == LeadGainId or
gi == KnowledgeId or gi == WaveElmId)
for i in 0..<len(PowerBins): for i in 0..<len(PowerBins):
if admit[0]: headsUp[i] = bot.headOn.predict(bot.lastState, bulletSpeed(PowerBins[i])) if admit[0]: headsUp[i] = bot.headOn.predict(bot.lastState, bulletSpeed(PowerBins[i]))
if admit[1]: linPreds[i] = bot.linear.predict(bot.lastState, bulletSpeed(PowerBins[i])) if admit[1]: linPreds[i] = bot.linear.predict(bot.lastState, bulletSpeed(PowerBins[i]))
@@ -1358,6 +1384,18 @@ method run*(bot: ModularBot) =
# LEADGAIN: Pattern base, lead scaled by a per-band learned gain. # LEADGAIN: Pattern base, lead scaled by a per-band learned gain.
if admit[LeadGainId]: if admit[LeadGainId]:
lgPreds[i] = bot.leadGain.predict(bot.lastState, bulletSpeed(PowerBins[i])) lgPreds[i] = bot.leadGain.predict(bot.lastState, bulletSpeed(PowerBins[i]))
# KNOWLEDGE: forecast base + a learned additive residual. It is told WHO
# it is aiming at (target selection stays with enemy_tracker/target_
# selector) and how hot the turret is, and answers only the aim angle.
if admit[KnowledgeId]:
bot.knowledge.gunHeat = getGunHeat()
bot.knowledge.targetId = tid
gkPreds[i] = bot.knowledge.predict(bot.lastState, bulletSpeed(PowerBins[i]))
# WAVEELM: analytic intercept + a learned (x, y) offset from the online
# ELM. It is told WHO it aims at, so its per-enemy scan tracks line up.
if admit[WaveElmId]:
bot.waveElm.targetId = tid
wePreds[i] = bot.waveElm.predict(bot.lastState, bulletSpeed(PowerBins[i]))
if admit[0]: bot.tracker.spawnBullets(0, headsUp, bot.lastState, tid) if admit[0]: bot.tracker.spawnBullets(0, headsUp, bot.lastState, tid)
if admit[1] and not gunDisabled(1): bot.tracker.spawnBullets(1, linPreds, bot.lastState, tid) if admit[1] and not gunDisabled(1): bot.tracker.spawnBullets(1, linPreds, bot.lastState, tid)
@@ -1381,6 +1419,10 @@ method run*(bot: ModularBot) =
bot.tracker.spawnBullets(TmHorizonId, tmhPreds, bot.lastState, tid) bot.tracker.spawnBullets(TmHorizonId, tmhPreds, bot.lastState, tid)
if admit[LeadGainId] and not gunDisabled(LeadGainId): if admit[LeadGainId] and not gunDisabled(LeadGainId):
bot.tracker.spawnBullets(LeadGainId, lgPreds, bot.lastState, tid) bot.tracker.spawnBullets(LeadGainId, lgPreds, bot.lastState, tid)
if admit[KnowledgeId] and not gunDisabled(KnowledgeId):
bot.tracker.spawnBullets(KnowledgeId, gkPreds, bot.lastState, tid)
if admit[WaveElmId] and not gunDisabled(WaveElmId):
bot.tracker.spawnBullets(WaveElmId, wePreds, bot.lastState, tid)
# Build slim enemy table for tickBullets # Build slim enemy table for tickBullets
var enemyPositions: Table[int, tuple[x, y: float, lastSeenTick: int, alive: bool]] var enemyPositions: Table[int, tuple[x, y: float, lastSeenTick: int, alive: bool]]
@@ -1417,6 +1459,8 @@ method run*(bot: ModularBot) =
of TmPatternId: bot.tmPattern.onResult(fe) of TmPatternId: bot.tmPattern.onResult(fe)
of TmHorizonId: bot.tmHorizon.onResult(fe) of TmHorizonId: bot.tmHorizon.onResult(fe)
of LeadGainId: bot.leadGain.onResult(fe) of LeadGainId: bot.leadGain.onResult(fe)
of KnowledgeId: bot.knowledge.onResult(fe)
of WaveElmId: bot.waveElm.onResult(fe)
else: discard else: discard
if fe.hit: inc bot.virtualHits else: inc bot.virtualMiss if fe.hit: inc bot.virtualHits else: inc bot.virtualMiss
if DebugDrawOn and VBulletDebugOn: if DebugDrawOn and VBulletDebugOn:
@@ -1472,6 +1516,8 @@ method run*(bot: ModularBot) =
of TmPatternId: bot.tmPattern.predict(bot.lastState, bulletSpeed(power)) of TmPatternId: bot.tmPattern.predict(bot.lastState, bulletSpeed(power))
of TmHorizonId: bot.tmHorizon.predict(bot.lastState, bulletSpeed(power)) of TmHorizonId: bot.tmHorizon.predict(bot.lastState, bulletSpeed(power))
of LeadGainId: bot.leadGain.predict(bot.lastState, bulletSpeed(power)) of LeadGainId: bot.leadGain.predict(bot.lastState, bulletSpeed(power))
of KnowledgeId: bot.knowledge.predict(bot.lastState, bulletSpeed(power))
of WaveElmId: bot.waveElm.predict(bot.lastState, bulletSpeed(power))
else: bot.headOn.predict(bot.lastState, bulletSpeed(power)) else: bot.headOn.predict(bot.lastState, bulletSpeed(power))
let aimTarget = aimAngle(getX(), getY(), pred.x, pred.y) let aimTarget = aimAngle(getX(), getY(), pred.x, pred.y)
@@ -1560,7 +1606,7 @@ proc seedSelectorRng() =
when isMainModule: when isMainModule:
var bot = ModularBot( var bot = ModularBot(
tracker: vb.initTracker(NumRackGuns), # 0: HeadOn, 1: Linear, 2: Tsetlin, 3: Circular, 4: GuessFactor, 5: Pattern, 6: WallBounce, 7: Accel, 8: StopShot, 9: Displace, 10: AvgLead, 11: DecayGF, 12: KNN, 13: TMSelect, 14: TMPattern, 15: TMHorizon, 16: LeadGain tracker: vb.initTracker(NumRackGuns), # 0: HeadOn, 1: Linear, 2: Tsetlin, 3: Circular, 4: GuessFactor, 5: Pattern, 6: WallBounce, 7: Accel, 8: StopShot, 9: Displace, 10: AvgLead, 11: DecayGF, 12: KNN, 13: TMSelect, 14: TMPattern, 15: TMHorizon, 16: LeadGain, 17: Knowledge, 18: WaveElm
headOn: HeadOnGun(), headOn: HeadOnGun(),
linear: LinearGun(), linear: LinearGun(),
circular: CircularGun(), circular: CircularGun(),
@@ -1578,6 +1624,8 @@ when isMainModule:
tmPattern: initTmRadialGun(), tmPattern: initTmRadialGun(),
tmHorizon: initTmHorizonGun(), tmHorizon: initTmHorizonGun(),
leadGain: initLeadGainGun(), leadGain: initLeadGainGun(),
knowledge: initKnowledgeGun(),
waveElm: initWaveElmGun(),
radar: RadarLockModule(), radar: RadarLockModule(),
meleeRadar: initAdaptiveMeleeRadar(), meleeRadar: initAdaptiveMeleeRadar(),
mover: TFILModule(debugGraphics: DebugDrawOn), mover: TFILModule(debugGraphics: DebugDrawOn),
+10
View File
@@ -34,6 +34,7 @@ import movements/learned_surfer
import guns/tm_horizon import guns/tm_horizon
import guns/lead_gain import guns/lead_gain
import guns/pattern_matcher import guns/pattern_matcher
import guns/gun_knowledge
import vbullet_draw import vbullet_draw
import geo_overlay import geo_overlay
@@ -469,6 +470,14 @@ proc printEffectiveValues(ctx: EnvReportContext) =
if dep.len > 0: emit("legacy TR_BITBRAIN_* aliases honoured", "yes", "legacy") if dep.len > 0: emit("legacy TR_BITBRAIN_* aliases honoured", "yes", "legacy")
else: emit("legacy TR_BITBRAIN_* aliases honoured", "no", "default") else: emit("legacy TR_BITBRAIN_* aliases honoured", "no", "default")
# ── KNOWLEDGE, the learned residual gun (rack id 17) ──────────────────────
# One knob: where its learned table lives. Unset = memory only, i.e. nothing
# is ever written to disk. The table is allocated on FIRST USE, so this line
# reports the configured path, not a live table.
let gkMem = getEnv(GK_MEM_ENV, "").strip()
emit("TR_KNOWLEDGE_MEM", if gkMem.len > 0: gkMem else: "(unset -> memory only)",
sourceOf(GK_MEM_ENV))
# ── Pattern match-shape + radial knobs ──────────────────────────────────── # ── Pattern match-shape + radial knobs ────────────────────────────────────
# These are resolved lazily inside `predict` (which has not run at boot), so # These are resolved lazily inside `predict` (which has not run at boot), so
# unless something already forced them we report the raw env value and say so. # unless something already forced them we report the raw env value and say so.
@@ -629,6 +638,7 @@ proc knownEnvNames*(): seq[string] =
TMH_SHIFT_ENV, TMH_BIG_MULT_ENV, TMH_LOG_ENV, TMH_RESET_ON_TARGET_ENV, TMH_SHIFT_ENV, TMH_BIG_MULT_ENV, TMH_LOG_ENV, TMH_RESET_ON_TARGET_ENV,
TMH_WINDOW_ENV, TMH_RESET_DROP_ENV, TMH_NSTATES_ENV, TMH_ACCURVE_ENV, TMH_WINDOW_ENV, TMH_RESET_DROP_ENV, TMH_NSTATES_ENV, TMH_ACCURVE_ENV,
TMH_RETRAIN_EVERY_ENV, TMH_EPOCHS_ENV, TMH_RETRAIN_EVERY_ENV, TMH_EPOCHS_ENV,
GK_MEM_ENV,
LG_MEM_ENV, LG_GAINS_ENV, LG_N_ENV, LG_NADE_ENV, LG_RANGE_ENV, LG_LOG_ENV, LG_MEM_ENV, LG_GAINS_ENV, LG_N_ENV, LG_NADE_ENV, LG_RANGE_ENV, LG_LOG_ENV,
LG_MIN_OBS_ENV, LG_WARMUP_ENV, LG_ADAPT_ENV, LG_CALIB_ENV, LG_DECAY_ENV, LG_MIN_OBS_ENV, LG_WARMUP_ENV, LG_ADAPT_ENV, LG_CALIB_ENV, LG_DECAY_ENV,
LG_DECAY_FRAC_ENV, LG_SEED_ENV, LG_RESET_ON_TARGET_ENV, LG_DECAY_FRAC_ENV, LG_SEED_ENV, LG_RESET_ON_TARGET_ENV,
+2
View File
@@ -100,6 +100,8 @@ proc gunColors*(gunId: int): tuple[turret, bullet: string] =
of 14: ("#AAFF00", "#CCFF66") # TMPattern — lime of 14: ("#AAFF00", "#CCFF66") # TMPattern — lime
of 15: ("#00AAFF", "#66CCFF") # TMHorizon — sky of 15: ("#00AAFF", "#66CCFF") # TMHorizon — sky
of 16: ("#FF1493", "#FF69B4") # LEADGAIN — deep pink of 16: ("#FF1493", "#FF69B4") # LEADGAIN — deep pink
of 17: ("#8B4513", "#D2691E") # KNOWLEDGE — saddle brown
of 18: ("#7B68EE", "#9370DB") # WAVEELM — medium slate blue
else: ("#FFFFFF", "#FFFFFF") else: ("#FFFFFF", "#FFFFFF")
proc gunTurretColor*(gunId: int): string = gunColors(gunId).turret proc gunTurretColor*(gunId: int): string = gunColors(gunId).turret
+7 -6
View File
@@ -1,7 +1,8 @@
## Enemy tracker — deterministic radar lock + dead reckoning for PPO_Bot. ## Enemy tracker — deterministic radar lock + dead reckoning for PPO_Bot.
## No bot API imports; takes plain floats. ## Takes plain floats; only the SDK radar constants are used.
import std/math import std/math
import tankroyale_botapi/constants
type type
EnemyState* = object EnemyState* = object
@@ -75,14 +76,14 @@ proc normalizeRelative(angle: float64): float64 {.inline.} =
proc getRadarTurnRate*(tracker: var EnemyTracker; proc getRadarTurnRate*(tracker: var EnemyTracker;
botX, botY, botDirection, radarDirection: float64): float64 = botX, botY, botDirection, radarDirection: float64): float64 =
## Returns radar turn rate (degrees/tick, positive = right). ## Returns radar turn rate (degrees/tick, positive = right).
## Before contact: full 45° sweep. ## Before contact: full-speed sweep.
## After contact: lock with overshoot; widen if stale. ## After contact: lock with overshoot; widen if stale.
if not tracker.hasContact: if not tracker.hasContact:
return 45.0 return MAX_RADAR_TURN_RATE
if tracker.current.ticksSinceLastScan >= 8: if tracker.current.ticksSinceLastScan >= 8:
# Lost lock — widen sweep # Lost lock — widen sweep
return 45.0 return MAX_RADAR_TURN_RATE
# Bearing from radar to enemy. # Bearing from radar to enemy.
# Tank Royale radar directions use standard math convention (0=east, CCW+). # Tank Royale radar directions use standard math convention (0=east, CCW+).
@@ -94,7 +95,7 @@ proc getRadarTurnRate*(tracker: var EnemyTracker;
# Width Lock: overshoot proportional to arctan(36 / distance) # Width Lock: overshoot proportional to arctan(36 / distance)
let distance = sqrt(dx * dx + dy * dy) let distance = sqrt(dx * dx + dy * dy)
let extraTurn = min(arctan(36.0 / distance) * 180.0 / PI, 45.0) let extraTurn = min(arctan(36.0 / distance) * 180.0 / PI, MAX_RADAR_TURN_RATE)
if radarTurn < 0.0: radarTurn -= extraTurn if radarTurn < 0.0: radarTurn -= extraTurn
else: radarTurn += extraTurn else: radarTurn += extraTurn
result = radarTurn.clamp(-45.0, 45.0) result = radarTurn.clamp(-MAX_RADAR_TURN_RATE, MAX_RADAR_TURN_RATE)
+14 -4
View File
@@ -22,6 +22,10 @@ import virtual_bullets
# TR_RACK_KNN=off -> removed from both racks # TR_RACK_KNN=off -> removed from both racks
# TR_RACK_TMPATTERN=off (shipped default for the new TM pattern gun) # TR_RACK_TMPATTERN=off (shipped default for the new TM pattern gun)
# TR_RACK_LEADGAIN=both -> the per-range-band lead-gain corrector (id 16) # TR_RACK_LEADGAIN=both -> the per-range-band lead-gain corrector (id 16)
# TR_RACK_KNOWLEDGE=both -> the learned residual gun (id 17); it is a
# persistence-carrying gun, so the shipped default
# is `off` and it only ever touches disk when a
# caller admits it
# #
# SHIPPED DEFAULT IS `onlyPattern`: Pattern (id 5) is admitted in both racks and # SHIPPED DEFAULT IS `onlyPattern`: Pattern (id 5) is admitted in both racks and
# every other gun is `off`. This is a deliberate, measured decision, not a # every other gun is `off`. This is a deliberate, measured decision, not a
@@ -45,10 +49,11 @@ import virtual_bullets
# transition the radar uses. # transition the radar uses.
const const
RackGunNames*: array[17, string] = [ RackGunNames*: array[19, string] = [
"HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN", "HEADON", "LINEAR", "TSETLIN", "CIRCULAR", "GUESSFACTOR", "PATTERN",
"WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF", "WALLBOUNCE", "ACCEL", "STOPSHOT", "DISPLACE", "AVGLEAD", "DECAYGF",
"KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN"] "KNN", "TMSELECT", "TMPATTERN", "TMHORIZON", "LEADGAIN", "KNOWLEDGE",
"WAVEELM"]
RackEnvPrefix* = "TR_RACK_" RackEnvPrefix* = "TR_RACK_"
## THE rack size, derived from `RackGunNames`. Every per-gun-indexed array and ## THE rack size, derived from `RackGunNames`. Every per-gun-indexed array and
## loop in the bot and in the harness MUST be sized with this, never with a ## loop in the bot and in the harness MUST be sized with this, never with a
@@ -74,7 +79,7 @@ const
## it never spawns a virtual bullet unless explicitly enabled, so the shared ## it never spawns a virtual bullet unless explicitly enabled, so the shared
## VirtualTracker ring head — and every other gun's learning order — is ## VirtualTracker ring head — and every other gun's learning order — is
## unchanged. ## unchanged.
DefaultRackMembership*: array[17, RackMembership] = [ DefaultRackMembership*: array[19, RackMembership] = [
rmOff, # 0 HEADON — off (measured: worst over-selected gun) rmOff, # 0 HEADON — off (measured: worst over-selected gun)
rmOff, # 1 LINEAR — off rmOff, # 1 LINEAR — off
rmOff, # 2 TSETLIN — off rmOff, # 2 TSETLIN — off
@@ -91,7 +96,12 @@ const
rmOff, # 13 TMSELECT — off rmOff, # 13 TMSELECT — off
rmOff, # 14 TMPATTERN — off (already shipped off; TM pattern gun) rmOff, # 14 TMPATTERN — off (already shipped off; TM pattern gun)
rmOff, # 15 TMHORIZON — off (horizon-based TM corrector; expected to lose) rmOff, # 15 TMHORIZON — off (horizon-based TM corrector; expected to lose)
rmOff] # 16 LEADGAIN — off (per-range-band lead-gain corrector) rmOff, # 16 LEADGAIN — off (per-range-band lead-gain corrector)
rmOff, # 17 KNOWLEDGE — off (learned additive angular residual on top of
# the self-consistent lead forecast; see
# `guns/gun_knowledge.nim`)
rmOff] # 18 WAVEELM — off (online-ELM learned offset on the analytic
# intercept; see `guns/waveelm.nim`)
## NOTE: the table is registered in the SAME commit as the gun id and the live ## NOTE: the table is registered in the SAME commit as the gun id and the live
## wiring, so `TR_RACK_LEADGAIN=both` (or the legacy `TR_RACK_BITBRAIN=both`) ## wiring, so `TR_RACK_LEADGAIN=both` (or the legacy `TR_RACK_BITBRAIN=both`)
## are the ONLY things that admit that gun, and an unset environment is ## are the ONLY things that admit that gun, and an unset environment is
+1 -1
View File
@@ -73,7 +73,7 @@ proc testKnownNames() =
check "known set has no duplicates", known.len == s.len check "known set has no duplicates", known.len == s.len
check "known set only holds TR_*/GUN_* names", check "known set only holds TR_*/GUN_* names",
known.allIt(it.startsWith("TR_") or it.startsWith("GUN_")) known.allIt(it.startsWith("TR_") or it.startsWith("GUN_"))
check "known set covers all 17 rack names", check "known set covers every rack name (width derived, not a literal)",
RackGunNames.allIt((RackEnvPrefix & it) in s) RackGunNames.allIt((RackEnvPrefix & it) in s)
for name in ["TR_MOVEMENT", "TR_POWER_ENERGY_MIN", "TR_TMHORIZON_NSTATES", for name in ["TR_MOVEMENT", "TR_POWER_ENERGY_MIN", "TR_TMHORIZON_NSTATES",
"GUN_VBULLET_METRIC", "TR_ENV_REPORT", "GUN_SELECTOR_SEED", "GUN_VBULLET_METRIC", "TR_ENV_REPORT", "GUN_SELECTOR_SEED",
+2 -2
View File
@@ -164,8 +164,8 @@ proc testDefaultParity() =
let want = if i == 5: rmBoth else: rmOff let want = if i == 5: rmBoth else: rmOff
if m[i] != want: onlyPattern = false if m[i] != want: onlyPattern = false
check "parity: a clean env still loads the shipped onlyPattern rack", onlyPattern check "parity: a clean env still loads the shipped onlyPattern rack", onlyPattern
check "parity: the rack is still 17 guns at id 16 = LEADGAIN", check "parity: the rack is still one entry per gun and id 16 = LEADGAIN",
RackGunNames.len == 17 and RackGunNames[LeadGainId] == "LEADGAIN" RackGunNames.len == NumRackGuns and RackGunNames[LeadGainId] == "LEADGAIN"
var g = initLeadGainGun() var g = initLeadGainGun()
check "parity: a clean env resolves the shipped candidate set", check "parity: a clean env resolves the shipped candidate set",
g.cands == @[0.0, 0.25, 0.5, 0.75, 1.0] and g.memMode == lgPerRound g.cands == @[0.0, 0.25, 0.5, 0.75, 1.0] and g.memMode == lgPerRound
+7 -6
View File
@@ -158,14 +158,14 @@ proc testDefaultsOnlyPattern() =
DefaultRackMembership[12] == rmOff and DefaultRackMembership[13] == rmOff and DefaultRackMembership[12] == rmOff and DefaultRackMembership[13] == rmOff and
DefaultRackMembership[14] == rmOff DefaultRackMembership[14] == rmOff
check "defaults: the default rack admits ONLY Pattern in 1v1", check "defaults: the default rack admits ONLY Pattern in 1v1",
admittedGuns(17, rm1v1, DefaultRackMembership) == @[PatternId] admittedGuns(NumRackGuns, rm1v1, DefaultRackMembership) == @[PatternId]
check "defaults: the default rack admits ONLY Pattern in melee", check "defaults: the default rack admits ONLY Pattern in melee",
admittedGuns(17, rmMelee, DefaultRackMembership) == @[PatternId] admittedGuns(NumRackGuns, rmMelee, DefaultRackMembership) == @[PatternId]
let loaded = loadRackMembership() let loaded = loadRackMembership()
check "defaults: with a clean environment loadRackMembership() == shipped table", check "defaults: with a clean environment loadRackMembership() == shipped table",
loaded == DefaultRackMembership loaded == DefaultRackMembership
check "defaults: RackGunNames covers the shipped 17-gun rack", check "defaults: RackGunNames covers the shipped rack (width derived, not a literal)",
RackGunNames.len == 17 and DefaultRackMembership.len == 17 RackGunNames.len == NumRackGuns and DefaultRackMembership.len == NumRackGuns
proc testFloorRespectsAdmission() = proc testFloorRespectsAdmission() =
## The FLOOR path (`bestRate <= 0` or below the floor rate) historically fell ## The FLOOR path (`bestRate <= 0` or below the floor rate) historically fell
@@ -213,14 +213,15 @@ proc testRevertOverrideRestoresFullRack() =
if m[i] != want: full = false if m[i] != want: full = false
check "revert: the documented one-liner restores the all-`both` full rack", full check "revert: the documented one-liner restores the all-`both` full rack", full
check "revert: 1v1 rack admits every gun again (TMPATTERN excluded)", check "revert: 1v1 rack admits every gun again (TMPATTERN excluded)",
admittedGuns(17, rm1v1, m) == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16] admittedGuns(NumRackGuns, rm1v1, m) ==
@[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18]
clearRackEnv() clearRackEnv()
# The ADE+SBC gun (old rack id 17) is RETIRED, so `TR_RACK_BITBRAIN` is now # The ADE+SBC gun (old rack id 17) is RETIRED, so `TR_RACK_BITBRAIN` is now
# unambiguously LEADGAIN's old name: alone, it admits LEADGAIN and nothing else. # unambiguously LEADGAIN's old name: alone, it admits LEADGAIN and nothing else.
putEnv("TR_RACK_BITBRAIN", "both") putEnv("TR_RACK_BITBRAIN", "both")
let mLegacy = loadRackMembership() let mLegacy = loadRackMembership()
check "revert: the legacy TR_RACK_BITBRAIN alone selects LEADGAIN (16) only", check "revert: the legacy TR_RACK_BITBRAIN alone selects LEADGAIN (16) only",
mLegacy[16] == rmBoth and admittedGuns(17, rm1v1, mLegacy) == @[5, 16] mLegacy[16] == rmBoth and admittedGuns(NumRackGuns, rm1v1, mLegacy) == @[5, 16]
clearRackEnv() clearRackEnv()
proc testEnvOverrides() = proc testEnvOverrides() =
+13 -10
View File
@@ -14,8 +14,9 @@
## The fix derives every gun-indexed width from `NumRackGuns` (== `len(RackGunNames)`). ## The fix derives every gun-indexed width from `NumRackGuns` (== `len(RackGunNames)`).
## This test is the guard that would have caught it: ## This test is the guard that would have caught it:
## ##
## A. rack table — `NumRackGuns` is 17, 17 DISTINCT names, and the ## A. rack table — `NumRackGuns` is one entry per gun, DISTINCT names, and
## membership table and the legacy alias target are in range; ## the membership table and the legacy alias target are in
## range;
## B. source shape — `ModularBot.nim` contains NO literal width/loop bound ## B. source shape — `ModularBot.nim` contains NO literal width/loop bound
## narrower than `NumRackGuns` for the gun-indexed ## narrower than `NumRackGuns` for the gun-indexed
## accounting, and sizes them with `NumRackGuns`; ## accounting, and sizes them with `NumRackGuns`;
@@ -26,10 +27,12 @@
## D. live (opt-in) — with a rack that admits ONLY the newest id, the bot ## D. live (opt-in) — with a rack that admits ONLY the newest id, the bot
## selects it, fires and lands hits (skipped without JARs). ## selects it, fires and lands hits (skipped without JARs).
## ##
## The ADE+SBC gun (rack id 17) was later RETIRED, so the rack is back to 17 and ## The ADE+SBC gun (rack id 17) was later RETIRED, so the rack went back to 17
## the newest id is LEADGAIN (16). The guard is unchanged in shape and in ## with LEADGAIN (16) as the newest id. KNOWLEDGE now occupies id 17 again, so
## strength: C3 now proves the fix survives a rack that grows again, which is ## the newest id is asserted as a DERIVED value (`NumRackGuns - 1`), never a
## the general form of the bug that shipped. ## literal: the guard is unchanged in shape and in strength, and C3 still proves
## the fix survives a rack that grows again, which is the general form of the bug
## that shipped.
## ##
## Run: nim c -r common_libs/tests/test_rack_stat_width.nim ## Run: nim c -r common_libs/tests/test_rack_stat_width.nim
## Live: TR_SERVER_JAR=... TR_BATTLE_RUNNER=... nim c -r common_libs/tests/test_rack_stat_width.nim ## Live: TR_SERVER_JAR=... TR_BATTLE_RUNNER=... nim c -r common_libs/tests/test_rack_stat_width.nim
@@ -47,7 +50,7 @@ const
adversaryDir = repoRoot / "common_libs" / "test_framework" / "adversaries" / "SittingDuck" adversaryDir = repoRoot / "common_libs" / "test_framework" / "adversaries" / "SittingDuck"
statsPath = "/tmp/rack_stat_width_stats.jsonl" statsPath = "/tmp/rack_stat_width_stats.jsonl"
PatternId = 5 PatternId = 5
NewestId = NumRackGuns - 1 ## 16 (LEADGAIN), the newest rack id NewestId = NumRackGuns - 1 ## the newest rack id (KNOWLEDGE)
LegacyLeadGainId = 16 LegacyLeadGainId = 16
var failures = 0 var failures = 0
@@ -59,7 +62,7 @@ proc check(name: string, ok: bool) =
proc testRackTable() = proc testRackTable() =
check "A1: NumRackGuns is derived from RackGunNames", check "A1: NumRackGuns is derived from RackGunNames",
NumRackGuns == RackGunNames.len and NumRackGuns == 17 NumRackGuns == RackGunNames.len and NumRackGuns > 0
check "A2: rack membership table has one entry per gun", check "A2: rack membership table has one entry per gun",
DefaultRackMembership.len == NumRackGuns DefaultRackMembership.len == NumRackGuns
var seen = initTable[string, bool]() var seen = initTable[string, bool]()
@@ -176,9 +179,9 @@ proc testAccounting() =
check "C3: a rack one gun WIDER is still fully covered by the NumRackGuns width", check "C3: a rack one gun WIDER is still fully covered by the NumRackGuns width",
grownOk and grown[NumRackGuns] == 1 grownOk and grown[NumRackGuns] == 1
# The legacy namespace: TR_RACK_BITBRAIN is now unambiguously LEADGAIN's old # The legacy namespace: TR_RACK_BITBRAIN is unambiguously LEADGAIN's old
# name (the ADE+SBC gun that briefly owned it was retired), so it always # name (the ADE+SBC gun that briefly owned it was retired), so it always
# admits LEADGAIN (16) — the newest id — and nothing else. # admits LEADGAIN (16) — and nothing else, not the gun that reused id 17.
for n in RackGunNames: delEnv("TR_RACK_" & n) for n in RackGunNames: delEnv("TR_RACK_" & n)
delEnv("TR_BITBRAIN_NET") delEnv("TR_BITBRAIN_NET")
putEnv("TR_RACK_BITBRAIN", "both") putEnv("TR_RACK_BITBRAIN", "both")
@@ -62,7 +62,8 @@ proc seedOldRack(t: var VirtualTracker, targetId: int) =
# ── registration table ──────────────────────────────────────────────────────── # ── registration table ────────────────────────────────────────────────────────
proc testTable() = proc testTable() =
check "rack: RackGunNames has 17 entries", RackGunNames.len == 17 check "rack: RackGunNames has one entry per rack gun (width derived)",
RackGunNames.len == NumRackGuns
check "rack: the new gun is named TMPATTERN at id 14", check "rack: the new gun is named TMPATTERN at id 14",
RackGunNames[TmPatternId] == "TMPATTERN" RackGunNames[TmPatternId] == "TMPATTERN"
check "rack: the new gun defaults to `off`", check "rack: the new gun defaults to `off`",
+9 -3
View File
@@ -399,14 +399,14 @@ tank.
| variable | default | what it does | | variable | default | what it does |
|---|---|---| |---|---|---|
| `TR_RACK_<GUN>` | `PATTERN=both`, all other 15 guns `off` | membership: `both` \| `1v1` \| `melee` \| `off` | | `TR_RACK_<GUN>` | `PATTERN=both`, all other 17 guns `off` | membership: `both` \| `1v1` \| `melee` \| `off` |
| `GUN_RACK_DISABLE` | empty | comma-separated gun **ids** to remove entirely (older mechanism; the gun never even spawns virtual bullets) | | `GUN_RACK_DISABLE` | empty | comma-separated gun **ids** to remove entirely (older mechanism; the gun never even spawns virtual bullets) |
| `GUN_STATS_PATH` | `/tmp/gun_stats.jsonl` | where the per-round per-gun stats are written | | `GUN_STATS_PATH` | `/tmp/gun_stats.jsonl` | where the per-round per-gun stats are written |
| `GUN_SHOTLOG_PATH` | `/tmp/shot_log.jsonl` | where the per-shot JSONL is written | | `GUN_SHOTLOG_PATH` | `/tmp/shot_log.jsonl` | where the per-shot JSONL is written |
`<GUN>` names (ids 0-15, `selector.nim:52`): `<GUN>` names (ids 0-17, `selector.nim:RackGunNames`):
`HEADON LINEAR TSETLIN CIRCULAR GUESSFACTOR PATTERN WALLBOUNCE ACCEL STOPSHOT `HEADON LINEAR TSETLIN CIRCULAR GUESSFACTOR PATTERN WALLBOUNCE ACCEL STOPSHOT
DISPLACE AVGLEAD DECAYGF KNN TMSELECT TMPATTERN TMHORIZON`. DISPLACE AVGLEAD DECAYGF KNN TMSELECT TMPATTERN TMHORIZON LEADGAIN KNOWLEDGE`.
Shipped default membership (`selector.nim:DefaultRackMembership`): Shipped default membership (`selector.nim:DefaultRackMembership`):
@@ -420,6 +420,8 @@ Shipped default membership (`selector.nim:DefaultRackMembership`):
| **PATTERN** | **both** | TMSELECT | off | | **PATTERN** | **both** | TMSELECT | off |
| WALLBOUNCE | off | TMPATTERN | off | | WALLBOUNCE | off | TMPATTERN | off |
| ACCEL | off | TMHORIZON | off | | ACCEL | off | TMHORIZON | off |
| STOPSHOT | off | LEADGAIN | off |
| KNOWLEDGE | off | | |
`TR_RACK_<GUN>` accepts aliases: `both`/`any`/empty → both; `TR_RACK_<GUN>` accepts aliases: `both`/`any`/empty → both;
`1v1`/`single`/`lock` → 1v1; `melee`/`multi` → melee; `1v1`/`single`/`lock` → 1v1; `melee`/`multi` → melee;
@@ -429,6 +431,10 @@ to `both`** (`selector.nim:parseRackMembership`).
The `1v1`/`melee` split is driven by **server truth**, `getEnemyCount()`: The `1v1`/`melee` split is driven by **server truth**, `getEnemyCount()`:
`== 1` → 1v1 rack, `> 1` → melee rack (`virtual_bullets.rackMode`). `== 1` → 1v1 rack, `> 1` → melee rack (`virtual_bullets.rackMode`).
| variable | default | what it does |
|---|---|---|
| `TR_KNOWLEDGE_MEM` | empty (memory only) | path of the learned table `KNOWLEDGE` (id 17) loads at the first round boundary and re-saves (atomically, after a prune) at every boundary. Unset = nothing is ever written to disk. |
**Empty-set fallback:** if every gun is filtered out for a mode, the *selector* **Empty-set fallback:** if every gun is filtered out for a mode, the *selector*
falls back to the **full rack** so it can never end up with no gun falls back to the **full rack** so it can never end up with no gun
(`admittedGuns`, `virtual_bullets.nim`). Note this fallback is on *selection*; (`admittedGuns`, `virtual_bullets.nim`). Note this fallback is on *selection*;
+14 -2
View File
@@ -48,8 +48,20 @@ is smooth but limited to 4°/tick at top speed.
### Coordinate system ### Coordinate system
North = 0°, clockwise. `directionTo` in `utils.nim` returns a bearing in East = 0°, North = 90°, positive angles increase counter-clockwise (Y increases
`[0, 360)`. `bearingTo` returns a signed relative bearing in `(-180, 180]`. upward, so the arena's bottom edge is Y = 0). `directionTo` in `utils.nim`
returns a bearing in `[0, 360)`. `bearingTo` returns a signed relative bearing in
`(-180, 180]`.
> **Note — the SDK's own doc comments are wrong here.** `bot.nim:183/187/191`,
> `utils.nim:68` and the examples at `utils.nim:159-161` and `~197` all claim
> "0 = North, 90 = East". The **implementation is authoritative**, not the
> comments: `utils.nim:162` computes
> `normalizeAbsoluteAngle(180.0 * arctan2(toY - fromY, toX - fromX) / PI)`, i.e.
> plain `arctan2(dy, dx)`, and `bot.nim:178` puts the arena's bottom edge at
> `Y = 0`. Running the SDK's own `directionTo` (robocode_tankroyale_botapi
> 1.0.7) returns `0.0` for East and `90.0` for North, and `bearingTo` agrees.
> Do not "fix" this section back to the commented convention.
--- ---