Skip to content

Add a system ​

A system runs every tick, or once every so many ticks, over the world. List it in your rules' systems.

ts
// in src/rules.ts
import { defineIds, type Rules, type System } from '@v12-engine/engine'

export const UNIT = defineIds('scout')

/** Rain of frogs: every twenty seconds, every player's units lose a little health, and the count is kept */
const frogs: System = {
	name: 'mygame.frogs',
	phase: 'resolve',
	every: 20 * 30, // ticks: 30 a second
	update(world) {
		for (const entity of world.units.values()) if (entity.def.kind === 'unit') world.damage(entity, 5)
		rained++
	},
	save: () => ({ rained }),
	restore: (_world, data) => {
		rained = (data as { rained: number }).rained
	}
}
let rained = 0

export const rules: Rules = {
	id: 'my-game',
	name: 'My game',
	units: [{ id: UNIT.scout, name: 'Scout', kind: 'unit', radius: 0.4, sight: 10, stats: { health: 100, moveSpeed: 5 } }],
	systems: [frogs],
	victory: null
}

Done: every 20 seconds every unit loses 5 health, and the count survives a save.

Run it only over some entities ​

Give over a component, and each runs for every entity that has it, in id order:

ts
import { defineComponent, type System } from '@v12-engine/engine'

/** Burning: health lost each second, until it runs out */
export const burning = defineComponent<{ left: number }>({ id: 'mygame.burning' })

export const burns: System = {
	name: 'mygame.burns',
	phase: 'resolve',
	over: burning,
	each(world, entity, dt) {
		const fire = entity.get(burning)!
		if (!entity.alive) return
		world.damage(entity, 4 * dt)
		fire.left -= dt
		if (fire.left <= 0) entity.remove(burning)
	}
}

over: 'units' (or nothing) runs each for every unit; a function picks the units. If there's an update too, it runs first, once a tick.

Replace one of the engine's systems ​

Leave it out by name and add your own:

ts
withoutSystems: ['supply'],
systems: [mySupply]

The core systems are abilities, areas, combat, construction, corpses, fog, forms, life, movement, orders, production, sequences, supply, timers, transports, victory. victory takes coreVictory(), objectiveVictory, your own system, or null.

Reference ​

FieldWhat it does
nameIts unique name.
phasecommands, decide, move, resolve or cleanup, run in that order a tick.
everyRun once every so many ticks (30 a second) instead of every tick. offset staggers two.
before, afterSystems it runs before or after.
updateRuns once a tick (or every every).
over, eachRun each for every entity that has a component.
save, restoreKeep its state through a save. Not needed without state.

A module-level variable is shared by every world in the process (a test, a server of many games). Keep state in a component or world.states instead. For a change at one moment rather than every tick, use a hook.