Skip to content

Test my rules ​

Your rules run with no page. Make a world with testWorld, spawn and order units, run seconds of game time, and check. The empty starter has tests/rules.test.ts on Vitest.

ts
// in tests/rules.test.ts
import { createWorldFromMap } from '@v12-engine/engine'
import { run, simulate, testWorld, winRates } from '@v12-engine/engine/testing'
import { describe, expect, it } from 'vitest'
import { mapNamed } from '../src/maps'
import { rules, onStart, UNIT } from '../src/rules'

describe('the rules', () => {
	it('give each player with a start a scout, at it', async () => {
		const map = mapNamed()
		const world = await createWorldFromMap({ map, rules, seed: 1 })
		onStart(world, { map })
		const scouts = [...world.units.values()].filter((entity) => entity.def.id === UNIT.scout)
		expect(scouts).toHaveLength(map.players.length)
		world.dispose()
	})

	it('send a scout where it is ordered', async () => {
		const world = await testWorld(rules)
		const scout = world.spawn(UNIT.scout, { at: { x: 10, z: 10 }, owner: 1 })
		scout.order('move', { x: 30, z: 10 })
		// seconds of game time, tick by tick, until the test says so or the time is up
		run(world, 20, () => scout.pos.x > 29)
		expect(scout.pos.x).toBeGreaterThan(29)
		world.dispose()
	})

	it('are fair from every start: four computers, eight games, no start past 60% of the wins', async () => {
		const games = await simulate({ rules: rules, map: mapNamed(), computers: [1, 2, 3, 4] }, { seeds: [1, 2, 3, 4, 5, 6, 7, 8] })
		const rates = winRates(games)
		for (const result of Object.values(rates)) expect(result.rate).toBeLessThanOrEqual(0.6)
	}, 120_000)
})

Done: npm test runs it. The same seed gives the same game, so a failure repeats every time.

Reference ​

CallWhat it does
testWorld(game, { size, players, seed })A flat world with test players.
createWorldFromMap({ map, rules, seed })A world on one of your maps.
run(world, seconds, until?)Steps the world, stopping early when until returns true.
order(…)Issues an order as a player's screen would.
thinkOnce(world, player)One think of a computer player.
simulate(game, { seeds })Plays whole games with computers at the seats, in worker threads if asked.
winRates(games)Win rates by start and by brain.
fixtureGame(), fixtureMap()A small ready game (worker, hall, barracks, soldier, archer, tower, hero, mine, creep…, 1000 gold and lumber) and a 64-cell two-start map, for testing your own pack, hook or order.

See Testing and balancing rules for benchmarks and replays as tests.