Virostatiq

Visualization, language and culture

Orbit Duel: a neural network learns to dogfight around a star

Runs in the browser on desktop and needs a keyboard: A/D or arrows to turn, W to thrust, Space to fire.

I remember this game from around 30 years ago. It was a two-player web game written in Flash. I don’t remember whether you could play it against the computer, but I had great fun playing it against my brother. It was hard enough as it was – the orbital mechanics are hard to a human to take into account during the gameplay, so entertainment, at least for the technologically inclined, is guaranteed.

I decided to recreate it with modern technology, to play against the computer. To make the AI opponent capable, I decided to experiment with RL. I read many good things about PufferLib by Joseph Suarez, so I instructed my coding agent to do a few experiments using that framework.

The result … to say it rekindled my interest in reinforcement learning would be an understatement. The framework is so fast and efficient, and the models it trained so capable it blew me away. I’m going to use it for a variety of tasks from now on. Highly recommend.

An obvious side note is that the trained AI is way too hard for a human to play against. On Ace, it’s even hard to survive for more than five seconds. Give it a try, it’s terrifying.

The game

Two ships orbit a star. Each can turn, fire its engine and shoot. The star’s gravity pulls on the ships and on every bullet, so shots curve, and a shot that misses can swing around the star and come back at the ship that fired it. Touch the star and you burn up; cross the outer ring and you are lost. Each player has three lives, and the first to lose all three loses the match.

Your opponent is a neural network. Nobody told it how orbits work, how to lead a target or that firing straight at the star is a bad idea. It learned all of that by playing against itself, about three billion steps in all.

The Orbit Duel title screen: a menu with controls, rules and three opponent levels on the left, and two ships, one cyan and one pink, circling a glowing star inside a ring on the right, with curved bullets between them.
The title screen runs the strongest model against itself.

PufferLib

I trained the agent with PufferLib 5.0, an open-source reinforcement learning library by Puffer AI. Version 5.0 is less a Python library than a trainer written in C and CUDA. An environment is a single C header with a handful of functions (reset, step, observations, rewards, an optional renderer) and an .ini file with the training settings. The build script compiles the environment into the trainer, so the simulation runs as native code next to the GPU and nothing passes through Python during training.

That makes it very fast. With 4,096 agents playing at once, my RTX 3090 trains at roughly five million steps per second. The first usable model, 500 million steps, took about a minute and a half, and the strongest one, three billion steps, about ten minutes. At that speed you can change a reward or an observation, retrain and look at the result within minutes.

PufferLib also ships the pieces a two-player game needs: self-play with a pool of past opponents, evaluation against scripted bots, head-to-head matches between saved models, and a small CPU inference engine for the trained network. That last part made the browser version possible, as I describe below.

The environment

The whole game is about 600 lines of C. The arena has radius 1, the star sits in the middle, and one step of the environment is 1/30 of a second, integrated in four smaller physics substeps so that fast bullets near the star stay accurate. Both ships start each round on the same circular orbit, on opposite sides of the star. Left alone, they would circle forever.

Actions. Each step the agent picks three things at once: turn left, right or not at all; engine on or off; fire or don’t. A ship can have at most four bullets in flight, and there is a short cooldown between shots.

Observations. The agent sees 62 numbers: its own position, velocity and heading, the same for the opponent, the relative position and velocity between them, all eight bullets, both players’ remaining lives and the elapsed time. One design decision matters more than it looks: they are ego-centric. Before the numbers go to the network, the world is rotated so that the observing ship always sits on the positive x axis. The game looks the same from any angle around the star, and with this rotation the network doesn’t have to learn the same manoeuvre separately for every direction. Bullets are listed enemy bullets first, then own bullets, each group sorted by distance, so the most dangerous ones are always in the same slots.

Rewards. The reward is as simple as it gets. When a ship dies, the survivor gets +1 and the dead ship −1, whatever the cause: hit by the opponent, hit by its own bullet, burned in the star or drifted out of the arena. There is no reward for aiming, for surviving, for hitting or for using little fuel. Self-play didn’t need that shaping. Everything the agent does, from holding a stable orbit to leading a moving target, follows from not dying and making the other one die.

A match lasts until one side loses all three lives, or 60 seconds.

Scripted bots first

Before training anything I wrote three scripted opponents: one that does nothing, one that spins in place and fires constantly, and one that aims with lead (it predicts where the target will be when the bullet arrives), checks whether the star is in the way, and burns its engine to raise or lower its orbit when it gets too close to the star, too far out, or too far from the opponent.

Bot matches serve two purposes. They test the environment: if a bot that should win never wins, the bug is in the physics or in the rules, not in the learning. And they give a fixed yardstick. In self-play, the opponent improves at the same rate as the learner, so the win rate against it stays around 50% and tells you nothing. A bot ladder doesn’t move.

The agent climbed the ladder quickly. After 131 million steps, about 25 seconds of training, it already beat the aiming bot 87% of the time. After 393 million steps it beat all three bots more than 99% of the time, and the ladder had nothing more to say. From there on, the only useful comparison was model against model.

Self-play

Self-play is the obvious way to train a duel: the agent plays against a copy of itself, and as it gets better, so does its opponent. The known failure is going in circles. The agent finds a strategy that beats its current self, forgets how to handle an older strategy, and the older strategy beats it again.

PufferLib’s answer is a pool of past opponents. In 20% of the games, the opposing ship is controlled by a frozen checkpoint drawn from a pool of up to 64 earlier versions of the agent; in the rest, the agent plays itself. Old strategies stay in the mix, so forgetting how to beat them is punished.

The network is small: three layers of 256 units, about 608,000 parameters, 2.4 MB of weights. The training algorithm is PufferLib’s variant of PPO. The settings I chose in the config are a learning rate of 0.003 that decays to zero over the run, a discount factor of 0.99, GAE λ of 0.9, 64-step rollouts, minibatches of 16,384 steps and a small entropy bonus, 0.003, that keeps the agent from settling on one way of playing too early.

What three billion steps buy

I trained two models. Pilot is the 500-million-step model; Ace trained for three billion steps. In 4,096 matches, Ace beat Pilot 99.4% of the time. To see how it got there, I played each of the 24 checkpoints saved during Ace’s training against both finished models, 4,096 matches each.

Two line charts over three billion training steps. Top: the win rate against Pilot rises from 0% to about 80% by 0.8 billion steps and close to 100% by 1.8 billion; the win rate against Ace stays near 0% until 1.3 billion steps, then climbs to about 50% at the end. Bottom: matches against Pilot last about 7 to 16 seconds throughout, while matches against Ace stay between 6 and 14 seconds until 2.4 billion steps and then jump to about 38 seconds.
Each point is one checkpoint from Ace’s training run, playing 4,096 matches against Pilot and against Ace.

Against Pilot, the curve is what you would expect. The run passes Pilot’s level at around 700 million steps (Pilot trained for 500 million, but in a different run with a different seed) and wins nearly every match from 1.8 billion steps on. Against Ace itself, the last checkpoint scores 52%, as it should against itself.

The bottom chart is the interesting one. For most of training, a match lasts between 6 and 16 seconds, whoever the opponent. In the last 600 million steps, two things happen at once: matches against Pilot get shorter, about seven seconds for three kills, and matches against Ace get much longer, almost 38 seconds out of the possible 60. In the late checkpoints’ matches, each ship fires about 90 shots against Ace and about 20 against Pilot.

My reading is that in this stage the agent learned to dodge. Against a weaker opponent, that doesn’t show: Pilot’s shots rarely threaten it, so it simply wins faster. Against an opponent just as good at dodging, neither side can land a hit easily, and the match turns into a long exchange of shots. You can watch it on the title screen, where Ace plays itself.

None of this was rewarded directly. The reward is still only +1 and −1 per death.

From the trainer to the browser

Because the environment is plain C, I didn’t have to rewrite the game for the web. I compiled the same orbit_duel.h used in training, together with PufferLib’s CPU inference code, to WebAssembly with Emscripten. The browser loads the network weights and runs the network on every step, about 30 times per second. The JavaScript side only reads the keyboard and draws the frame. What you play against in the browser is the environment the agent trained in, compiled from the same source.

A trained policy is only reliable in situations that resemble its training, so every change for the web had to keep the agent’s inputs looking familiar:

  • Speed. At full speed the game was too fast for people. Instead of changing the physics per step, which the agent would notice, the browser simply plays the steps back at 80% of real time. To the agent, nothing has changed.
  • Time. In training, a match ends after 60 seconds, and the agent sees the elapsed time as one of its inputs. In the browser, matches end only when someone loses all their lives. Letting the clock run past 60 seconds would show the agent values it had never seen, so the clock it observes stops at 50 seconds and stays there.
  • Difficulty. There are three opponents. Pilot is the 500-million-step model and Ace the three-billion-step one. Cadet is Pilot with slowed reactions: 45% of the time it repeats its previous action instead of choosing a new one. It still flies well, but it reacts late.
  • Smooth motion. The game steps 30 times per second, but screens refresh at 60 Hz or more. The renderer interpolates ships and bullets between steps along curves that match their positions and velocities, so the motion looks smooth without changing the simulation.

Your score is the longest time you stay alive in a single life against each opponent, and the best times go on a leaderboard.

What I learned

  • Speed changes how you work. When a full training run takes a minute or ten, you test ideas instead of debating them. PufferLib‘s C environments are more work to write than a Python environment, but for a small game like this one it paid off many times over.
  • Keep the reward simple and the observations good. The win/loss reward was enough. The design effort went into what the agent sees: the rotated frame and the ordering of bullets by threat.
  • Build a bot ladder before training. It tests the environment and gives a measure that self-play alone can’t. Once the agent beats every bot, switch to matches between saved models.
  • Self-play results are relative. The match length told me more about what changed late in training than the win rate did. The same skill can be invisible against one opponent and decisive against another.
  • Deploy the exact environment. Running the training code itself in the browser meant there was no second implementation of the physics that could drift from the first.