Testing your rules
A game's rules run in Node with no page and no graphics card. A test makes a world, gives orders, steps time and checks the result. The same helpers play hundreds of computer-vs-computer games for balance.
Quick start
import { order, run, testWorld } from '@v12-engine/engine/testing'
import { describe, expect, it } from 'vitest'
import { rules, UNIT } from '../src/rules'
describe('the rules', () => {
it('send a knight where it is ordered', async () => {
const world = await testWorld(rules)
const knight = world.spawn(UNIT.knight, 1, { x: 10, z: 10 })
order(world, [knight], { type: 'move', point: { x: 30, z: 10 } })
run(world, 20, () => knight.pos.x > 29)
expect(knight.pos.x).toBeGreaterThan(29)
world.dispose()
})
})Run it with npm test (Vitest). testWorld makes a flat world with test players, order gives an order as a player would, and run steps up to 20 seconds of game time or until the condition is true. Always world.dispose(): a world holds its navigation in WebAssembly memory.
Common tasks
Test on a real map with your start
import { createWorldFromMap } from '@v12-engine/engine'
import { expect, it } from 'vitest'
import { mapNamed } from '../src/maps'
import { onStart } from '../src/rules'
it('gives each side with a start five knights', async () => {
const map = mapNamed()
const world = await createWorldFromMap({ map, rules, seed: 1 })
onStart(world, { map })
for (const player of map.players) {
const knights = [...world.units.values()].filter((entity) => entity.def.id === UNIT.knight && entity.owner === player.id)
expect(knights).toHaveLength(5)
}
world.dispose()
})Save and load halfway
import { decodeSave, encodeSave, loadWorld, saveWorld } from '@v12-engine/engine'
const loaded = await loadWorld(decodeSave(encodeSave(saveWorld(world))), { rules: towerDefense })
expect(loaded.tunable(waveGapTuning.id)).toBe(waveGapTuning.max)Check the game is deterministic
import { checkDeterminism } from '@v12-engine/engine/testing'
const report = await checkDeterminism(() => createTowerDefense(1), { ticks: 2700, from: 300, rules: towerDefense })
expect(report).toEqual({ twice: null, fromSave: null })It runs your world twice side by side, and a saved world beside its load, and names the first tick and field that differ (entities[id 11].pos.x). Usual causes: Math.random (use world.rng), the clock (count ticks), or state outside the world.
Record and replay commands
import { recordCommands, runReplay } from '@v12-engine/engine'
const recorder = recordCommands(world, { player: 1, checkpoints: 300 })
// … the game is played …
const { apart, difference } = await runReplay(recorder.stop(), { rules: towerDefense })
expect(difference).toBeNull()Compare two saves with saveDifference(a, b, registry), or from a project with npx v12 save diff a.json b.json (exits 1 when they differ).
Expose a number to tune while playing
import { defineTunable, layTuning } from '@v12-engine/engine'
export const waveGapTuning = defineTunable({ id: 'td.betweenWaves', name: 'Seconds between waves', default: 15, min: 2, max: 60, step: 1 })// in the Rules
tunables: layTuning([firstWaveTuning, waveGapTuning], tuningFile)
// in the rules
waitForWave(world, world.tunable(waveGapTuning.id))The editor's Tuning panel shows a slider for each while the game plays; saving writes tuning.json. In a test, world.setTunable(id, value).
Play many games for balance
import { type Simulation, simulate } from '@v12-engine/engine/testing'
const duelOfComputers: Simulation = {
rules: melee,
map: duel(),
seconds: 45,
measure: (world) => ({
units: [...world.units.values()].filter((entity) => entity.alive && entity.isUnit && !world.player(entity.owner).neutral).length,
gold: world.player(PLAYER).resources.gold ?? 0
})
}
const games = await simulate(duelOfComputers, { seeds: [1, 2], onGame: (game) => console.log(game.seed, game.winner) })The computer plays every seat with a start until there is a winner or seconds run out.
Play in worker threads
// balance.mjs: a default export Node can load as it is
export default { rules: game, map, measure }
// the script
const games = await simulate(new URL('./balance.mjs', import.meta.url), { seeds: [1, 2, 3, 4, 5, 6, 7, 8], workers: 4 })Leave workers out to use all cores but one.
Two brains against each other
import { winRates } from '@v12-engine/engine/testing'
import { meleeBrain } from '@v12-engine/engine/ai'
const duel: Simulation = { rules: { ...melee, brains: [myBrain] }, map: duelMap(), seconds: 1800 }
const seeds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const games = [
...(await simulate({ ...duel, brains: { 1: meleeBrain, 2: myBrain } }, { seeds })),
...(await simulate({ ...duel, brains: { 1: myBrain, 2: meleeBrain } }, { seeds }))
]
winRates(games) // { 'core.melee': { games: 20, wins: 6, losses: 9, draws: 5, rate: 0.3, decided: 0.4 }, 'mygame.brain': { … } }Swapping sides per seed cancels any start advantage. profiles sets how each plays (a difficulty name or an AiProfile).
Test a computer player's decisions
import { brainOf, expectDecision, fairPlay, recordDecisions, thinkOnce, watchComputer, checkComputerSave } from '@v12-engine/engine/testing'
world.computers.seat(ENEMY, { enemyBases: [home], brain: meleeBrain })
const watch = watchComputer(world, ENEMY) // checks the invariants after every think
run(world, 120)
expectDecision(thinkOnce(world, ENEMY), 'defend') // throws with the goal's row in words where it does not run
watch.assert() // throws listing every rule it brokeCheck the view's names against the rules
const game = createGame({ /* … */ checkView: 'throw' }) // a typo in a view fails at once
await game.check() // rules and maps, no view
checkGame({ rules, view }) // the problems as data (GameProblem: where, id, message)Editor
- Play the map in the editor and open the Tuning panel to move sliders; Save writes
tuning.json. - Set up a situation and save it as a scenario; load it in a test with
readScenarioandscenarioWorld(apps/example/tests/scenario.test.ts).
Reference
Helpers (@v12-engine/engine/testing)
| Helper | What it does |
|---|---|
testWorld(rules, { size, players, seed, terrain }) | A world on flat ground (flatTerrain, TEST_PLAYERS) |
order(world, entities, init) | Gives an order as a player would |
run(world, seconds, until?) | Steps the world; returns the ticks run. world.step() for one tick |
checkDeterminism(make, { ticks, from, rules, every }) | Twice and from a save; worldFingerprint, worldHash(world) |
simulate(simulation, { seeds, workers, onGame }) | Many games; playGame(simulation, seed) for one |
winRates(games) | Seats, wins, losses, draws, rate, decided by brain |
Simulation
rules, map, seconds, measure(world), computers (which players), brains (by player: a brain or id, e.g. core.melee), profiles, ai (Partial<AiOptions>), start, until.
Each game returns winner, seconds, ticks, failed, your measures, and computers by player: commandsAMinute, idleArmySeconds, churn, blockedOnMoney, refused, held (AiStats), plus brain, team, won.
Computer-player helpers
| Helper | What it does |
|---|---|
brainOf(world, player) | The brain seated there |
thinkOnce(world, player) | One whole think now; returns the report |
expectDecision(report, goal, { picked? }) | Throws with ai.explain when the goal does (not) run |
watchComputer(world, player, options) | Checks the invariants after every think (observe, assert(), stop()) |
fairPlay(world, player) | The fair-play check alone, and how many commands were refused |
recordDecisions(world) | Every computer's decisions as plain data |
checkComputerSave(make, { from, ticks, rules: game }) | A save at from, loaded, decides the same until ticks |
The invariants (checkBrain, AI_INVARIANTS; limits in AiCheckOptions.limits):
| Invariant | What must hold |
|---|---|
squads | A unit is in one squad at most and held by one goal, rule or module at most |
purse | A think spends no more than it had |
finite | Every score, strength and odds is a finite number |
commands | Every command names its own units, entities it sees and places on the map |
churn | No order is resent to a unit still doing the same kind |
ends | Builders (120 s), squad tasks in one phase (300 s), held money and stuck wants (600 s) end |
With setDebugChecks(true) (debugChecks.ai) every brain checks these after each think.
Determinism notes
saveWorld'sreseat(on unlessfalse) puts the saved world's crowd back as a load does, so the two games stay together; it doubles a save's cost (about 37 ms at 1000 units a side).runReplayreturnsapart(the first tick whose hash differs) and, withcheckpoints,difference:{ tick, path, a, b }.
In the example
apps/example/tests: simulate.test.ts (balance), tunables.test.ts, scenario.test.ts, determinism.test.ts, aiTesting.test.ts, ids.test.ts. The campaign starter's tests/rules.test.ts plays each mission headless. packages/bench/bench/aiMelee.bench.ts and races.bench.ts are larger balance runs (npm run bench -- bench/races.bench.ts).