All guides

Build and train

Build and train

Simulator

The ladder's match code in JavaScript and Python, for millions of games offline.

Read as Markdown

The simulator is the ladder's own match code in one JavaScript file: the engine, the protocol's message checks and the server's match rules, with the shipped rules, maps, starter bot and Random built in. Use it to train a policy (reinforcement learning, self-play, tuning) without a server, sockets or clocks, from JavaScript or from Python. One CPU core plays about 100 to 150 games a second, plus your own bot's thinking time.

It isn't a copy of the game: the ladder runs every match on the same code, and each release of the ladder serves the simulator built from that release. A policy trained on it sees exactly the messages it will see on the ladder.

Download

Shell
curl -O https://assets.victris.ai/download/0.99.2/arena-sim.mjs                       # JavaScript (ES module)
pip install https://assets.victris.ai/download/0.99.2/victris_arena_sim-0.99.2-py3-none-any.whl  # Python 3.10+

Each release also publishes the same simulator as victris-arena-sim on npm and PyPI, a few minutes after it goes live, with its source in the public Victris Arena SDK repository (MIT):

Shell
npm install victris-arena-sim   # import { Game } from "victris-arena-sim"
pip install victris-arena-sim   # import arena_sim

The download links above always match the ladder you play on. To pin a registry install to it, add the ladder's versions.release from GET /api (victris-arena-sim==<release> or victris-arena-sim@<release>).

GET /api lists them under simulator: javascript, script (the same code as a plain script that sets a global ArenaSim, for engines that don't load modules) and python. Prefer those links: on the public ladder they may be versioned CDN URLs (/download/<release>/…) with long cache headers. The short /download/… paths on the ladder still work. The JavaScript file has no dependencies and uses no Node APIs, so it runs in Node 18+ and in browsers. The Python package runs that same file in embedded V8 (mini-racer), so it needs no Node.js.

Play a game in JavaScript

JavaScript
// train.mjs: node train.mjs
import { Game } from "./arena-sim.mjs";

let wins = 0;
for (let seed = 0; seed < 100; seed++) {
  const game = new Game({ seed, opponent: "ts-starter" });
  while (!game.over) {
    const obs = game.next(1); // the observation your bot would receive
    const enemy = obs.enemies[0];
    game.step({
      1: { move: "E", ...(enemy ? { attack: { name: "ranged", target: enemy.pos } } : {}) },
    });
  }
  if (game.next(1).result === "win") wins++; // after the last tick, next() is the end message
}
console.log(`${wins} wins out of 100`);

The loop is the same as a bot's loop on the ladder: answer each observation with a turn until end arrives. The messages are the ones the ladder sends, as plain JSON (the observation schema documents every field), so the code that turns an observation into a decision can be shared between training and your live bot.

new Game(options)

optiondefault
seed0decides the spawns and, unless map is given, the map (the seed modulo the number of maps, as the ladder picks)
mappicked by the seeda shipped map's name (arena-21, columns-21, pillars-21), or a map object of your own
opponentnonea bot to play fighter 2: the starter (ts-starter) or Random (random), a bot of yours (see your own bots) by its registered name or as an object. Without one, you play both fighters (self-play)
rulesthe shipped rulesa rules table, for experiments; the ladder only plays the shipped one
limitsthe rules' limitsthe deadlines hello reports and max_consecutive_failures (10 failed ticks in a row disqualify)
name, versionplayer, simwhat the replay records for your fighters
member
playersthe fighter ids you play: [1] against the starter, [1, 2] in self-play
hello(id)the match's hello for fighter id (rules, map, pickups, seed)
next(id)what fighter id has been sent and not yet answered: this tick's observation, or end once the match is over
nextFrame(id)the same as the JSON text, for passing to another process or language without parsing it here
step(replies)resolves the tick with one reply per player, keyed by fighter id
over, resultwhether the match has ended, and {winner, reason, final_tick}
summary(), replay()once over: the result, the replay and per-fighter stats (the same stats as end.stats)

The ladder separately records duration_ms in its match records and displays it on /match/<id> under Stats. This wall-clock measurement includes startup, bot waits and replay saving; it is null for older games. Local simulation and replay-derived stats do not contain this server duration.

A reply is what your bot would send: a turn object such as {move: "E", attack: {name: "ranged", target: [9, 4]}} (its tick is filled in if you leave it out), the raw JSON text, or null for no reply. Each takes the ladder's path: a malformed frame, a schema error, a reply for the wrong tick or no reply is an idle turn that counts as a failure, reported in the next observation's events like on the ladder; a well-formed turn with an illegal part loses only that part.

null models a missing reply (timeout), not a disconnected socket. The simulator has no transport or wall-clock reconnect grace. On the ladder, disconnected turns do not count as protocol failures; combat continues while the client is away. See disconnects, timeouts and match completion for live recovery and attribution. Replay stats count disconnects as runs of recorded disconnected turns, so they cannot establish socket-close counts or the underlying cause.

Unknown message types are schema failures. Attack names must be actual entries in hello.rules.attacks; other names are refused as unknown_attack. Direct shots lock their aim direction after movement, before repulsors resolve. A push shifts the launch point but preserves that direction, even if the shooter lands on its original aim tile; the shot fires with its normal cooldown. The projectile's target shifts with its origin to describe that direction. These rules also apply in the Python bundle.

Play from Python

Python
import numpy as np
from arena_sim import ArenaVectorEnv, Basic

# 64 matches at once against Random and the starter, stepped in one call.
env = ArenaVectorEnv(64, opponent=["random", "ts-starter"], encoder=Basic())
obs, info = env.reset(seed=0)
rng = np.random.default_rng(0)
for _ in range(1000):
    actions = np.array([rng.choice(np.flatnonzero(mask)) for mask in info["action_mask"]])  # your policy here
    obs, rewards, terminated, truncated, info = env.step(actions)
ArenaEnv(opponent, encoder, reward, map)a Gymnasium environment: one match an episode, as fighter 1 against the starter
ArenaVectorEnv(n, opponent, encoder, reward, map)n matches stepped together, the fast way (a Gymnasium vector environment with next-step autoreset), you as fighter 1. opponent is the starter, a policy of yours (below), a ScriptedOpponent, or a list of these spread over the matches; set_opponents(...) changes it for the matches that start next
ArenaSelfPlayEnv(n, encoder, reward, map)self-play: n matches stepped together with both fighters yours, as 2n environments (game 0's fighter 1, game 0's fighter 2, game 1's fighter 1, ...), so one policy learns from both sides
arena_sim.multiagent.ArenaParallelEnv(encoder, reward, map)self-play as a PettingZoo parallel environment, agents fighter_1 and fighter_2 (pip install "victris-arena-sim[pettingzoo] @ <the wheel's URL>")
Simulator(n)the low-level interface: start(i, seed=, opponent=, map=), then step([{fighter: reply}, ...]) for every game in one call, result(i), replay(i), replay_text(i), and close() (also a context manager) to release embedded V8. Any mix of house-bot games and self-play

Call env.close() (or sim.close()) when finished: that disposes the process's V8 isolate. On Python 3.13+, skipping it can leave the interpreter hanging at exit even after your script has finished its work.

An encoder turns observations into what your network reads and its actions into turns. Raw() (the default for ArenaEnv) passes the ladder's JSON through: observations are dicts and actions are turn dicts, exactly as a bot sends them. Basic() is a small, complete starting point to replace: a 9-channel grid of the map (walls, you, the enemy, shots, danger, areas, the zone, pickups) plus 19 numbers (health, cooldowns, states, time) in, and 68 discrete actions out (17 movements times 4 attacks), with info["action_mask"] marking the ones the engine would accept. Write your own by subclassing Encoder. The reward is win_loss (1, -1 or 0 at the end) unless you pass reward=f(observation, next_message); damage_trade adds, every tick, the damage you dealt minus the damage you took, a denser signal to start learning from. Every info carries the raw observation, and end when a match ends.

An opponent of your own comes in two kinds. A policy is a function policy(observations, action_masks) -> actions in the encoder's spaces, called once a step with every match it plays, so a network (say, a frozen copy of your own from an earlier checkpoint) runs batched. A ScriptedOpponent(decide) is written like a ladder bot: decide(observation, hello) gets the ladder's JSON and returns a turn dict, once per match. Training against a growing pool of your own past policies is a few lines:

Python
import copy

pool = ["random", "ts-starter"]
env = ArenaVectorEnv(64, opponent=pool, encoder=Basic())
# ... every so often, freeze the current network and add it:
frozen = copy.deepcopy(net)
pool.append(lambda obs, masks: frozen.act(obs, masks))  # your network's batched action function
env.set_opponents(pool)

Speed, per process: about 26,000 game ticks a second through Simulator; with Basic, about 16,000 seats through ArenaSelfPlayEnv (sending JSON to Python and encoding it there takes most of that), plus your network's time. A call into V8 costs about 200 µs, so step many games per call rather than one environment per call. If Basic is your encoder, the fast environments below do the same work many times faster.

Fast environments

FastVectorEnv and FastSelfPlayEnv play the same matches as ArenaVectorEnv and ArenaSelfPlayEnv, through the same match code, but the simulator encodes them itself: it writes every seat's grid, numbers, action mask, reward and done flag into one buffer that numpy reads in place, and reads your actions from it. No JSON crosses into Python. The encoder is Basic unless you give it your own. Basic's arrays are exactly what Basic makes of the ladder's JSON (a test checks it, value for value), so a policy trained here plays a ladder bot that runs Basic.encode on its observations.

Python
import numpy as np
from arena_sim import FastSelfPlayEnv, FastVectorEnv

if __name__ == "__main__":
    # Self-play, the matches split over 12 processes. Or, against starter with the shaped reward:
    # env = FastVectorEnv(128, opponent=["random", "ts-starter"], reward="damage_trade")
    env = FastSelfPlayEnv(1536, workers=12)
    obs, info = env.reset(seed=0)
    rng = np.random.default_rng(0)
    for _ in range(1000):
        actions = (rng.random(info["action_mask"].shape) * info["action_mask"]).argmax(1)  # your policy here
        obs, rewards, terminated, truncated, info = env.step(actions)
    env.close()
FastVectorEnv(n, opponent, map, reward, workers, copy, grid, encoder, scripts, teacher)n matches, you as fighter 1. opponent is a bot by name (the starter, or one of yours from scripts: either runs inside the simulator), a ScriptedOpponent (a bot written in Python), a batched Policy of yours (called with the arrays and masks of every match it plays), or a list of these; set_opponents(...) changes it for the matches that start next, and playing says who each match is playing now
FastSelfPlayEnv(n, map, reward, workers, copy, grid, encoder, scripts, teacher)self-play: n matches as 2n environments, in ArenaSelfPlayEnv's order

What's different from the JSON environments:

  • The encoder runs in the simulator: Basic (with size as its one setting, and the observation and action spaces Basic()'s), or one of yours written in JavaScript (below), not a Python Encoder.
  • reward is "win_loss" or "damage_trade", the functions of those names computed in the simulator, rather than a Python function of the messages. For a reward of your own, every step's info["dealt"] and info["taken"] are the damage each seat dealt and took that tick, as fractions of its max hp (0 on the tick a match ends, whose result is in info["result"]).
  • No messages in info. A seat whose match just ended has info["result"] (1 a win, -1 a loss, 0 a draw) instead of end. seed, action_mask and, with same-step autoreset, final_obs are as before. Only a ScriptedOpponent (or teacher) gets the ladder's JSON: the simulator sends its seats' observations to Python, and nobody else's.
  • workers=N splits the matches over N processes, each with its own V8 and its share of the matches, writing into memory shared with yours. They start with spawn, so put your script's top level under if __name__ == "__main__":.
  • copy=False hands out grid and vec as views of the simulator's buffer instead of copies: no copying at all, but the next step overwrites them, so use them (or copy them to the GPU) before stepping again. Stable-Baselines3 keeps the last observation across a step: leave copy on with it.
  • grid="uint8" makes the grid a byte a tile, a quarter the size: less to copy between processes and to the GPU, and to keep in a rollout buffer. decode_grid(codes) turns it back into Basic's values exactly, on a numpy array or a torch tensor (on the GPU, after the copy): a danger code c is 1 / c (0 for none), any other code is half its value. Danger more than 254 ticks away, which today's maps can't produce, reads as 1/255.
  • replay_text(g) gives match slot g's most recently finished match as a replay file. Its ticks carry no state hashes (hashing a tick costs more than playing it); everything else is as Simulator records it.

Measured on a desktop (Intel Core Ultra 9 285K, 24 cores), random legal actions, environment steps a second:

steps/s
ArenaSelfPlayEnv(64), for comparison16,000
FastSelfPlayEnv(128), one process105,000 (121,000 with copy=False)
FastSelfPlayEnv(1536, workers=12, copy=False)456,000
FastSelfPlayEnv(1536, workers=12, copy=False, grid="uint8")463,000

About 128 matches a process is the sweet spot; past 12 to 16 workers the cores and memory are busy. Opponent decision costs affect throughput; measure your training setup. The same batch is in the JavaScript module as VectorBatch, for training loops written in JavaScript: new VectorBatch(n, {opponents, encoder, teacher, taught, map, reward, autoreset, size, grid}), with buffer, layout (where each array is in it) and spec (the encoder's sizes), reset(seed), step(), setOpponents, setTeacher and replayText(g).

Profile offline training

Use profile=True to diagnose FastVectorEnv or FastSelfPlayEnv without patching workers. It is off by default. JavaScript samples one batch step in 16; profile_every=1 measures every step at higher overhead. Read a detached snapshot when you need one:

Python
env = FastVectorEnv(1024, workers=4, copy=False, grid="uint8", profile=True)
obs, info = env.reset(seed=0)
# ... collect a rollout ...
report = env.profile(reset=True)  # read and clear diagnostic counters; games keep playing
for worker in report["workers"]:
    print(worker["simulator"]["phases_ms"])

In JavaScript, use new VectorBatch(n, {profile: true}), or {profile: {every: 1}}, then batch.profile() or batch.profile(true) to read and clear. A disabled profiler returns null (None in Python). reset(seed) resets games; it does not clear profiling counters.

ReportWhat it measures
simulator.steps, sampled_steps, everyTotal step attempts, sampled attempts, and the sampling interval. Initial reset() is excluded.
simulator.games, resets, encoded_seatsValid game transitions, autoreset slots and non-terminal seat encodings within sampled steps. A same-step terminal transition can count as both a game and a reset. Reset setup includes its initial encoding, excluded from encoded_seats.
simulator.elapsed_msWall time inside every JavaScript step, in milliseconds. Compare with all-call Python v8_seconds for a coarse bridge/scheduling estimate, subject to clock quantization and adjustments.
simulator.total_ms, phases_msSampled JavaScript wall time in milliseconds. Non-overlapping phases: actions (decode, bot policy and turn validation), simulation (resolve and replay recording), observation, encoding, teacher, wire (opponent observation copies), reset (whole autoreset setup), and other (rewards, buffer clearing and remaining work).
Each Python worker's steps, v8_seconds, python_secondsAll successful calls, elapsed time around the V8 step call, and external Python bot/teacher reply handling, in seconds. V8 time includes JS execution, bridge work and scheduling; sampled JS phase totals cannot be subtracted from this all-call value.
pid, first_game, num_games, ready_at, completed_atWorker identity, game range and perf_counter() timestamps: ready after loading the batch, latest step completed before its ACK. Completion order is independent of parent receive order. With one process, completion follows Python reply handling.
Pool workers' action_copy_seconds, publication_seconds, service_seconds, service_cpu_secondsAll-step action copy, shared-memory publication, and service totals. Service starts before action copy and ends after publication, excluding command wait and ACK send. CPU time uses the entire worker process, including V8 threads.
parent (pool only; otherwise None)All-step steps, dispatch_seconds, wait_seconds, and corresponding dispatch_thread_cpu_seconds / wait_thread_cpu_seconds. Waiting wall time includes worker computation and descheduling; it is not serialization cost.

Snapshots are requested explicitly. Steps send no observation JSON or simulator timing JSON for profiling; pool ACKs add only a completion timestamp. Snapshots keep bounded aggregate totals, not a history of every step. Clearing counters preserves ready/completion timestamps. Batched Python opponent policies run in the parent and are outside these worker timings.

With this repository, compare worker counts and enabled/disabled overhead on your CPU allocation:

Shell
bun run build:sim
uv run --project packages/sim-python python scripts/profile-simulator.py --source packages/sim/dist/arena-sim.js --workers 1 2 4 8 --games 1024 --ticks 512 --repeats 3

The benchmark warms up, reverses run order between repeats and prints JSON lines with valid game transitions/s, reset slots and diagnostic snapshots. --baseline-source <older-arena-sim.js> also compares disabled profiling with an older bundle. Startup and snapshot retrieval are outside the timed rollout. Use a fixed CPU allocation; try fewer workers before adding more. Worker counts change seed partitioning, so throughput comparisons do not prove learning equivalence. Random-action simulator throughput is not end-to-end PPO throughput. The house champion has a separate batch and worker implementation; these diagnostics cover the public simulator.

Your own bots, encoders and teachers

The fast environments run more than the starter and Basic. Three things of yours go inside the simulator, where they cost no JSON and no extra process:

  • Bots, to play against: the bot you wrote for the ladder, the starter's code changed, a rival's style you've written down. A policy trained against a few opponents learns to beat those; more and stronger opponents make it general.
  • An encoder, the part of a learning bot that turns the observation into what the network reads and its action back into a turn. Basic is a small starting point. What a network can't see it can't learn, so the encoder is often where a bot gets better, and the fast environments run yours at the same speed as Basic.
  • A teacher: a bot whose turn on every state your policy reaches is written next to it, as the action your encoder comes closest to. Imitating it there (not only on the states the teacher reached itself, as imitating recorded games does) is how you distil a scripted bot into a network, and a shaping signal next to the reward.

They are JavaScript, since the simulator is. In Node or a browser, pass them as objects; for Python, put them in a script that registers them by name, and pass the script:

JavaScript
// mine.js: loaded after the simulator, which defines ArenaSim
ArenaSim.registerBot("mine", {
  version: "1",
  start(hello) {
    // once a match: what answers each of its observations
    const memory = { seen: 0 };
    return (observation) => {
      // the JSON the ladder would send it
      memory.seen++;
      const step = observation.moves[0];
      return step ? { move: step.dir } : {}; // a turn as the bot would send it (tick filled in)
    };
  },
});
Python
from arena_sim import FastVectorEnv
env = FastVectorEnv(256, opponent=["mine", "ts-starter"], scripts=["mine.js"], workers=8)

A bot's turns take the ladder's path: the protocol's schema, then the match rules, so a malformed turn is an idle, failed tick, and ten in a row disqualify it, as on the ladder. An exception in it stops the step with its message. Game takes a bot as its opponent too, and Simulator (Python) takes scripts and the names they register.

From a TypeScript bot. The starter keeps its strategy in strategy.ts, apart from the connection, with no imports. A few lines put it in a script (esbuild bundles it, with your bot's other modules):

TypeScript
// sparring.ts: npx esbuild sparring.ts --bundle --format=iife --outfile=sparring.js
import { decide } from "./strategy.ts";
declare const ArenaSim: any;
ArenaSim.registerBot("mine", {
  version: "1",
  start: (hello: any) => {
    const match = { id: hello.match_id, rules: hello.rules };
    return (obs: any) => decide(obs, match);
  },
});

From a Python bot. A ScriptedOpponent plays in the fast environments too: the simulator sends its seats' observations to Python as the ladder's JSON and takes its turns back. It runs at your bot's speed, in Python, but only its seats leave the simulator. Give it decide(observation, hello), or start(hello) returning each match's decide(observation) to keep per-match state. With workers, it goes to each worker process, so define those functions at the top level of a module (from bot import decide works, with websockets installed: the starter's connection only runs when it's started as a script):

Python
from arena_sim import FastVectorEnv, ScriptedOpponent
from bot import decide  # your bot.py

def start(hello):
    match = {"id": hello["match_id"], "rules": hello["rules"]}
    return lambda observation: decide(observation, match)

env = FastVectorEnv(256, opponent=[ScriptedOpponent(start=start), "ts-starter"], workers=8)

An encoder says the sizes of what it writes and turns each seat's observations into them:

JavaScript
ArenaSim.registerEncoder("mine", {
  gridShape: [4, 21, 21], // per seat; [0] for no grid
  gridType: "float32", // or "uint8": a quarter the memory to copy and keep
  features: 12, // numbers beside the grid
  actions: 51, // how many actions the policy chooses from
  start(hello) {
    // once per fighter per match: it may remember earlier ticks
    let last = null;
    return {
      encode(observation, out) {
        last = observation; /* write out.grid, out.vec, out.mask (1 = allowed) */
      },
      turn(action) {
        return {/* the turn this action stands for, after `last` */};
      },
      action(turn) {
        return 0; /* the action closest to a turn, or -1: for teachers and imitation */
      },
    };
  },
});
Python
env = FastSelfPlayEnv(1024, encoder="mine", scripts=["mine.js"], workers=12, copy=False)
env.single_observation_space  # {"grid": Box(4, 21, 21), "vec": Box(12,)}, from the encoder's sizes
env.spec                      # the same sizes, as the simulator reports them

Each tick the arrays start at zero, so write only what's there. The encoder sees the observation as the batch builds it, not parsed from JSON; check_encoder (below) proves it reads both the same. Its turns are checked like a bot's. A mask that allows an action the engine refuses loses only that part of the turn, as on the ladder.

A teacher is a bot by name or a ScriptedOpponent:

Python
env = FastVectorEnv(1024, opponent="ts-starter", teacher="mine", scripts=["mine.js"], workers=12)
obs, info = env.reset(seed=0)
info["teacher_action"]  # per seat: the teacher's action there, or -1 where none of yours fits

It labels the fighters you play (in FastVectorEnv, fighter 1), using your encoder's action(turn), kept only where the mask allows it. set_teacher changes it (or removes it, with None) for the matches that start next.

On the ladder. A TypeScript bot imports the encoder's module and calls it as the simulator does. A Python bot runs the same JavaScript through ScriptEncoder, so the training and the live encoding are one piece of code:

Python
from arena_sim import ScriptEncoder
encoder = ScriptEncoder("mine", scripts=["mine.js"])      # or ScriptEncoder("basic")
x = encoder.encode(observation, hello)                     # {"grid", "vec"}, as in training
mask = encoder.action_mask(observation, hello)
turn = encoder.decode(policy(x, mask), observation, hello) # the reply's move, dash and attack

It keeps each fighter's encoder by match, starting a new one when a match starts, and also works as the encoder of the JSON environments (ArenaVectorEnv(..., encoder=ScriptEncoder(...))).

Checking an encoder. check_encoder(replay, "mine", scripts=["mine.js"]) replays a recorded match through two copies of your encoder, one reading the observations the batch passes and one reading the ladder's JSON, and reports every difference: in the arrays, in the turn for any allowed action, and wherever action(turn(a)) isn't a (which teachers and imitation rely on). State shared between seats, or kept outside start, shows up here. Run it on a few replays before a long training run, and again when you change the encoder.

Stable-Baselines3

arena_sim.sb3.ArenaVecEnv makes ArenaVectorEnv, ArenaSelfPlayEnv or a fast environment an SB3 vector environment that steps every match in one call (pip install "victris-arena-sim[sb3] @ <the wheel's URL>"). SB3 restarts an episode on the step that ends it, so make the environment with autoreset_mode=AutoresetMode.SAME_STEP. sb3-contrib's MaskablePPO gets Basic's action masks from it, and from ArenaEnv.action_masks() if you use single environments instead.

Python
from gymnasium.vector import AutoresetMode
from sb3_contrib import MaskablePPO
from arena_sim import ArenaVectorEnv, Basic
from arena_sim.sb3 import ArenaVecEnv

env = ArenaVecEnv(ArenaVectorEnv(64, opponent=["random", "ts-starter"], encoder=Basic(),
                                 autoreset_mode=AutoresetMode.SAME_STEP))
model = MaskablePPO("MultiInputPolicy", env, n_steps=128, batch_size=1024)
model.learn(total_timesteps=1_000_000)
model.save("arena-ppo")

This trains about twice as fast as SB3's own DummyVecEnv over 64 ArenaEnvs. A finished episode's info has its terminal_observation and end message (from a fast environment, its result).

Train a policy: the example PPO script

arena_sim.examples.train_ppo trains sb3-contrib's MaskablePPO with the Basic encoder, action masks and the damage_trade reward (damage dealt minus damage taken, then the win or loss). It trains against random until it wins 90% of fresh matches, then ts-starter (mixed with some Random) until it wins 60%. Extend CURRICULUM with your own registered opponents as your policy improves.

Shell
pip install "victris-arena-sim[sb3] @ https://assets.victris.ai/download/0.99.2/victris_arena_sim-0.99.2-py3-none-any.whl"
python -m arena_sim.examples.train_ppo --out arena-ppo

The script evaluates every 100,000 steps and saves arena-ppo.zip. --help lists the settings. Training time depends on your hardware and opponents; evaluate on fresh seeds and all maps.

Train on a GPU: the fast PPO script

arena_sim.examples.train_ppo_gpu trains against the same Random-to-starter curriculum in plain PyTorch. It runs FastVectorEnv over worker processes with byte grids, decodes those grids on the GPU and keeps the rollout and updates on the device. CUDA graphs reduce update overhead. It also runs on a CPU.

Shell
pip install torch --index-url https://download.pytorch.org/whl/cu130
pip install "victris-arena-sim @ https://assets.victris.ai/download/0.99.2/victris_arena_sim-0.99.2-py3-none-any.whl"
python -m arena_sim.examples.train_ppo_gpu --out arena-gpu

It saves arena-gpu.pt. load(path) returns a batched policy, policy(observations, action_masks) -> actions, which FastVectorEnv also accepts as an opponent. On the ladder, encode each observation with Basic().encode(observation, hello) and call the policy on a batch of one. Train against frozen copies of yourself to build a broader opponent pool.

Learn from ladder games

WebSocket keepalive belongs to the live client, outside the simulator. The starters use client Pings every 20 s with a 20 s Pong timeout and reconnect on failure; no JSON heartbeat or simulated tick is involved. Queue silence is normal, and transport recovery does not guarantee the current match survived. See keepalive and recovery.

Live connections receive hello again when they reconnect or take over an attached match, followed by the current observation if play has started. A repeated match_id means resumption; keep any retained strategy state. Socket handoffs do not restart the simulation, restore spent budget or appear in replay trajectories as additional match starts. A fresh live client can initialize from the resent hello; see message flow.

Every ladder match is public, with its replay. replay_trajectories re-runs a replay through the server's own match code and gives back each fighter's view of it: the hello, then every tick's observation exactly as that bot was sent it and the turn the server took from its reply (with a reason when the turn was idle: a timeout, a bad message...), and the end. That is training data for imitating strong bots, offline RL, or studying a rival.

Python
from arena_sim import download_replays, replay_trajectories

for match, replay in download_replays("https://victrisarena.com", bot="house-kiter", limit=20):
    trajectories = replay_trajectories(replay)
    for bot in match["bots"]:
        trajectory = trajectories[bot["fighter"]]
        pairs = [(s["observation"], s["turn"]) for s in trajectory["steps"]]  # what it saw, what it did
        print(bot["name"], bot["version"], trajectory["end"]["result"], len(pairs), "ticks")

download_replays(ladder, bot=None, limit=50, min_rating=None, cache=None) yields a bot's (or everyone's) most recent matches, newest first, as the match record and the replay's text. With min_rating, it fetches the recent matches of every bot on the leaderboard rated at least that, each match once, and each record gets strong: the fighter ids of those bots in it. cache is a directory to keep replays in, so running it again fetches only new ones. It fetches each minute's public pack once where the ladder has them, and otherwise each replay's own URL. League matches do not advertise bulk downloads. Downloads reach back 30 days; older matches aren't available for training. Anyone may download each bot's newest 200 public matches: a bot's list stops at its first older match, with a warning, and cache remembers that refusal so a rerun doesn't ask again. Retry a temporary 503 after its Retry-After delay. replay_trajectories also takes a replay file's path, its gzipped bytes or a parsed replay. A replay doesn't record everything: in the rebuilt messages budget_ms_left stays at the match budget, match_id is "replay", the deadlines are the rules' defaults and a refused message's event has no detail; a disqualified bot's last observation, whose reply never resolved, is missing. A replay from another release's engine or rules is refused (ValueError). In JavaScript the same function is replayTrajectories(parseReplay(text)).

For imitation, replay_dataset goes straight to arrays through an encoder from the simulator (Basic, or yours), a row per fighter per tick: what it saw as your network reads it, its mask, and action, the encoder's action closest to the turn it sent (-1 where it timed out or nothing allowed comes close):

Python
import numpy as np
from arena_sim import download_replays, replay_dataset

pairs = list(download_replays("https://victrisarena.com", min_rating=1800, limit=200, cache="replays"))
data = replay_dataset(pairs, "basic", grid="uint8")   # or "mine", scripts=["mine.js"]
strong = np.array([f in pairs[m][0]["strong"] for m, f in zip(data["match"], data["fighter"])])
x, y = {"grid": data["grid"][strong], "vec": data["vec"][strong]}, data["action"][strong]

It also returns mask, fighter, tick, match (which replay) and skipped, the replays from another release, which the simulator can't replay. fighters= keeps only some fighters' rows: a list of ids, or a function of the replay's header. In JavaScript, replayDataset(replay, encoder).

python -m arena_sim.examples.imitate --ladder https://victrisarena.com --min-rating 1800 does all of it: downloads the strong bots' matches, trains train_ppo_gpu's network to predict their actions (holding a tenth of the matches out to measure how often it agrees with them), saves it, and plays it against the starter. Imitation copies the experts on the states they reached; on states they never did it can fall apart, which is what a teacher and reinforcement learning fix.

Train against a league

python -m arena_sim.examples.league --init arena-bc.pt --bots random ts-starter --minutes 30 goes on from a network (imitate's, train_ppo_gpu's, or none) with PPO, every match against an opponent drawn from a pool: bots by name (the starter, or yours, with --scripts), the network it started from, frozen copies of the learner taken as it improves, and the learner itself (--self-play, a share of the matches). Opponents it still loses to are drawn more often. --kl pulls the policy toward the network it started from, so early updates don't undo it; --teacher adds imitation of a bot's turns on the states the learner reaches. It reports its share of wins against each named bot and its recent results against each opponent in the pool, and saves last.pt and best.pt (the best worst-case share of wins). Like the other examples it is a starting point to copy: the pool, the weighting, the network and the losses are yours to change. --encoder and --scripts train it through your encoder.

Use it during a match

Computation on your own machine is yours to use: a bot may run the simulator while it plays on the ladder, for example to search ahead by simulating candidate turns against likely replies before choosing one. It still knows only what its observations show (fog of war hides the rest), and the deadlines still apply: 1 second a tick, 300 seconds a match, network time included.

Look ahead: the forward model

forward is the engine's own tick, for bots that search. Build a state from what your bot was told, copy it, step candidate turns and score what comes out. It is the code the ladder resolves matches with, so a step here is the step there. One core copies and steps about 200,000 states a second.

JavaScript
import { forward } from "victris-arena-sim"; // or from "./arena-sim.mjs"

// Each tick: the state as your bot sees it, with a guess for where a hidden enemy is.
const state = forward.fromObservation(hello, obs, { enemy: { pos: lastSeen } });
const me = hello.bot_id;
const enemy = hello.opponent.bot_id;
const myTurns = forward.options(state, me).moves.map((m) => ({ move: m.dir }));
const replies = [{}, ...forward.options(state, enemy).moves.map((m) => ({ move: m.dir }))];

// The turn whose worst reply leaves you best off.
let best = null;
for (const mine of myTurns) {
  let worst = Infinity;
  for (const theirs of replies) {
    const next = forward.clone(state);
    forward.step(next, { [me]: mine, [enemy]: theirs });
    worst = Math.min(worst, score(next, me)); // yours: hp, position, pads...
  }
  if (!best || worst > best.worst) best = { turn: mine, worst };
}
forward.
start(hello)the match's state on its first tick, exactly as the ladder starts it: the hello names the map and carries the seed, which decides the spawns
fromObservation(hello, obs, assume?)a state that agrees with everything obs shows; what the fog hides comes from assume (below)
clone(state)a copy to step without touching the original
step(state, turns)resolves one tick in place and returns its events. turns is {fighterId: turn}, each as your bot would send it; a missing one is idle
observe(state, id)the observation fighter id would receive on this tick, without the server's budget and events
options(state, id)the steps and dashes fighter id could start now (an observation's moves and dashes)
validate(state, id, turn)how the engine would take that turn: turn (the parts it plays) and rejected (the parts it refuses, with the reason)
hash(state)the ladder's hash of the whole state, as recorded with every replay tick
apithe contract's version; it changes when a function's arguments or results do

Each turn is validated as on the ladder: an illegal part is dropped and reported in a rejected event, and the rest is played. step throws once state.result is set. Both start and fromObservation need the hello's map to be one this simulator ships, unchanged; for a map of your own, pass the map object as their last argument. They also refuse a hello whose engine_version isn't this simulator's engine: its steps would not be the ladder's. In training, game.state() gives a copy of a Game's whole state, fog and all, to search with the truth or to check a bot's guesses against it.

A state is plain data, safe to turn into JSON: the engine's match state, the same object each replay tick's hash is taken over. Read it, and change it to fit what you believe (fighters, pickups, projectiles, areas, zone, tick).

What the fog hides

fromObservation takes everything the observation shows as fact. For the rest, give your own guesses in assume, written the way an observation would show them (ticks left, not absolute ticks). Without a guess it picks a cautious default.

assume.what it isdefault
enemythe opponent: pos, hp, cooldowns, state, state_ticks_left, buffs, ticks_outside, damage_dealt. Only what isn't in sight is usedin sight: every attack ready (only its dash cooldown is shown). Out of sight: pos is required, full hp, everything ready
selfticks_outside (consecutive ticks you ended outside the zone, which zone damage grows with) and damage_dealt0
pickupspads out of sight, by pad id: {ready_in}, 0 for stockedstocked once pads first appear
projectilesshots you believe are flying out of sight, in the observation's formnone
areasfrost areas you believe are out of sight, in the observation's form (tiles not needed)none

A state rebuilt with the true values for all of these plays on exactly like the real match. Two things are never shown and change nothing: where a frost area was thrown from, and ids used up by shots that already ended (next_projectile_id).

From Python

ForwardModel runs the same functions in embedded V8, with states as dicts. Its step and step_many return new states instead of changing theirs. A call costs more than a tick, so expand a node's children with one step_many:

Python
from arena_sim import ForwardModel

fm = ForwardModel()
state = fm.from_observation(hello, obs, {"enemy": {"pos": [10, 10]}})
children = fm.step_many(state, [{1: {"move": "E"}, 2: {}}, {1: {"dash": "W"}, 2: {}}])
for child, events in children:
    print(fm.observe(child, 1)["self"]["hp"])

Simulator.state(i) gives game i's whole state, like game.state().

Differences from the ladder

  • No clock. Nothing is timed, so self.budget_ms_left stays at the match budget and a reply never arrives late. On the ladder you have 1 second a tick and 300 seconds a match, network time included; time your bot's decisions yourself.

  • Your fighter is 1 against the starter. On the ladder you may be fighter 1 or 2. The seed, not the id, decides who spawns where, and the maps are mirror-symmetric, so a policy shouldn't care.

  • Only the starter and Random are bundled. ts-starter runs the same strategy as the downloadable TypeScript starter. Brawler, Kiter and the other house opponents are available on the ladder; their strategies and shared helpers are excluded from simulator bundles and source maps. Train offline with the starter, Random, self-play, your own bots or networks learned from replays. The stronger Brawler and Kiter are scripted ladder opponents, with the same combat rules.

  • Bundled limits. Deadlines and failure tolerance are the release's defaults. Pass the live operational_policy.match_limits from GET /api as Game's limits option to reproduce the ladder's current ones; replays keep their match's actual limits.

  • No matchmaking. Online weighted/information policy choices do not affect offline games. Offline games use the opponents, maps and seats you choose; they don't reproduce queueing, the ladder's map balancing or its fighter-id assignment. When comparing bots, cover every map and both fighter ids.

  • No live transport. There are no reconnects, server_draining notices or restarts to handle.

Staying current

Rules and engine change only in a release, and each release's simulator carries its number. A simulator is current while its release and rules hash match the ladder's (GET /api, versions.release and versions.rules_hash). After a release, download it again.

  • Hear about releases. Subscribe to https://victrisarena.com/changelog.atom. A release that changes the rules says so in its title: until you update, the simulator plays another game.

  • A match names its engine. Each hello carries engine_version. The engine can change in a release while rules.version stays the same, so a bot that relies on the engine's exact steps compares that, not only the rules. The forward model does it for you: forward.start and forward.fromObservation refuse a hello from another engine.

  • The Python package warns when the ladder plays other rules or another engine. It compares what the ladder has already sent you with the rules and engine it ships, and raises an OutdatedSimulatorWarning (once per rules table or engine version) when they differ. It never contacts a ladder on its own to do it:

    • a live match's hello, when Basic or ScriptEncoder encodes the match's first observation. With an encoder of your own, call check_hello(hello) when a match starts;
    • the replays download_replays fetches (each replay's header records its rules).

    The match limits in hello.rules.limits are the ladder's live settings and don't count. The simulator's own games (sim-… match ids), on rules you pass to it, are left alone.

  • See what changed. python -m arena_sim changelog prints the ladder's release notes since yours (changelog() in Python). Each package also carries its own release's notes.

  • Read the source. The engine's TypeScript is in the Victris Arena SDK repository's engine/ folder, with the maps in maps/, at every release's tag: compare two tags to see exactly what changed. Each release also ships the TypeScript it was built from, as source maps next to the bundles (arena-sim.mjs.map, arena-sim.js.map) and inside the Python package: python -m arena_sim source ./arena-src writes it out (packages/engine/src/…, packages/sim/src/…) with that release's CHANGELOG.md.

  • Go back to a release. Every release's downloads stay at /download/<release>/… (for example the wheel https://victrisarena.com/download/0.41.1/arena_sim-0.41.1-py3-none-any.whl), and each release is on npm and PyPI, so you can re-run training or evaluation on the simulator a policy was trained on.

Shell
python -m arena_sim check https://victrisarena.com   # says whether it's current, and how to update
python -m arena_sim changelog                      # what changed since this release
python -m arena_sim source ./arena-src             # the TypeScript this release was built from
JavaScript
import { RELEASE, SHIPPED_RULES, rulesHash } from "./arena-sim.mjs";

const api = await (await fetch("https://victrisarena.com/api")).json();
if (api.versions.release !== RELEASE || api.versions.rules_hash !== rulesHash(SHIPPED_RULES))
  console.warn("the ladder runs another release: download the simulator again");
// A live bot can check the rules it trained on at the start of each match. The ladder writes its
// live limits into hello.rules.limits, which don't change the game, so leave them out:
// rulesHash({ ...hello.rules, limits: SHIPPED_RULES.limits }) === rulesHash(SHIPPED_RULES)
// and its engine: hello.engine_version === ENGINE_VERSION (import it too)

Replays

A finished game's replay opens in the viewer like a ladder replay. Knockouts get the same slow-motion final-hit close-up and delayed result reveal as Watch Live; the recording and simulation stay unchanged. Scrub or step to inspect a tick directly:

Actions and fighter labels use the replay's bot names (Game records name from its options). Unicode names remain intact in replays; hosted registration applies the API name rules, while local simulator labels do not need registration. Replays opened from the ladder use its display names when match metadata is available.

JavaScript
import { writeFileSync } from "node:fs";
import { gzipSync } from "node:zlib";
import { encodeReplay } from "./arena-sim.mjs";

writeFileSync("game.jsonl.gz", gzipSync(encodeReplay(game.replay())));
// then: bun run arena -- view game.jsonl.gz

verifyReplay and parseReplay are exported too. New recordings identify their producing release and replay_format: 1, alongside the engine version, embedded rules/map and inputs. Starting with release 0.62.0, the viewer and CLI select the recording's producing release, even if its engine version matches the currently installed engine. This preserves the original implementation as later releases change. The regression suite plays an unchanged 0.62.0 recording through its published runtime in the CLI and browser, checking its tick hashes, result, statistics and playback. Older files without those fields use the installed engine when compatible. For legacy engine 0.21.0, the viewer and CLI can load a separately versioned runtime built from the vetted 0.29.0 source. They check its pinned source/adapter identity and artifact checksum, then use that original engine to verify every tick and result. The recording's header and actions stay unchanged. Other unsupported legacy engines still report an incompatibility; no release is guessed.

The supported legacy artifact lives at /download/legacy-engines/0.21.0/v1/{manifest.json,arena-sim.mjs,replay-fixture.jsonl}. It is separate from the original release downloads. A missing or corrupt legacy artifact is an error; the viewer never retries that game using today's physics.

The bundle also exports replayRuntime (API 1): simulate, verifyReplay, replayStats, observe, stateHash, cloneState, and helpers for rendering/audio. Its identity fields are release, engine, format and api. simulate(replay, { keepStates: true, verifyHashes: true }) returns the reconstructed frames; verifyReplay checks the completed result as well. The frame/event/helper contract is versioned independently of the file format. Custom viewers must check the API before using archived frames. A release's manifest.json records artifact checksums and supported versions, and replay-fixture.jsonl provides a deterministic verification case.

Continuing a replay with --from/--swap requires that release of the CLI. Observations, snapshots, statistics and normal playback can use the archived runtime without continuing the match.

verifyReplay checks recorded tick hashes and combat results. A forfeit or disqualification must end at the next unresolved tick while combat is still running, with a living fighter as winner (a forfeit can also draw). It trusts the server's reason for that ending, since combat inputs cannot establish what happened to a socket or deadline.

Match summaries also include optional fighters[].occupancy: grid width, height and row-major counts. Each living fighter is sampled before each resolved tick; idle ticks count and dash traversal adds no extra samples. Older simulator releases may omit occupancy.