Run your own AI on the games¶
Every RetroSpeedLab game is a pure function of its RAM and the buttons held: no clock, no hidden state, no randomness outside the 2 KiB of memory. That makes the games a clean playground for your own agents. This guide goes from a ten-line script to a trained PPO policy and the full TAS search, with code that runs against the repository as it is.
Run everything from the repository root in Linux or WSL, after uv sync --locked. Save each script to a file and run it with uv run python <file>.
What an agent sees¶
The cartridge contract is the whole interface:
| Call | Gives you |
|---|---|
reset(ram, unlocked) |
Power-on |
step(ram, buttons) |
One frame, at 60 frames per second |
level(ram) |
The level being played, from 0 |
won(ram) |
True from the frame the game is beaten |
dead(ram) |
True when the hero goes down |
hero(ram) |
(area, x, y) of the hero, or None off the play field |
camera(ram) |
Where the screen looks |
bytes(ram) |
A savestate: restore it and the game continues exactly from there |
Buttons are nine slots, ("B", None, "SELECT", "START", "UP", "DOWN", "LEFT", "RIGHT", "A"), one boolean each. For the search, each game also has a speedrun wrapper in games/speedrun/<slug>.py with a typed RAM reader (lives, health, position, a progress measure), one state per stage with its goal, and an action table of short button patterns such as "jump right" or "dash up".
Play a game headless¶
The Console wraps a cartridge with power-on, step, savestates and the screen as a NumPy array.
import numpy as np
from retrospeedlab.engine.cartridge import BUTTONS
from retrospeedlab.engine.collection import GAMES_COLLECTION, cartridge_name
from retrospeedlab.engine.console import Console
console = Console(GAMES_COLLECTION, cartridge_name(GAMES_COLLECTION, "comet_courier"), False)
start = np.array([name == "START" for name in BUTTONS], dtype=np.int8)
idle = np.zeros(len(BUTTONS), dtype=np.int8)
console.step(start)
for _ in range(120):
console.step(idle)
ram = console.state()
game = console.cartridge
print(game.TITLE, game.VERSION, "level", game.level(ram), "won", game.won(ram), "hero", game.hero(ram))
Pip Express 2.0.4 level 0 won False hero (0, 24, 201)
console.get_screen() returns the current frame as a 240 × 256 × 3 image, console.get_ram() the RAM as an array, and console.restore(state) jumps back to any savestate.
Write a bot¶
A bot is a loop that reads the RAM and picks buttons. This one runs right and jumps whenever the hero stops making ground, then saves what it pressed as a movie:
from pathlib import Path
import msgspec
import numpy as np
from retrospeedlab.engine.cartridge import BUTTONS
from retrospeedlab.engine.collection import GAMES_COLLECTION, cartridge_name
from retrospeedlab.engine.console import Console
from retrospeedlab.engine.movie import Movie, encode
def press(*names: str) -> np.ndarray:
return np.array([name in names for name in BUTTONS], dtype=np.int8)
console = Console(GAMES_COLLECTION, cartridge_name(GAMES_COLLECTION, "comet_courier"), False)
power_on, pressed, best_x = console.state(), [press("START")], 0
console.step(pressed[0])
for frame in range(60 * 60):
hero = console.cartridge.hero(console.state())
stuck = hero is not None and hero[1] <= best_x and frame % 20 < 10
buttons = press("RIGHT", "A") if stuck else press("RIGHT")
best_x = max(best_x, hero[1]) if hero is not None else best_x
console.step(buttons)
pressed.append(buttons)
ram = console.state()
print("level", console.cartridge.level(ram), "won", console.cartridge.won(ram))
movie = Movie(console.name, console.version, power_on, encode(np.array(pressed)))
Path("bot.movie").write_bytes(msgspec.msgpack.encode(movie))
It will not beat Pip Express. That is the point: the games are built so that a skilled run needs routing, risk and movement tech.
Render a video¶
uv run python -m retrospeedlab.engine.cli video src/retrospeedlab/games bot.movie bot.mp4 libx264
The video plays the movie at twice the size with the game's music. Use h264_nvenc on an NVIDIA GPU.
Verify a run¶
A run counts only when it replays: the verifier powers the game on, feeds one byte of buttons per frame and reports the frame the game is won. The scripted route that beats Pip Express shows it:
from retrospeedlab.engine.collection import GAMES_COLLECTION, cartridge_name
from retrospeedlab.engine.pad import packed
from retrospeedlab.engine.verify import verified
from retrospeedlab.games.speedrun.routes import RUNS, load_route, route_frames
route = load_route(RUNS / "comet_courier" / "full.route")
inputs = bytes(packed(buttons) for buttons in route_frames(route))
print(verified(GAMES_COLLECTION, cartridge_name(GAMES_COLLECTION, "comet_courier"), inputs))
{'cartridge': 'retrospeedlab.games.comet_courier.cartridge', 'version': '2.0.4', 'won_at': 17409}
17409 frames at 60 frames per second is 4:50.15. A movie that starts at power-on verifies the same way with verified(..., movie.frames). The verifier also runs as a command that reads the inputs on stdin, which is how the backend calls it:
cd src
uv run python -m retrospeedlab.engine.verify retrospeedlab.games.comet_courier.cartridge < ../run.inputs # one byte per frame
Train a PPO policy¶
PolicyEnv is a Gymnasium environment over a game's speedrun wrapper. Observations are the RAM scaled to 0–1, actions are rows of the game's action table, and the reward pays for new RAM states and for leaving the current level, minus a penalty for dying. It starts from a start the search saved; for a first try, save power-on yourself:
cp config.example.yaml config.yaml
echo '[]' > hints.json
from pathlib import Path
from stable_baselines3 import PPO
from retrospeedlab.search.policy.env import PolicyEnv
from retrospeedlab.search.settings import load_config
from retrospeedlab.search.speedrun.live import LIVE_DIR
from retrospeedlab.search.speedrun.paths import tas_dir
from retrospeedlab.search.speedrun.policy_start import POLICY_START_FILE, save_policy_start
from retrospeedlab.search.speedrun.workers import worker_runner
from retrospeedlab.search.workflow.wrapper import game_wrapper
WRAPPER = game_wrapper("comet_courier")
CONFIG = Path("config.yaml").resolve()
output = tas_dir(load_config(CONFIG))
output.mkdir(parents=True, exist_ok=True)
if not (output / POLICY_START_FILE).is_file():
save_policy_start(output / POLICY_START_FILE, worker_runner(WRAPPER, CONFIG).power_on())
env = PolicyEnv(WRAPPER, CONFIG, output, output / LIVE_DIR)
model = PPO("MlpPolicy", env, n_steps=512, batch_size=64, verbose=1)
model.learn(total_timesteps=2048)
model.save(output / "my_policy")
From power-on the only exit is pressing START, so the policy learns that within a few rollouts. Once the search has run, policy_start.msgpack holds the level it is stuck on, and the same script trains on that. The search's own trainer, search/policy/trainer.py, runs several environments in parallel on the GPU and hands its exits back to the search.
Run the TAS search¶
The search is the AI that holds the records. To run it on one game, set up the configuration from the example and turn off what needs the production services:
ui:
enable: false # no relay to the backend
twitch:
enabled: false
speedrun:
vision_scouts: 0 # vision scouts need the Claude CLI
uv run python -m retrospeedlab.runner search comet_courier "$PWD/config.yaml"
It runs until stopped and keeps its state in working/cache/tas/: the route by level, the archives of explored cells, the record and a log. Check at any time that every stored piece still replays:
uv run python -m retrospeedlab.search.speedrun.run comet_courier "$PWD/config.yaml" working/cache/tas/levels.msgpack
Set training.game to search another game, and speedrun.policy: true to train PPO beside it on a GPU. Search explains the roles and every key.
Compare against the boards¶
Each game has one public board per minor version, with the AI's verified record beside the humans':
curl https://api.retrospeedlab.com/highscores/comet_courier
Times are in frames. Boards take runs played in the browser at games.retrospeedlab.com: the page records every input from power-on, and when you save with Discord the server replays them with the same verifier in a sandbox without network, new processes or writes outside a scratch folder. A run counts when it plays the board's version and won_at equals its length. Verify your agent's runs locally the same way and compare frames.