← Back
engineering /

Teaching game characters to fight with reinforcement learning in Arstid

I let a swordsman learn to fight by trial and error, from flailing around in the grass to parrying a boss 34 times in one fight. Then I trained a mage, a two-person party and finally the boss itself.

A small party fighting a group of pink monsters in Arstid's pixel-art field, with damage numbers floating above them.

For a while now I’ve been building Arstid, a small browser RPG with a pixel-art field, a handful of monsters and a few classes. Until recently every enemy and helper in it ran on rules I wrote by hand. If the target is close, swing. If health is low, drink a potion. That works, but it gets brittle fast, and every character ends up fighting the same way.

So I spent a weekend trying something different. I gave a character the controls and a score, told it nothing else, and let it play a few million fights in a simulator to figure things out on its own. This is the same swordsman in the same kind of fight, at the start of training and at the end.

Before · the very start of training. It wanders, swings at nothing and dies in 17 s.
After · 3M decisions (10 minutes of training). It clears the pack in 7.6 s without a scratch.

I never told it to pull the monsters into a line or to parry the wasps. It started doing both because they scored better.

By the end of the weekend I had run 28 training runs, counting the small test ones. This post goes through all of it in order. First a solo swordsman, then the boss, then a mage that took five tries, then a swordsman and mage learning to fight as a team, and finally the boss learning to fight back. The last section covers the setup in more detail for anyone who wants it.

How it learns

The method is called reinforcement learning, which is a formal name for trial and error. The character (I’ll call it the agent from here on) looks at the game, picks an action and gets a small reward or penalty for it. At first its choices are basically random. After every batch of fights, whatever led to a better score becomes a bit more likely next time. Do that a few million times and the flailing slowly turns into something that looks like a plan.

For the learning algorithm I used PPO (Proximal Policy Optimization), which is the usual go-to for this kind of problem. My implementation follows the single-file style of CleanRL, with GAE to judge how much better or worse each action turned out than expected, and invalid action masking so the agent never wastes time on moves the game won’t allow. The brain itself is tiny, just two layers of 256 neurons.

The one idea worth knowing about PPO is how careful it is. After each batch it compares how likely an action is under the new version of the agent and under the old one. That ratio is called ho ho (rho).

ρ=πnew(a∣s)πold(a∣s),ρ is kept between 0.8 and 1.2\rho = \frac{\pi_{\text{new}}(a \mid s)}{\pi_{\text{old}}(a \mid s)}, \qquad \rho \text{ is kept between } 0.8 \text{ and } 1.2

Here π(a∣s)\pi(a \mid s) is the chance of picking action aa in situation ss. In plain words, a single update can make any action at most about 20% more or less likely. That stops one lucky or unlucky batch from throwing away everything it has learned so far.

Keeping it fair

An agent that reacts in zero milliseconds and reads hidden numbers wouldn’t tell me anything useful about my game. So I built human limits into the environment itself.

  • It makes 5 decisions per second, and each one lands 100 ms after it was made, roughly like a human reaction.
  • It only sees what a player would see. Positions, health bars and the warning markings on the ground are visible. Hidden attack timers and the random number generator are not.
  • Spells are typed. In Arstid a mage casts by typing out a chant, so a scripted typist handles that at a fixed speed. Typing is a motor skill, so I kept it out of what the agent has to learn.
  • The simulator runs the same combat code as the game server. Anything the agent learns carries straight over to the real client, which is also why every video on this page is recorded in the actual game.

What it gets rewarded for

The reward has to describe what I actually want, otherwise the agent will find a loophole. It found a few anyway. Roughly, it works like this.

  • Damaging enemies earns points, and losing your own health costs points. This uses potential-based reward shaping, so letting a monster heal back costs exactly what hitting it earned.
  • Winning is +1, with a bonus for winning quickly. Dying or running out the clock is −1.
  • Every second costs a little, so stalling never pays.
  • Potions cost money, and the health they give back gets subtracted again. Drinking only pays off if it actually keeps you alive.

Written out, the step-by-step part is simple. First I give the current situation a score, written Φ(s)\Phi(s) (phi of ss). It uses HP, the health points of each side, as a share of their maximum so everything sits between 0 and 1.

Φ(s)=0.3×my HP−enemy HP left\Phi(s) = 0.3 \times \text{my HP} - \text{enemy HP left}

The reward for one step is then how much that score improved, minus the small time cost and anything spent on potions.

rt=γ Φ(st+1)−Φ(st)−0.002−potion costr_t = \gamma\,\Phi(s_{t+1}) - \Phi(s_t) - 0.002 - \text{potion cost}

Here sts_t is the situation at decision tt and st+1s_{t+1} is the one right after it. γ\gamma (gamma) is a number just below 1 that makes rewards further in the future count a little less. It matters a lot later, in the mage section.

So hitting an enemy pushes the score up, getting hit pushes it down at 30% of the weight, and standing around slowly costs points. On top of that the last step of a fight adds the outcome. A win is worth 1+0.5×time left+0.3×HP left1 + 0.5 \times \text{time left} + 0.3 \times \text{HP left}, and dying or running out of time is −1-1.

Keep that last one in mind, because it causes trouble twice.

Round 1, a pack of wasps

The first test was a level 10 swordsman against a group of 4 to 8 Quillwasps and Sketchgrubs. To have something to compare against, I ran my existing scripted bots on the same fights at three skill settings, casual, average and expert.

Win rate climbs from 0% to 100% within the first 300k decisions, matching the scripted expert's 99%. Time to clear the pack falls from about 30 s to 10.3 s, below the scripted expert's 13.1 s. Health left after a fight rises to 95%, above the scripted expert's 76%.
The horizontal axis is decisions made during training, and the dashed line is my best hand-scripted bot on the same fights. Curves are smoothed over recent fights.

Learning to win took about 300,000 decisions, which is only a couple of minutes of training. What surprised me more was what happened after that. Even once it stopped losing, it kept getting faster and kept finishing with more health, since the score still rewarded both.

Swordsman vs. wasps (100 to 300 fights each) Win rate Time to clear Health left Parries
Scripted bot, casual 84% 16.8 s 40% 1.4
Scripted bot, average 96% 17.8 s 54% 5.3
Scripted bot, expert 99% 13.1 s 76% 6.7
Learned agent 100% 10.0 s 94% 4.6

These numbers come from separate test fights it had never seen during training, with the agent always picking its most likely action, so they aren’t just the training curve looking good.

Round 2, the boss

Next up was the Great Puddling, a water boss with 12,000 HP and five area attacks. Each attack is announced by markings on the ground a moment before it hits. If you throw a level 15 swordsman straight at it, it loses every single time, and an agent that always loses has nothing to learn from.

So I used a curriculum, which works a lot like school. It starts with the wasps, then a boss with 15% of its health, then 25%, 40%, 70% and finally the full version. Once it wins 70% of its recent fights, it moves up a level, and a fifth of its fights still come from the earlier levels so it doesn’t forget them.

Before · early training, against a boss with only 15% of its health. It stands in the attacks and dies at 36 s. (2× speed)
After · 40M decisions, against the full-strength boss. It steps out of the markings, parries 36 times and wins with 68% health left. (2× speed)

The final win rate is nice, but the training curves are the more interesting part.

Win rate against the full-strength boss is briefly high, collapses to near zero between about 1.5M and 5M decisions, then recovers to 98%. The scripted expert wins 15%. Potions per fight start at about 50, drop to almost zero during the collapse, then settle at 13. Parries per fight climb from about 10 to 37, then settle around 34.
Fights against the full-strength boss only, over all 40M training decisions. The scripted expert is a level 15 swordsman bot, same as the agent.

It actually got worse before it got better. Early on, the agent was beating the boss by drinking around 50 potions per fight. Potions cost points, though, and at some point it figured that out and overcorrected by almost completely stopping. For about four million decisions after that it lost nearly every fight. Eventually it settled somewhere in the middle, drinking fewer potions and leaning on a skill that could replace them.

That skill was parrying. In Arstid, if your sword strike lands just before an enemy’s blow, the hit is cancelled and your skill comes back off cooldown. It’s easily the hardest thing to pull off in the game. The agent went from around 10 parries per fight to 34, and its potion use dropped to 13. For comparison, my expert scripted bot at the same level beat this boss only 15% of the time and went through 41 potions doing it. The trained agent won 98% of its fights.

Round 3, a mage that took five tries

I expected the mage to be the same recipe with a different character. It wasn’t. The swordsman’s setup got it about halfway up the curriculum, and then it stalled.

Attempt What I changed How far it got
1 Same setup as the swordsman Reached the boss with 40% HP, then its win rate fell to zero and it nearly stopped attacking
2 and 3 Made it care more about the future (gamma from 0.997 to 0.999) Still stuck at the 40% boss, best win rate around 50%
4 Charged potions only their shop price, not the health they restore Got all the way to the full boss, but couldn’t beat it
5 Raised the typing speed from 60 to 90 words per minute and continued from attempt 4 98.5% wins against the full boss
Mage win rate in the fifth attempt climbs from 0% to about 75% in the first million decisions, then slowly to 98.5% by 9M. Mage health left after a fight rises from 0% to 86% over the same run.
The fifth attempt, all of it against the full-strength boss. Once the typing was fast enough it kept improving for the whole run.

The gamma (γ\gamma) change is about how far ahead the agent plans. A reward that arrives kk decisions from now is worth γk\gamma^k of a reward right now, so rewards far in the future fade away. A handy rule of thumb for how far ahead it effectively looks is

horizon≈11−γ decisions\text{horizon} \approx \frac{1}{1-\gamma} \text{ decisions}

At 5 decisions per second, that works out like this.

Discount (gamma) Horizon In seconds
0.997 about 333 decisions about 67 s
0.999 about 1,000 decisions about 200 s

About a minute is fine for a swordsman who wins in 90 seconds. A mage fight runs longer, so it needed the longer horizon to connect what it does now with winning later.

The potion fix was the big one. A mage fight against this boss is long enough that you simply have to drink to survive. Under the original rule, every potion cost the agent the health it restored plus its price. Say a fight needs nn potions that each cost cc, and write RextwinR_{ ext{win}} and RextdieR_{ ext{die}} for the reward at the end of a won fight and a lost one. Drinking through the fight only makes sense when

n×c < Rwin−Rdien \times c \ <\ R_{\text{win}} - R_{\text{die}}

A win is worth at least +1+1 and dying is −1-1, so that gap is about 2. A long mage fight needed enough potions that n×cn \times c went past it, and from the agent’s point of view dying became the cheaper option. A comment I left in the reward code still says it plainly, a long fight a class must drink through otherwise “pays less than dying dry.”

The typing speed was the last piece. My guess is that at 60 words per minute the chants were simply too slow to fit between the boss’s attacks. 90 is fast, but it’s a speed real people type at. Once the mage could cast in time, it learned to stay at range and fit its spells into the gaps, without ever parrying. Same setup, very different style.

Round 4, fighting as a team

Next I put the swordsman and the mage in the same fight. Each one keeps its own network, but they share one reward, so the only way to score is to win together. Both started from their solo versions. Their networks were widened with extra inputs for seeing each other, with those new inputs starting at zero, so on the first fight they played exactly like they did alone.

Party · the latest swordsman and mage against the boss. They win in 73 s and the swordsman finishes at full health. (2× speed)

They won from the very first fight, so the win rate tells you nothing here. What changed was how they won. Over 6M decisions of training together, their average clear time went from 99 s to 76 s, and the potions they used between them dropped from 55 per fight to 31.

The party clear time falls from about 99 s to 76 s over 6M decisions, most of it in the first 3M. Potions used by both players together fall from about 55 per fight to 31.
The first party round, 6M decisions. Every fight was already a win, so these two are where the learning shows.

The odd part is the swordsman. Solo, it parried 34 times a fight. In the party it parries maybe once or twice. I haven’t dug into exactly why yet, but with a mage dealing damage from the back, the fights are shorter and the boss isn’t always swinging at the swordsman, so there’s simply less to parry.

Round 5, training the boss

At this point my own agents could beat the boss nearly every time, so the boss clearly needed work. I flipped things around and made the boss the one learning.

The boss doesn’t get any new abilities. Every attack keeps the same warning markings, timing and wind-up. The only thing it learns is which attack to use and when, and it’s also allowed to hold for a moment instead of attacking. Its reward is pretty simple. Hurt the players, knock someone out and stay alive.

To stop both sides from just exploiting the other’s latest habits, I set up a small league, loosely based on how AlphaStar was trained. The party trains against every past version of the boss. Then the boss trains against every past version of the party plus the solo agents and the scripted bots, and then everyone plays everyone. Two of the rounds trained only the boss while the party stayed frozen. Over about a day and a night the league produced five versions of the boss.

While a boss version trains, the players’ win rate barely moves, because each fight is against a random mix of opponents. Its reward climbing and the fights getting longer show the learning better.

The reward of boss version 4 climbs from about 10.5 to 11.6 per fight over 1.2M boss decisions. Fights that the players win get longer, from about 88 s to 102 s, while boss version 4 trains.
Boss version 4, the one that ships, over its 1.2M decisions of training.

Then I put the same RL party against every boss version.

The RL party's average clear time against each boss version rises from 74 s against the hand-written boss to 84 s against version 4. The RL party's potions per fight rise from 31 against the hand-written boss to 44 against version 4.
The same RL party against every boss version, 24 fights each. It still won all of them, but each new boss made it work harder.

Against my trained party, every boss version still lost. The party just needed longer and more potions each time. The real test is how the boss does against players who can’t adapt to it, so I ran the version that now ships in the game against everyone, 30 fights per opponent.

Player win rate against the hand-written boss versus the learned boss. The RL party stays at 100%. The RL swordsman drops from 60% to 30%, the RL mage from 60% to 17%, the scripted expert party from 70% to 17% and the scripted average party from 10% to 0%.
30 fights per opponent, on the current game rules. The solo agents were trained before I tightened the parry window and potion cooldown, which is why they no longer win 98%.

What makes the learned boss harder isn’t extra damage. It’s that it picks its attacks based on what the player is doing.

Situation Hand-written boss Learned boss
player at mid range Ring, Crash and Rain about evenly Crash 35%, Rain 25%, and it holds back 25% of the time. It almost never uses Ring
player in the middle of a spell Crash 30% Crash 41% and Rain 32%, which punish a mage standing still to chant
boss below half health (its second stage) mostly Burst (35%) mostly Deluge (37%) and Crash (34%), Burst drops to 6%
player standing behind it mostly Burst (47%) about the same (43%)

The holding is my favourite part. About one decision in ten, it waits a beat for the player to commit to a dodge before it attacks. I never programmed that. This version of the boss now ships in the game as roughly 88,000 numbers stored as 16-bit values and run directly in the browser.

Under the hood

This part is for anyone who wants the details. Everything runs on one desktop with an Intel i5-10400F and a GTX 1070. Most of the work is the game simulator running on the CPU. The networks are so small that the graphics card has very little to do.

Training pipeline. The game's own combat rules run inside a Node simulator with human limits. The simulator exchanges observations, rewards and actions with a Python PPO trainer. The trainer produces replays, which play back in the real game client, and policy files, and the best boss gets packed and shipped to run in the browser.

The simulator is written in JavaScript and imports the same combat code the game server uses. A Python trainer runs PPO in PyTorch and talks to 11 simulator processes, each running 16 fights at once. That comes out to about 7,000 decisions per second, so 40M decisions takes around an hour and a half.

What the agent sees and does

Solo or party agent Boss
Inputs 766 numbers (291 in the wasp version). Its own health, SP (the energy skills cost), cooldowns, casting progress and potions, the nearest 5 enemies, up to 2 allies, its 8 skill slots, and in boss fights the boss’s state, the next 4 warning markings with their shapes, which way the boss faces and its recent moves 71 numbers about the players around it and its own state
Actions 58. Do nothing, move in 8 directions, stop, drink a health or SP potion, sit, attack one of 5 targets, or cast one of 8 skills at one of 5 targets. Anything the game wouldn’t allow right now is masked out 13. Each of its 6 attacks aimed either at the player it’s focused on or at the other party member, or hold
Decisions 5 per second, landing 100 ms late whenever it’s free to start a new attack

Training settings

These are standard PPO settings, and the PPO and GAE papers linked above explain each one. The only one worth spelling out here is the network. The actor picks the actions, and the critic guesses how well the fight is going so the actor knows which choices helped.

Setting Value
Network two hidden layers of 256, separate actor (picks actions) and critic (judges the situation)
Learning rate 3e-4 with linear decay
Discount γ 0.997 for the swordsman, 0.999 for the mage, 0.99 for the boss
GAE λ 0.95
PPO clip 0.2
Entropy bonus 0.01
Batch 176 fights × 128 steps, 4 epochs of 8 minibatches
Early stop when the KL divergence of an update passes 0.03

Takeaways

The reward is basically the design. Every surprising thing the agents did, good or bad, traced straight back to what I was rewarding. The swordsman giving up on potions and the mage choosing to die rather than drink weren’t learning bugs. I had simply asked for the wrong thing.

The human limits are what make the numbers mean something. Because the agent reacts at roughly human speed, what it can pull off is something a skilled player could pull off too. That makes its results a fair check on whether a fight is too easy or too hard.

A learned boss turned out to be more useful as a design tool than as a smarter enemy. In about a day the league found attack patterns I wouldn’t have come up with, like holding back to bait a dodge. Now I can keep the ones that are fair and fun and tone down the ones that aren’t.

And it didn’t need much hardware. Almost all of the work was the simulator running on a mid-range CPU, and the networks are small enough that the graphics card barely mattered.

Run Decisions Wall time Result
Swordsman vs. wasps 3M 10 min 100% wins, 10.0 s clears
Swordsman vs. boss (curriculum) 40M 95 min 98% wins, 34 parries a fight
Mage vs. boss (fifth attempt, continued from the fourth) 9M 23 min 98.5% wins
Party of two 6M per league round about 20 min per round clears in 76 s instead of 99 s, potions 31 instead of 55
Boss league (5 boss versions) 0.6M to 1.2M boss decisions each about a day scripted expert party drops from 70% to 17% wins

Keep reading

All posts ↗
ESC
↑↓ navigate ↵ open