Files
SirRoboGarage/DevControlBot_garage/README.md
T

704 lines
35 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# DevControlBot
Control skeleton bot: it boots, participates in the battle, and drives **no
movement and no gun**. The radar is the only driven part.
All radar logic is **one module**, `modules/radar.nim` (90 lines including its
comments; two procs, three variables, three constants). `run()` just calls
`commandRadar()`.
**Two commands, one decision.** Exactly one enemy alive *and* a target in hand ->
**lock** (servo onto the target's bearing). Anything else -> **sweep** at
`MaxRadarTurn` = 45 deg/tick, the radar's physical cap, i.e. a full revolution
every 8 turns. The sweep does double duty and needs no separate "melee" mode: it
is both the search when no target is in hand and the right answer for 2+ enemies
(a full revolution re-scans every enemy as fast as the physics allow, and locking
one of several is worthless). The choice is made from the API's
`getEnemyCount()` (bot.nim:166, from `tick.botState.enemyCount`, bot.nim:1295;
field at schemas.nim:134) every tick — the server's alive count, so it cannot
drift and it shrinks by itself when an enemy dies. No counter, no seen-id set, no
mode enum, no dispatch table.
**There is never a tick without a command.** `commandRadar()` ends in
`setRadarTurnRate(...)` on *every* path — the sweep is not a state the lock falls
back *into*, it is the single command the lock replaces. Switching costs zero
turns, in either direction, by construction.
**The lock works because of the 5° overshoot.** The commanded rate is the delta
from the radar's *current* heading to the target's bearing, plus 5° **past** it
in the direction of the turn, clamped to ±45. So the radar sweeps *across* the
bearing every tick instead of settling on it — which is what produces a fresh
`ScannedBotEvent` every tick. (Turning by the bare error, or holding inside a
deadzone, parks the radar on the bearing: the scans stop and the target has to be
re-found by the sweep, which is the delay this design removes. The `setRescan()`
trick this used to need is unnecessary here — the radar is never idle.) The
bearing is recomputed from the target's remembered **absolute position** each
tick, so the lock keeps correcting a target, and a radar, that have moved.
**Lost-target safety.** `scanlessTicks` counts the ticks since the target was last
scanned (reset by every scan) and `FreshScanTurns = 10` is how long a remembered
target stays usable — one sweep revolution plus slack. This can never throw a
good lock away: a working lock re-scans its target *every* tick, so the counter
never gets past ~1. It only bites on a target unseen for a while, where locking
would slew blindly at a stale point; the sweep re-finds it within one revolution
instead. The target is then dropped and the sweep resumes on the same tick.
`onScannedBot` is a one-liner — `onScan(e.x, e.y)` — and issues no command:
`go()` sends the tick's intent *before* dispatching the pending events, so
commanding first means the command is part of THIS tick's intent, while
`onScannedBot` only feeds the next one.
Angles are **0° = east, positive = counter-clockwise = turn LEFT**: proven from
the installed API — `directionTo` is `180 * arctan2(dy, dx) / PI`
(utils.nim:146-165, its "0 = North" doc comment contradicts its own code), and
`setTurnRadarLeft` sets a positive rate while `setTurnRadarRight` is
`setTurnRadarLeft(-degrees)` (bot.nim:1062-1070).
**Provenance.** The design is ModularBot's (Davide Cappellini, Apache-2.0), i.e.
`common_libs/radar_lock/radar_lock.nim` (`doRadar`, which is where the overshoot
comes from) and `common_libs/radars/melee_scan.nim`, picked per tick exactly this
way in `ModularBot.nim`: `let targetMode = if getEnemyCount() == 1: 0 else: 1`.
`common_libs/` is never edited in place.
**Measured** (1 round each, RadarSpy observer; scans/turn, idle = turns with no
radar command, max gap = longest run of turns without a scan):
| battle | version | scans/turn | idle turns | max scan gap |
|---|---|---|---|---|
| 1v1 Walls | before | 0.513 | **391 / 509** | **33 turns** |
| 1v1 Walls | now | **0.960** | **0** | **1 turn** |
| vs 2 adversaries | before | 0.256 | 0 | 8 |
| vs 2 adversaries | now | 0.278 | 0 | 8 |
| vs 2 adversaries (3 bots, mixed) | before | 0.462 | 233 | 32 |
| vs 2 adversaries (3 bots, mixed) | now | 0.548–0.644 | **0** | **8** |
The 2-enemy rows are identical by construction (both versions issue the same
45 deg/tick sweep). When the count drops to 1 mid-round the new radar is
acquiring again within 6 turns and never parks; the old one took 29 turns and
sat at rate 0 for 26 of them.
The radar keeps moving forever: sweeping at full rate until an enemy is
scanned, servoing onto it while it is the only one alive, spinning at the cap as
soon as a second one is alive, and dropping straight back to the lock when one of
them dies. All of it is in `DevControlBot/modules/radar.nim`.
Body, turret, gun and radar all start plain **white**, which by team convention
means "not programmed yet". The radar then claims its **own** colours when it
starts working: `initRadar()` (`DevControlBot/modules/radar.nim`) paints the radar
and the scan arc **black** — black = "programmed and running" — while
body/turret/gun stay white (this bot never moves and never fires). Colors are set
**once** (startup + radar init), never inside the tick loop.
## Layout
```
DevControlBot_garage/
├── AGENTS.md
├── README.md
└── DevControlBot/
├── DevControlBot.nim # bot type + entry point (isMainModule)
├── DevControlBot.json # bot metadata
├── DevControlBot.nimble # the single `runBot` task
├── DevControlBot.sh # BotLauncher entry point
└── .env # OPTIONAL local config (secrets; never commit)
```
There is no `src/`, no `tests/`, no `out/`, no `config.nim`, no `nimble.paths`
and no vendor directory. `DevControlBot.nim` is both the bot implementation and
the program entry point.
## Dependencies
Only two, both installed **globally** with Nimble and resolved from the global
package store — nothing vendored, no `nimble.paths`, no `nimble develop`:
- `robocode_tankroyale_botapi >= 1.0.7` (the renamed `tankroyale_botapi`)
- `jsony >= 1.1.5`
```sh
nimble install robocode_tankroyale_botapi
```
The `runBot` task asks Nimble where each of those packages actually lives
(`nimble path <pkg>`) and passes explicit `--path:` flags to `nim c`. This is
required because the compiler's own `nimblepath="$home/.nimble/pkgs2/"` only
works when `$HOME` is set — with an empty environment (`env -i`, Nix build
sandbox, CI) the packages are otherwise not on the search path. If a package is
not installed, the build stops with `run: nimble install <pkg>` instead of a
compiler error.
## Run
```sh
./DevControlBot/DevControlBot.sh
```
`DevControlBot.sh` is the **BotLauncher entry point**. It is a thin wrapper: it
locates itself, `chdir`s to the directory holding the `.nimble` file, forwards
arguments and signals to `nimble runBot`, and propagates the real exit code.
All build/run/cleanup logic lives in the `runBot` task of `DevControlBot.nimble`,
which creates a throwaway `mktemp -d` build dir, compiles there, runs, and always
removes the dir via an `EXIT`/`INT`/`TERM` trap. **Nothing is left behind** — this
bot never creates an `out/` directory.
`runBot` also accepts a metadata path: **as the first positional argument**. If it
ends in `.json` it is used instead of the bundled `DevControlBot.json`; there is
no `--json` flag (an argument that does not end in `.json` is forwarded to the bot
as-is).
```sh
./DevControlBot/DevControlBot.sh # bundled metadata (default)
./DevControlBot/DevControlBot.sh /path/to/my.json # alt metadata
./DevControlBot/DevControlBot.sh --debug /path/to/my.json # alt metadata, debug build
```
With **no arguments at all** the wrapper does *not* print usage: it performs a
quiet RELEASE build and runs the bot with the bundled `DevControlBot.json`,
exactly as if that path had been passed. Usage is printed **only** for an
explicit `-h` / `--help` (exit 0, nothing is built).
## Configuration comes from the environment — the API's own mechanism
No configuration code exists in `DevControlBot.nim`, and none is needed. The
bot API reads its own environment variables inside `start()`:
| variable | read at | default |
|---|---|---|
| `SERVER_URL` | `robocode_tankroyale_botapi.nim:424` (documented at `:396`) | `ws://localhost:7654` |
| `SERVER_SECRET` | `robocode_tankroyale_botapi.nim:425` | `""` |
| `BOT_NAME`, `BOT_VERSION`, `BOT_AUTHORS`, … | `bot_info.nim:117-130`, used only when no JSON is found | see that file |
This is the supported mechanism the official BotLauncher uses: it puts those
variables in the bot's process environment before starting the binary. So the
only thing the build/run wrapper does is make sure the variables are *present*
in the bot's environment for local runs.
## Optional `.env` (a convenience for local runs only)
`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
the API defaults apply. It is not required, not generated, and not committed.
When present it is loaded by the **`runBot` task**, not by `DevControlBot.sh`, so
it applies identically to `./DevControlBot.sh` and to a direct `nimble runBot`
and the wrapper stays a thin wrapper. Properties:
- **Format:** plain `NAME=value` and `export NAME=value` lines; blank lines and
`#` comments ignored; anything that is not a simple `NAME=value` identifier
assignment is ignored (a `.env` can never smuggle in a command).
- **CRLF tolerant:** `CR` characters are stripped, so a Windows-edited file does
not turn the value into `bar\r`.
- **Nothing is ever printed.** Only the *names* taken from the file are reported,
never a value, and `set -x` is not used.
- **Overridable path:** `$DEVCONTROLBOT_ENV_FILE` points the loader at a
different file (useful for testing).
### Precedence: the environment always wins
A variable **already present in the environment is never overridden** by the
`.env` file. This matters because the official BotLauncher's values must win:
if a `.env` sitting in the checkout could overwrite them, this convenience would
silently break a real BotLauncher run.
The `.env` file is therefore **not** simply sourced — sourcing it would do the
opposite, because an assignment in a sourced file overwrites an already-exported
variable of the same name. Instead the file is **filtered line by line**: a
`NAME=value` line is dropped when `NAME` is already set in the environment
(tested with `[ -n "${NAME+x}" ]`, i.e. *set but possibly empty*, not merely
non-empty), and only the still-unset names are then exported with `set -a` and
sourced. The filtering is what implements the precedence.
```sh
SERVER_URL=ws://host:1234 ./DevControlBot.sh # shell wins, .env ignored for SERVER_URL
./DevControlBot.sh # .env supplies SERVER_URL
```
`.env` contains secrets, so it must never be committed; see the note in
[AGENTS.md](AGENTS.md) about the root `.gitignore`.
## Build modes: release by default, `--debug` for the classic build
| invocation | build | output |
|---|---|---|
| `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 |
### 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
repeated `--debug` is harmless) and is handed to the `runBot` task via the
exported env var `$DEVCONTROLBOT_DEBUG` (`debug` / `release`) rather than as a
task argument: an env var can never be mistaken for a bot argument, cannot
collide with the `$DEVCONTROLBOT_STATUS_FILE` exit-code mechanism, and leaves the
task's argument parsing untouched. Every other argument is forwarded verbatim.
In release mode the compiler's stdout/stderr is captured to a log and replayed
**only if the build fails**, so a failed build is always loud in both modes while
a successful release build stays short (10 lines including the no-server report,
vs 16 with `--debug`). `--help` / `-h` prints usage and exits 0 **without
building**; no arguments does the opposite — it builds and runs.
The bot needs a running Tank Royale server at `SERVER_URL` (the API's documented
default is `ws://localhost:7654`); without one the run fails with
`[start] Cannot connect to <SERVER_URL>` and exits 1 (expected during local
verification).
## Failure reporting and exit codes
Nimble's `exec` raises a NimScript exception — stack trace, escaped copy of the
whole script — for *any* non-zero exit, which made "no game server" look like a
catastrophic build crash. The `runBot` shell therefore always exits 0 and writes
the real code to the status file named by `$DEVCONTROLBOT_STATUS_FILE`, which
`DevControlBot.sh` exports and then re-exits with. The real code is preserved,
not masked.
| exit | meaning |
|---|---|
| `0` | clean run |
| `1` | bot could not connect to the game server at `SERVER_URL` (expected locally) |
| `2` | a dependency is not installed — `nimble install <pkg>` |
| `3` | compilation failed — the compiler's own errors are printed above |
| other | the bot's own exit code (runtime crash, bad metadata) |
Each mode prints its own short line, e.g.
```
[start] Cannot connect to ws://localhost:7654: Connection refused
[devcontrolbot] bot exited with code 1.
[devcontrolbot] No game server on ws://localhost:7654 (SERVER_URL).
[devcontrolbot] Start the Tank Royale server, or point SERVER_URL at a running one.
```
No `Exception raised during nimble script execution`, no stack trace, no source
dump. `nimble runBot` run directly (no status file) keeps the old behaviour and
still raises.
Interrupt handling is unchanged: SIGINT/SIGTERM are forwarded, the build dir is
removed by the `EXIT` trap and the wrapper exits 143 (SIGTERM) / 130 (SIGINT).
## Gotcha: `nimble runBot` must be run from `DevControlBot/`
The `.nimble` file lives in `DevControlBot/`, so the task is only visible from
there:
```sh
cd DevControlBot && nimble runBot # works
cd DevControlBot_garage && nimble runBot
# Error: Could not find a file with a .nimble extension inside the specified
# directory: .../DevControlBot_garage
```
`DevControlBot.sh` handles this for you by `cd`-ing itself. Note also that
`compile`/`build` are reserved Nimble builtin names — hence the `runBot` name.
## Test
There are **no tests** in this garage. The `test` task and the `tests/` directory
were removed along with the old build layout; see
## Movement-prediction gun
The gun predicts **where the enemy will actually be when the bullet arrives**.
The old model predicted the opponent's aim error (how far *their* shots missed a
correct intercept); using that as our own correction made the gun aim like the
opponent, which is why it added a constant +1.6°..+11.5° bias and lost to the
plain geometric gun. That path is deleted (`train_elm_gun.nim` removed,
`extract_realistic.py` marked deprecated). The base geometric intercept is still
the base lead (`heuristicAim`); the ELM now refines it with a movement
prediction.
### The label
For every sampled tick (shooter fixed to DevControlBot, power 2, bullet speed
`20 - 3*2 = 14`, so shooter state and bullet speed match the live gun):
* **base** = the plain geometric intercept bearing from the enemy's current
scan-based position/velocity (the same `heuristicAim`);
* **true** = bearing to the enemy's ACTUAL position at the tick the bullet
reaches it, solved by fixed-point iteration against the observer's true
trajectory;
* **label** = `wrap(true - base)`.
Generated by `tools/elm_bench/extract_predict.py` (stride 5) over
`data/drussgt_raw` + `data/generalization_raw` into `samples_predict.ndjson`
(53 980 samples, 9 opponents, gitignored and reproducible).
| | mean | sd | p5 | median | p95 |
|---|---|---|---|---|---|
| label | **-0.329°** | 18.322° | -32.68° | -0.35° | +32.81° |
**Centred near zero.** The old opponent-bias label had a large systematic offset
(+0.042 rad = +2.4°); this one does not (-0.006 rad = -0.33°). On a target that
holds its line the label is 0; only real turning/acceleration moves it.
### Features (`elm_features.nim`, 32-D)
Enemy-motion-centric: 7 newest-to-oldest scan-to-scan displacement vectors (each
divided by its own tick gap, /16), newest/mean/sd speed, heading sin/cos, turn
rate sin/cos, curvature, plus the single-frame geometry (distance, relative
bearing, own speed, bullet speed, time of flight, `predErr`, lateral velocity,
closing speed, LOS rate). The motion window (`WinCap = 8`) is fed from
`modules/radar.nim`'s new scan buffer. One definition is shared verbatim by the
trainer and the gun.
### Training (`train_predict.nim`, 5 round-group folds, pooled held-out)
| model | RMSE | MAE | medAE | predMean |
|---|---|---|---|---|
| plain intercept (correction 0) | 0.31983 | 0.23227 | 0.15208 | 0 |
| constant mean | 0.31978 | 0.23219 | 0.15173 | -0.00577 |
| ELM H=256 λ=1e-2 | **0.23101** | **0.18174** | **0.14966** | **-0.00631** |
| ELM H=128 λ=1e-2 | 0.23934 | 0.19052 | 0.15856 | -0.00630 |
The ELM beats the plain intercept by **-27.8% RMSE** and beats a constant by the
same. Its output mean is **-0.0063 rad (-0.36°)** — the centring failure of the
old model is gone. (H=64: RMSE 0.24895.)
### Confidence gate
The correction is applied only when `|correction| > GATE_TAU`, else the gun
returns the exact geometric aim. `GATE_TAU = 0.10 rad (5.7°)`, the largest
0.05-grid threshold whose gated RMSE stays within 2% of the un-gated model:
**open-rate 61.4%**, gated RMSE 0.23348 (-27.0% vs the intercept). The offline
optimum is `tau = 0` (the model helps at every magnitude), so the gate is a
conservative filter for the small/noisy corrections, not a performance device.
### Real battles — 20 rounds each, RawRecord observer ground truth, all CONTIGUOUS
Damage per round is primary. `won/rd` = rounds where DevControlBot ranked first.
| opponent | gun | shots | hits | hit% | damage | dmg/rd | won/rd |
|---|---|---|---|---|---|---|---|
| DrussGT | geometric | 547 | 6 | 1.1% | 60 | 3.0 | 0/20 |
| DrussGT | ELM-gated | 656 | 16 | 2.4% | 160 | **8.0** | 0/20 |
| CassiusClay | geometric | 357 | 1 | 0.3% | 10 | 0.5 | 0/20 |
| CassiusClay | ELM-gated | 427 | 14 | 3.3% | 140 | **7.0** | 0/20 |
| Komarious | geometric | 356 | 29 | 8.1% | 290 | 14.5 | 0/20 |
| Komarious | ELM-gated | 550 | 95 | 17.3% | 950 | **47.5** | **10/20** |
| Phoenix | geometric | 350 | 3 | 0.9% | 30 | 1.5 | 0/20 |
| Phoenix | ELM-gated | 447 | 8 | 1.8% | 80 | **4.0** | 0/20 |
Damage per *shot* also rises (DrussGT 0.11 -> 0.24, Komarious 0.81 -> 1.73):
the gain is accuracy, not just volume.
Aim error at fire versus the **TRUE impact point** (deg; reference solved against
the observer's true trajectory, so lead is not counted as error — this is not the
constant-velocity reference printed by `score_battles.py`):
| opponent | gun | n | mean | median | sd |
|---|---|---|---|---|---|
| DrussGT | geometric | 542 | -2.56 | -12.13 | 33.96 |
| DrussGT | ELM-gated | 647 | -4.27 | -9.24 | **23.39** |
| CassiusClay | geometric | 341 | -1.70 | -3.56 | 40.64 |
| CassiusClay | ELM-gated | 413 | -2.96 | -6.20 | **29.11** |
| Komarious | geometric | 352 | 0.62 | -1.61 | 23.49 |
| Komarious | ELM-gated | 529 | -2.66 | -2.05 | **12.96** |
| Phoenix | geometric | 331 | 0.92 | 5.38 | 41.55 |
| Phoenix | ELM-gated | 426 | -1.91 | 0.10 | **28.38** |
The ELM cuts the aim-error spread by 30-45% against every opponent.
### Bottom line
**Yes — with the movement label the ELM now beats the plain intercept in real
battles**, on damage/round against all four opponents (2.7x..14x), with a higher
hit rate, more damage per shot, one 10/20 round win vs Komarious, and a
30-45% smaller true-impact aim-error spread. The old model's fatal constant bias
is gone (predMean -0.36° vs +2.4°).
Honest caveats: these four opponents are *in* the pooled training corpus (same
bots, different recording), so this is not a held-out-opponent generalisation
claim; the absolute hit rate against DrussGT is still only 2.4%. The gain is
real but the gun is still weak.
### Files and reproduction
| file | what |
|---|---|
| `DevControlBot/modules/ELM/elm_features.nim` | the 32-D enemy-motion feature vector (shared trainer/gun) |
| `DevControlBot/modules/ELM/elm_gun.nim` | geometric `heuristicAim`, ELM correction, gate, weights loader |
| `DevControlBot/modules/radar.nim` | scan buffer (window of the last 8 scans) |
| `DevControlBot/modules/ELM/elm_gun_weights.txt` | exported weights + `GATE_TAU` |
| `tools/elm_bench/extract_predict.py` | relabel: true-impact correction corpus |
| `tools/elm_bench/train_predict.nim` | 5-fold eval, baselines, gate calibration, export |
```sh
cd DevControlBot_garage/DevControlBot
python3 ../../tools/elm_bench/extract_predict.py /tmp/samples_predict.ndjson \
../../data --stride=5
nim c -r --hints:off --path:. ../../tools/elm_bench/train_predict.nim /tmp/samples_predict.ndjson
nim c -d:release --out:/tmp/DevElm DevControlBot.nim # ELM-gated gun
nim c -d:release -d:baselineGun --out:/tmp/DevBase DevControlBot.nim # intercept only
# battles: java -cp tools/raw_recorder/out:$RUNNER_JAR RawRecord \
# --dir /tmp/rec --rounds 20 --bot <DevElm dir> --bot <opponent dir>
python3 tools/elm_bench/score_battles.py /tmp/rec_Elm_DrussGT /tmp/rec_Base_DrussGT
```
## Sample-bot gate (held-out opponents)
**Question.** The movement-prediction ELM beat the geometric intercept by
2.7x–14x on DrussGT, CassiusClay, Komarious and Phoenix — but all four are *in*
the pooled training corpus. Do the gains survive on bots the model has never
trained on? This is the first genuine held-out-opponent test.
**Method.** The 13 runnable Nim sample bots from `tr_bots/` (`SAMPLE_BOTS.md`;
`MyFirstTeam` skipped, it is a team container). Each fought both arms for 10
rounds, RawRecord observer ground truth: `Base` = `-d:baselineGun` (pure
intercept), `ELM` = default build. The ELM arm additionally carries
`-d:gunLog`, a logging-only define that changes no gun behaviour, so the raw
per-shot corrections (and therefore the gate state) could be read. All 26
recordings `query.py --verify`: **CONTIGUOUS, no drops, no dups**. Build:
`nim c -d:release [-d:baselineGun|-d:gunLog]`.
### Damage per round (primary)
Most sample bots are so weak that both arms kill them every round, so this
metric saturates at the ~100–110 dmg/rd ceiling. The un-saturated rows are the
moving/beatable bots (Crazy, MyFirstBot, MyFirstLeader, SpinBot, Walls).
| sample bot | intercept dmg/rd | ELM dmg/rd | delta | won/rd int / ELM |
|---|---:|---:|---:|---:|
| Corners | 93 | 93 | 0 | 10/10 / 10/10 |
| Crazy | 64 | 73 | **+9** | 10/10 / 10/10 |
| Fire | 105 | 105 | 0 | 10/10 / 10/10 |
| MyFirstBot | 74 | 90 | **+16** | 10/10 / 8/10 |
| MyFirstDroid | 110 | 110 | 0 | 10/10 / 10/10 |
| MyFirstLeader | 70 | 42 | **−28** | 10/10 / 9/10 |
| PaintingBot | 85 | 85 | 0 | 10/10 / 10/10 |
| RamFire | 98 | 99 | **+1** | 10/10 / 10/10 |
| SpinBot | 45 | 43 | **−2** | 4/10 / 0/10 |
| Target | 105 | 108 | **+3** | 10/10 / 10/10 |
| TrackFire | 105 | 92 | **−13** | 10/10 / 10/10 |
| VelociBot | 100 | 98 | **−2** | 9/10 / 9/10 |
| Walls | 63 | 59 | **−4** | 10/10 / 10/10 |
**ELM beats intercept on 4/13, ties 4/13, loses on 5/13. Median delta 0.0
dmg/rd; mean delta −1.5.** Pooled over all 13: intercept 11170 damage / 3728
shots / 30.0% hits; ELM 10970 / 3688 / 29.7% — the ELM is **1.8% worse in
aggregate**.
### Gate open-rate per battle
Gate open = `|correction| > GATE_TAU (0.10 rad)` at an actual shot (read from
the `-d:gunLog` stream).
| sample bot | shots | gate open | rate |
|---|---:|---:|---:|
| Corners | 284 | 173 | 60.9% |
| Crazy | 344 | 267 | 77.6% |
| Fire | 226 | 57 | 25.2% |
| MyFirstBot | 467 | 149 | 31.9% |
| **MyFirstDroid** | **116** | **0** | **0.0%** |
| MyFirstLeader | 484 | 321 | 66.3% |
| PaintingBot | 434 | 188 | 43.3% |
| RamFire | 121 | 44 | 36.4% |
| SpinBot | 592 | 343 | 57.9% |
| Target | 173 | 31 | 17.9% |
| TrackFire | 111 | 15 | 13.5% |
| VelociBot | 396 | 213 | 53.8% |
| Walls | 610 | 472 | 77.4% |
| **all** | **4358** | **2273** | **52.2%** |
The gate opened in 12 of 13 battles (52.2% overall, versus the 61.4% calibration
figure). **Against MyFirstDroid the gate never opened: that ELM arm is
bit-for-bit the intercept arm**, which is why its damage, hits and aim spread
are identical. Every other battle genuinely exercised the correction.
### Comparison with the in-training legacy result (memorization check)
| test | opponents | improved | median delta | verdict |
|---|---|---:|---:|---|
| legacy (in training corpus) | DrussGT, CassiusClay, Komarious, Phoenix | **4/4** | +5.75 dmg/rd (2.7x–14x) | large, consistent gain |
| sample bots (held out) | 13 Nim samples | **4/13** | **0 dmg/rd** | no gain |
On bots it was trained on, the ELM improved every opponent by a large factor; on
bots it has never seen, it is a coin flip that trends slightly negative. **The
legacy gains do not transfer. The most parsimonious reading is that a
substantial part of the legacy result was memorization of those four opponents'
motion, not a general movement-prediction skill.** This echoes the earlier
offline finding that the label law is ≈ `0.87 × lead` — an opponent-shape
idiosyncrasy captured by the corpus, not a universal correction.
### Trivial-bot sanity (stationary / near-stationary cases)
* **Target** (stationary until damaged): intercept 105 → ELM 108 dmg/rd. Not a
regression, but the gain is within the saturation ceiling.
* **Walls** (stationary): intercept 63 → ELM 59 dmg/rd, **−4**. This is the red
flag the gate design is supposed to prevent. Walls does not move, so the true
correction is ~0, yet the gate opens on **77.4%** of shots and the ELM *adds*
a correction: aim spread goes 9.93° → 10.45° sd. The correction is not
trustworthy on stationary targets, and `GATE_TAU` is too low to catch it.
### Bottom line
**No — on bots it has never trained on, the movement-prediction ELM does not
beat the plain geometric intercept.** It wins 4 of 13 sample bots, ties 4,
loses 5, with a median delta of exactly 0 and an aggregate damage 1.8% *below*
the baseline. The large in-training gains reported above are therefore not
evidence of general movement prediction. Two concrete defects are visible: the
gate admits corrections against stationary targets (Walls), and one entire
battle (MyFirstDroid) never opened the gate at all. A null-to-negative held-out
result this clean says the current ELM should not be shipped as an improvement;
the next step is to make the gate/correction honest on non-moving targets before
re-measuring held-out opponents. 10 rounds per bot means the ~±4 dmg/rd rows are
noisy — but no amount of extra rounds turns a median of 0 into a win.
## Online-learning gun
The previous section is the null result that motivates this one: the
**pretrained** cross-opponent model does not generalise (4/13 held-out wins,
aggregate 1.8% worse). This section is the paradigm change it points to —
**learn the opponent in front of you during the battle**, and reset only when
the opponent changes.
### Reset event: `GameStartedEventForBot`, never `RoundStartedEvent`
In Tank Royale a **battle is many rounds against the same opponent**, and that
opponent's movement code does not change between rounds. The bot API delivers
both events distinctly (`onGameStarted` / `onRoundStarted`,
`schemas.nim:202/212`), and the API starts `run()` on the first
`RoundStartedEvent` while firing `onGameStarted` once per battle before it. So
`DevControlBot.onGameStarted` calls `resetOnline()` and `onRoundStarted` does
**nothing**: the model, the pending queue and the gate persist across every
round of a battle and are wiped exactly once, at the start of a new opponent.
(The mean online sample count grows 36 → 642 across the round buckets below,
which is the runtime proof the reset is per-battle, not per-round.)
### Online learning with delayed labels
The label is the same validated one (`wrap(trueImpactBearing -
geometricInterceptBearing)`, `extract_predict.py`). At fire time the true impact
position does not exist yet — it is only knowable once the bullet's flight time
has elapsed. So at every shot the bot enqueues a `PendingShot(feat, base,
selfX, selfY, dueTick = fireTick + round(range / bulletSpeed))`. Each tick
`drainPending(nowTick)` resolves every shot with `dueTick <= nowTick`: it reads
the enemy's **actual** position from a rolling per-tick enemy trace (kept in
`elm_gun.noteEnemyAt`, the nearest trace sample within 3 ticks), computes
`label = wrap(bearing(selfFire -> truePos) - base)`, and feeds one sample to the
ELM (the engine's `decay=0.999`, `refitEvery=25`, the tuning the earlier online
work validated). The queue is keyed by `dueTick`; nothing is trained before the
bullet would have arrived, so there is no future leakage.
### Neutral vs weak prior
Both start from the **same frozen hidden layer** (the pretrained `W`/`hs`); they
differ only in the output layer at `GameStartedEventForBot`:
* **neutral** (`priorScale = 0`, the default): zero `beta`, learns purely online.
* **weak prior** (`-d:elmPrior`): the pooled pretrained `beta`, scaled by 0.1.
Over the 9 held-out sample bots they are **tied within noise**: neutral 88.3
dmg/rd, weak-prior 88.9 (base 70.1). The weak prior is a touch better on the
hard movers (MyFirstLeader 103.5 vs 95.5, MyFirstBot 83.0 vs 76.5) and a touch
worse on the near-stationary ones (VelociBot 83.5 vs 87.0, Walls 68.0 vs 74.0).
Neither is a clear winner; the default is **neutral**, because starting from a
prior that was shown not to generalise risks importing exactly the bias the gate
is meant to catch, and the neutral model reaches the same place within a round.
### Novelty gate: never worse than the intercept by construction
The correction is applied only if **all** of these hold, else the gun returns the
exact geometric aim:
1. `nOnline >= OnlineMinSamples (12)` — no signal at all until the model has seen
real samples for *this* opponent;
2. `modelErr < 0.95 * zeroErr` — the model's **held-out-style** error must beat
what always aiming at the intercept costs. `feedSample` scores the *current*
model against each new label **before** training on it (EMA α = 0.08), so
`modelErr` is a genuine online held-out error and `zeroErr` is the
zero-correction baseline;
3. `|correction| > GATE_TAU (0.10 rad)` — the existing magnitude filter.
`modelErr` only starts moving after the first closed-form refit (25 samples), so
the gate opens conservatively. Measured open-rate (shots where a nonzero
correction was applied), logged with `-d:gunLog`:
| arm | r1–2 | r3–4 | r5–10 | r11–15 | r16–20 |
|---|---:|---:|---:|---:|---:|
| Online open-rate | 36% | 60% | 69% | 68% | 72% |
| Online mean samples | 36 | 110 | 271 | 449 | 642 |
| Prior open-rate | 58% | 64% | 62% | 62% | 56% |
The gate **opens later in the battle** — that is the online learning becoming
genuine signal for the opponent in front of it.
### Damage per round — 20 rounds each, RawRecord ground truth, all CONTIGUOUS
36 recordings (12 opponents × 3 arms), each `query.py --verify` = CONTIGUOUS.
Arms: **Base** = `-d:baselineGun` (pure intercept), **Online** = default
(neutral, online), **Prior** = `-d:elmPrior`. `Δ` is Online − Base.
| opponent | kind | Base | Online | Prior | Δ Online |
|---|---|---:|---:|---:|---:|
| Corners | held-out | 94.0 | 96.5 | 96.0 | +2.5 |
| Crazy | held-out | 58.0 | 72.5 | 76.0 | **+14.5** |
| MyFirstBot | held-out | 49.0 | 76.5 | 83.0 | **+27.5** |
| MyFirstLeader | held-out | 25.0 | 95.5 | 103.5 | **+70.5** |
| SpinBot | held-out | 36.0 | 91.0 | 85.5 | **+55.0** |
| Target | held-out | 103.5 | 102.5 | 103.5 | −1.0 |
| TrackFire | held-out | 99.0 | 99.5 | 101.5 | +0.5 |
| VelociBot | held-out | 95.5 | 87.0 | 83.5 | −8.5 |
| Walls | held-out | 71.0 | 74.0 | 68.0 | +3.0 |
| Komarious | legacy | 21.0 | 33.0 | 27.0 | **+12.0** |
| Phoenix | legacy | 3.5 | 7.5 | 7.0 | +4.0 |
| DrussGT | legacy | 5.5 | 10.5 | 16.5 | +5.0 |
Pooled: held-out 9 bots **70.1 → 88.3 dmg/rd (+26%)**, hit rate 23.5% → 33.0%;
legacy 3 bots **10.0 → 17.0 (+70%)**, 4.6% → 6.6%. Online wins **7/9 held-out**,
loses 2 (Target −1.0, VelociBot −8.5 — both already near the saturation ceiling
at ~95–103 dmg/rd). Note this is a **single 20-round recording per pair**, so the
± few-dmg rows are noisy; the large rows are not.
### The round-index curve — does it improve WITHIN a battle?
Pooled damage/round by round index (clean, log-free builds):
| arm | r1–2 | r3–4 | r5–10 | r11–15 | r16–20 |
|---|---:|---:|---:|---:|---:|
| Base | 65.9 | 74.7 | 67.8 | 69.8 | 65.4 |
| Online | 71.7 | 84.8 | 82.3 | 75.5 | 75.3 |
| Δ Online | +5.8 | +10.0 | +14.6 | +5.7 | +9.9 |
| Δ Prior | +1.4 | +8.8 | +12.5 | +10.2 | +7.6 |
**Yes, the gain grows with rounds seen**, peaking at +14.6 dmg/rd in rounds 5–10
while the gate open-rate climbs 36% → 72% and the model accumulates 36 → 642
samples for the same opponent. The r11–20 rows are noisier (bots die faster once
the gun lands, shortening rounds), but the direction is exactly the online
paradigm working.
### Bottom line
**Yes — online learning beats the plain geometric intercept on opponents it has
never seen.** On 9 held-out Nim sample bots it is +26% aggregate damage/round
(88.3 vs 70.1), higher hit rate (33.0% vs 23.5%), and the advantage grows across
rounds of the same battle (+5.8 → +14.6 dmg/rd as the gate opens). This is the
opposite of the pretrained model's null/negative result above: the model that
does **not** generalise from a corpus does fine when it trains on the opponent
in front of it. Two honest caveats: (1) the two losing rows are opponents the
intercept already kills at ~100 dmg/rd, so there is little headroom and the
losses are within noise; (2) neutral and weak-prior starts are statistically
indistinguishable here, so the win is the **online adaptation**, not the prior.
Reproduce:
```sh
# build the three arms (Base / Online / Prior)
bash tools/elm_bench/run_online_battles.sh Corners Crazy ... Walls Komarious Phoenix DrussGT
python3 tools/elm_bench/analyse_online.py /tmp/gun_exp_clean
```