I set out to train an AI that could fight a human in a game I built. It worked well enough: there is a trained model I can launch and play against today. It could have been better, and the gap between “it works” and “it works well” is where I learned the most.
M.A.R.L.S is a 2D fighting game built in pygame, where both fighters are trained with multi-agent reinforcement learning (PPO, via Stable-Baselines3). I expected the hard part to be the neural network. Instead, most of the work came down to rewards, metrics and settings.
This post covers what worked, what could have gone better, and what I’d do differently next time: a five-lesson curriculum, the problems it ran into, and the single self-play run that replaced it.

The setup
Two fighters share one stage. Each has 100 HP, a hit does 10 damage within 60 px, attacks have a 0.5 s cooldown, and blocking cuts damage by 67%. The game runs on pygame-ce, and a small Tkinter launcher lets me pick any trained model and play Human vs AI or watch AI vs AI.

For training, Gymnasium environments run the game headless. Physics runs at 120 FPS, but agents only decide every sixth frame: 20 decisions a second, so a 60-second match is 1,200 decisions.
Each decision, both fighters pick one of seven actions: idle, left, right, jump, crouch, attack or block. Each sees 19 numbers, clipped to [-1, 1]: its own position, velocity, facing, jump/crouch/block state and attack cooldown, the same details about its opponent relative to itself, the distance between them, and an agent ID. Both fighters together make a 38-number observation.
Plan A: a five-lesson curriculum
Rather than throw seven actions at a blank network, I split training into five phases, 2.8M steps in total. Each phase unlocked new skills and started from the previous phase’s weights.
| Phase | Goal | Steps | Episode | Reward highlights |
|---|---|---|---|---|
| 1. Movement and spacing | Close the distance | 500K | 30 s | +5 for closing distance, +2 at 60–80 px |
| 2. Attack timing | Attack when in range | 300K | 15 s | +1,000 per hit, ±2,000 win/loss |
| 3. Limited self-play | Space, attack, evade | 500K | 30 s | ±10 per hit, ±100 win/loss |
| 4. Defence | Block and crouch | 500K | 45 s | +5 per block, +5 per crouch dodge |
| 5. Full competitive | Final self-play | 1M | 60 s | ±100 win/loss dominates |
From Phase 3 on, opponents came from a pool: 50% the agent’s current self, 40% past checkpoints and 10% a random policy, so it couldn’t overfit to one style.

Look at the reward column again. Phase 2 pays 100 times more per hit than Phase 3. I didn’t notice that at first either.
What could have gone better
The curriculum gave me fighters that moved toward each other, a working transfer-learning pipeline, and models I could actually play. It also ran into five problems, and each one taught me something I now check on every RL project.
1. Agents that vibrate instead of fight
After Phase 1, my agents flipped left, right, left, right, in place. The first cause was a convenience feature: every step, the environment turned each fighter to face its opponent.
# --- Auto-face opponent ---
self.player1.update_facing(self.player2)
self.player2.update_facing(self.player1)
It quietly overrode the agent’s own choices, so the policy never learned a stable link between pressing a direction and where it was facing. I deleted it. Now move_left() and move_right() set facing, and the agent has to learn it.
Phase 2 brought the stutter back for a different reason: my penalties fought each other. Turning cost reward, facing away cost reward, and standing in range without attacking cost reward. An agent beside its opponent but facing the wrong way had no free move, so it oscillated between the least-bad options.
The fix was to make penalties depend on context:
- Turning is only penalised within twice the attack range. Far away, the agent can reposition freely.
- Not attacking is only penalised when already facing the opponent.
- A new +0.5 reward for standing still, facing the opponent, in range. It spells out the sequence I wanted: approach, stop, face, attack.
- Attacking while facing away costs 1.5 times the out-of-range penalty.
2. Phases that couldn’t share what they learned
The point of a curriculum is that each lesson builds on the last. Mine couldn’t. Loading a Phase 1 model into Phase 2 crashed:
ValueError: Action spaces do not match: MultiDiscrete([3 3]) != MultiDiscrete([4 4])
The phases enabled 3, 4, 5, 7 and 7 actions, and the policy’s output layer has one output per action. Every phase had a differently shaped network, so none could reuse the previous phase’s weights.
The fix was to stop changing the network and change the rules instead. Every phase now uses MultiDiscrete([7, 7]). If an agent picks an action its phase hasn’t unlocked, the environment turns it into idle and applies a -5 penalty:
action_p1_valid = action_p1 if action_p1 in self.enabled_actions else 0
p1_invalid_action = action_p1 not in self.enabled_actions
That is a soft mask: the agent still has to learn not to pick locked actions. A hard mask, like MaskablePPO in sb3-contrib, removes them from the choice entirely. The soft version was enough to make PPO.load() work between phases.
3. Rewards on the wrong scale
Phase 2 paid +1,000 per hit and ±2,000 for a win or loss. The logged mean episode reward climbed to 230,000–260,000, and the run finished averaging 607,393 per episode.
Big numbers look like progress, but they hurt learning. PPO’s critic has to predict returns in the hundreds of thousands, and small shaping terms, like +0.5 for standing well, vanish next to a single hit.
Phase 1 showed what that does to the critic. It ended with a value loss of 318,000 and an explained variance of 0. Explained variance measures how much of the actual returns the critic’s predictions account for; 0 means none. The critic learned nothing, so the advantage estimates PPO relies on were noise.
4. A metric that lies
Phase 2 reported a hit accuracy of 287%. Other runs logged 386% and 402%.
Accuracy can’t go above 100%, so the counter was wrong: hits were being counted per physics frame or per agent rather than per attack. It’s the kind of number that’s easy to scroll past in thousands of lines of logs, and it would have kept looking like progress.

5. Settings that never took effect
The phase configs set episodes from 15 to 45 seconds. Every log shows a mean episode length of 1,200 decision steps: the full 60 seconds. Somewhere between the config and the environment, the setting was dropped, and every phase trained on full-length matches. Phase 2’s short bursts of aggression never happened.
The later lessons paid off least. After 2.8M steps, Phases 3–5 finished with negative average rewards in both full runs.

The two runs differ tenfold in size, but they agree on the sign: by the last three lessons, the agents were losing more reward than they earned.

Plan B: one long self-play run
After fixing all of this, I asked whether five phases were worth it. Every phase had its own reward table, its own bugs and its own fixes. I was debugging the curriculum more than training the fighter.
So I replaced it with a single “master” run: all seven actions from the first step, no phases, 5M steps of self-play.

The chain of hand-offs, each with its own rewards to tune, becomes a single loop: the policy fights an opponent drawn from its own past, learns from the result, and adds to the pool.
The rewards flip the priority. Winning is the main signal, everything else is light shaping, and nothing goes above 100:
| Signal | Reward |
|---|---|
| Win / loss / draw | +100 / -100 / -50 |
| Hit landed / hit taken | +5 / -5 |
| Successful block | +2 |
| Missed attack | -1 |
| Ideal spacing (60–80 px) | +0.1 per step |
| Too close (under 50 px) | -0.5 per step |
| Oscillating | -0.5 |
Compare +5 per hit with Phase 2’s +1,000. The shaping can no longer drown out the question that matters: did you win?
The opponent pool grew to 20 checkpoints. Each match, the opponent is the current policy 30% of the time, a recent checkpoint 40%, an older one 20% and a random policy 10%.
PPO settings: learning rate 3e-4, n_steps 2,048, batch size 256, 10 epochs, gamma 0.99, GAE lambda 0.95, clip 0.2, entropy 0.01, a [256, 256, 128] network and 16 parallel environments. The curriculum had used a higher learning rate (5e-4) and five times the entropy (0.05).
Where it landed: good enough
The 5M-step master run finished, and its final model, models/master/latest_master.zip, is the one I play against in the launcher. That was the goal: an AI that can fight a human, end to end, from training to a playable game.
It could be better. I never saved a head-to-head win rate between the master model and the Phase 5 model, so I can say Plan B is simpler, not that it’s stronger. Several bugs, like the impossible accuracy and the ignored episode lengths, were found late, after compute had already gone into runs built on them. Catching them on day one would have saved the most time.
What I learned
- Your agent optimises your rewards, not your intentions. Vibrating in place was a reasonable answer to the rewards I wrote.
- Keep rewards on one scale. If explained variance sits at 0, your critic isn’t learning, and huge rewards are a likely cause.
- Sanity-check every metric against its bounds. An accuracy over 100% is a bug, not a breakthrough.
- Confirm your config reaches the environment. Compare the logged episode length with the one you set.
- Don’t let the environment do the agent’s job, and make penalties conditional. Auto-facing caused one stutter; penalties with no escape caused the other.
- Keep the network shape fixed. Restrict behaviour in the environment, through masking, so weights can carry over.
- Simplify when the tuning outgrows the idea. A curriculum is only worth it if it saves more time than it costs.
What’s next
First, the missing number: a head-to-head win rate between the master model and the Phase 5 model. After that, I want to try hard action masking, and to use the 880 actions I recorded from my own matches. That recording uses an older 17-number observation, so it needs converting before it can teach anything.
If you’ve built agents with self-play or fought your own reward function, I’d like to hear what worked for you.
