automationagents , 6 min read

My tank bot couldn't count its own kills

A Battle City bot reported 7 to 17 kills a stage. The real number was zero. Moving it to a headless copy of the game with a scoreboard took the clear rate from 4.3% to about 76%, and most of my clever ideas lost.

A week after the Flash tower defense bot, I wanted another one, and picked Battle City. It's the NES game where you drive a small yellow tank around a brick maze and protect an eagle at the bottom of the screen from twenty enemy tanks per stage. A fan site runs a Unity WebGL version in the browser, and on September 26 at 23:34 I started writing a bot for it.

The tower defense bot never looked at the screen. This one had to, because the game state was locked inside a Unity canvas. So the first version read pixels.

Reading a game through its pixels

Getting pixels out of the canvas was the first fight. The Unity build renders with preserveDrawingBuffer: false, which means any read after the frame is presented comes back black. The bot wraps requestAnimationFrame and reads the canvas inside it, right after Unity draws. It then shrinks the playfield to the game's native 208 by 208 grid and classifies cells by colour: bricks are orange, the backdrop is grey, the player is yellow.

Every assumption about colours was wrong once. Enemy tanks in this build are mid-grey, not white. The eagle is dark grey, so a brightness test misses it. Chrome throttles a window that's hidden behind other windows to about one frame a second, which quietly turned a 90 ms control loop into a 1 Hz one. Resizing the window rebuilt the canvas, and reads came back black again. On the title screen, pressing up one time too many wrapped the cursor onto a DONATE link, which navigated away and ended two long runs.

There was also a language model in the loop, an advisor that looked at the parsed state and picked targets. At first it picked individual moves. That path skipped the bot's own path finder entirely, so for a while the path finder never ran.

The number that measured something else

By September 27 the bot reported between 7 and 17 kills a stage. That number came from the HUD, the column of small tank icons on the right side of the screen, which shrinks as the stage goes on. I read it as enemies destroyed.

It's the count of enemies still waiting to be deployed. It shrinks when a tank spawns, whether or not anyone shoots it. The game-over screen said 0 PTS, and I had assumed that was a display glitch. It was accurate. The bot had killed nothing.

The honest replacement was the explosion sprite, a specific purple and red. With it, and with a rule keeping the tank close to the eagle, the bot managed about one kill a minute. Then that detector turned out to fire on the flashing spawn markers too. So the second kill counter was also counting spawns.

A bot that can't score itself can't be improved, because every change looks as good as every other. That was the end of the pixel version.

A copy of the game I can run 2,857 times faster

Someone has written an MIT-licensed clean-room JavaScript port of Battle City. It keeps the game as data: a 13 by 13 grid of tiles, bricks down to quarter tiles, entity slots, who fired which shell, kills per enemy type. On September 28 and 29 I moved the bot onto it, in Node, with no browser and no screen.

The sandbox drives the port's own update() tick with a seeded random number generator, at about 170,000 ticks a second. That's roughly 2,857 times real time. Spread over every CPU core, 420 stage runs take about 10 seconds. Each policy change got a label and a line in a JSONL scoreboard: runs, clear rate, kills, deaths, eagle losses, shots fired.

The first line, at 23:03 on September 28, was v1-baseline: 70 runs, 4.3% of stages cleared, 8,066 shots for 484 kills. The language model went in the same cleanup. A round trip to it was 30 to 120 times too slow for a game that wants a decision 60 times a second. By then its API key wasn't even set, so it couldn't have run anyway.

Most good ideas lost

The scoreboard has 64 lines, and a lot of them are ideas that looked smart and measured worse.

  • The tank moved in an ugly way, twitching and replanning constantly. I tried seven ways to smooth it. Each one cost 5 to 11 points of clear rate.
  • "Destination commitment," where the bot picks a goal and sticks to it, cut replans from thousands to 23 in 50 seconds. The clear rate fell from 14% to 6%.
  • The bot stood still 49% of the time, which looked like a bug. Camping near the eagle beat hunting enemies across the map, 14% to 4%.
  • Line-of-sight seats and an anti-flip rule lost too, and the README keeps a list of a dozen more ideas that made no measurable difference.

The scoreboard also caught the harness lying. One A/B test compared against a simulation of the old code instead of the old code itself. Another left the anti-flip experiment switched on while measuring the baseline, which dragged the baseline down to 3 or 4% and made the experiment look like a win. The rules that came out of it: seed the RNG before comparing anything, restore the real old code path as the control, and if both arms have identical frame counts, the harness is broken.

The scoreboard itself got committed to the repo on September 29 at 11:10. Until then it lived in /tmp, which was one cleanup away from deleting the evidence for 16 experiments.

Dodging shells that haven't been fired yet

Deaths were the next problem, and the diagnostic script that films each lost stage found two causes.

The old dodge rule stepped "the short way, if free." Pinned against a wall, the bot flipped between the wall side and the shell's lane every frame and stood in the lane. 34 of 58 deaths were shells the bot had seen more than three frames earlier. The replacement is a forward model. A shell flies straight at a known speed and stops at the first wall, so its future is known. Every frame, the bot simulates its own next 120 frames for each move it could make, using the game's real movement rules, and keeps its intended move only if that move survives.

After that, 25 of the 33 remaining deaths were shells fired one to three frames before the hit, from a tank 14 to 30 pixels away. No dodge can beat that. But an enemy fires on one frame in 32 whenever its gun is free, in whatever direction it faces. So a close tank facing the bot is a shell that hasn't been fired yet:

const GHOST = parseInt(process.env.BC_PHANTOM ?? '40', 10);
const ghosts = [];
if (GHOST > 0 && !(s.freezeTimer > 0)) {
  for (const e of s.entities) {
    if (e._slot < 2 || !e.alive || e.spawnAnim > 0 || s.bullets.some((b) => b.owner === e._slot)) continue;
    if (Math.abs(e.x - me.x) + Math.abs(e.y - me.y) > GHOST) continue;
    const tr = fly({ x: e.x + DX[e.dir] * 8, y: e.y + DY[e.dir] * 8, dir: e.dir, powered: e.type === 2 });
    if (tr.length) ghosts.push({ tr });
  }
}

Over 35 stages and 16 seeds, phantom shells took deaths from 200 to 142 and the clear rate from 73.6% to 75.9%. On held-out seeds never used for tuning, with a longer phantom range, deaths went from 316 to 198.

By September 30 the default game cleared about 76% of stages. Much of the jump from about 16% came from bugs, which reading the port's source and the benchmark runs turned up. A node choice that steered the tank back to waypoints it had already passed. A shot check that probed only the centre of the shell while the game also probes one pixel to the side, so a steel corner stopped shells the bot thought were clear. A frozen-enemies power-up during which the tank buzzed up and down in place. That bug had three causes, the shot probe among them, and fixing all three was worth 2.7 points.

There are game mods now too: chaos events, waves of enemies, bricks that grow back, a 39 by 39 field with 300 enemies. The bot clears that one with the shovel power-up on. None of that was possible while the bot measured spawns and reported them as kills.

More writing

All posts