AI reference
How a brain thinks, what it can read, and the engine's three brains in detail. For the API of each name, see the API reference.
A think
Once every every seconds the brain takes one snapshot of its seat (ai.snapshot), reads it into its view (ai.view), updates its knowledge, and runs its modules phase by phase: hear (words, rules), sense (raids, team), plan (economy, building, training), decide (goals), act (picker, waves, squads), fight (micro). Commands it sends (ai.send, counted in ai.sent) land next tick, so a think never sees its own orders.
import { defineBrain, type AiModule } from '@v12-engine/engine/ai'
// a module in the `sense` phase that writes a line to the decision log each think
const countUnits = (): AiModule => ({ id: 'mygame.count', phase: 'sense', think: (ai) => ai.decide(`${ai.view.mine.length} units`) })
export const counter = defineBrain({ id: 'mygame.counter', modules: [countUnits] })The think budget
Without a budget a think runs in one tick. AiOptions.budget (over the profile's budget; ThinkBudgetOptions) spreads it: modulesPerTick and unitsPerTick. The budget counts work, never milliseconds, so the same seed always gives the same game. A module that walks many units reports with ai.budget.spent(n) and, where out of room, calls ai.budget.later() to continue next tick. warnAfterMs (4) only logs a slow module. AiReport.budget shows how a think was sliced.
Memory and saves
A brain's memory is plain data (save: { v, rng, thinks, told, modules }), each module's under its id with its version. A module's migrate(data, from) updates an old memory; a module with no memory starts fresh. A think in progress when the game was saved is kept too (BrainMemory.areas.thinking) and replayed on load without resending commands.
Areas
Shared state beyond knowledge, goals, plans, squads and purse is an area (AiArea): the kit's Micro, Economy, Defence, Scouting, Team and Waves (ai.area(Economy)), or your own:
const diplomacy = defineArea({ id: 'mygame.diplomacy', make: (ai) => new Diplomacy(ai) })
ai.area(diplomacy)An area has remembers, save, restore and reportTo. Type its memory with declare module '@v12-engine/engine/ai' { interface AreaMemories { … } }.
The lean picture
A computer gets a snapshot cut to what a brain reads: entities, players, items on the ground, and the events deaths, damage, healing, pings, chat, command answers and the game's own (COMPUTER_EVENTS). A brain that needs the rest says defineBrain({ snapshot: 'full' }).
Cost
On a 256-cell map, 12 computers take about a tenth of a 0.6 ms tick (0.17 ms a think on average). Take your picture once a think (ai.snapshot), never again from the session. The Stats window (📊) shows each computer's time under the systems; seat.timing() gives it in code.
The view
ai.view (AiView) is the snapshot read once per think.
const { view } = ai
view.mine.workers().idle() // my workers with nothing to do
view.enemies.near(view.home()!, 20).fighters() // what is attacking home
view.enemies.known().buildings().nearest(from) // the nearest enemy building I know of, seen or remembered
view.resources.ofResource('gold').nearest(base.at) // the nearest gold mine
view.mine.withRole('hall').finished() // my halls that stand
view.typesOf('barracks')[0] // the barracks of my race, the first the game listsSets (UnitSet): mine, allies, enemies, hostile (enemies and creeps), creeps, neutral, resources, all. They read like arrays (length, for..of, map, filter, find, some, every, forEach, first(), at(i), items) and chain: ofType(id), withRole(role), withTag(tag), fighters(), workers(), heroes(), buildings(), units(), finished(), idle(), visible(), alive(), ofResource(kind), ofOwner(player), where(predicate), near(point, radius), nearest(point), centre(), ids(), has(id), and(other), strength(). map and filter give arrays; where gives a set.
In sight vs remembered. enemies is what is in sight now. enemies.known() adds enemy buildings seen before (visible: false), which may be gone. A unit out of sight is absent; ask the knowledge where their army was.
The player is view.me: resources, supply, upgrades, research, tech, heroes, objectives, income (view.me.income), the purse. It is updated during a think (a train bumps supplyUsed) so later modules don't overspend.
Places: view.home(), view.bases() (each with centre, at, buildings), view.resourcesNear(base), view.mines(), view.camps(), view.regions, view.inRegion(name, point), view.named(name), view.canPlace, view.findPath, view.cellAt, view.cells, view.lanes().
From the game: view.report (Rules.report), view.component(entity, myComponent), view.events.of('death'), view.events.game(myEvent), view.me.objectives, view.me.unlocks.
Roles
The kit knows roles, not types: worker, gatherer, topper (built on a deposit, a cursed mine), hall, supply, barracks, altar, workshop, tower, shop, soldier, hero, caster, healer, siege, air, scout, detector, plus your own words. They are inferred from definitions (inferRoles; view.roles.explain(type) says why). Declare them where the guess is wrong with UnitTypeDef.ai: { role, tags, counters, priority }; a declared role replaces the inferred ones, declared tags join the kit's (ranged, melee, hitsAir). AiOptions.roles replaces the whole table. view.typesOf(role) is what this player can make, in the game's order.
Knowledge
ai.knowledge (Knowledge) is what the brain remembers between thinks, from what its seat saw only. It is kept in a save.
const { enemy, map, own, events } = ai.knowledge
enemy.bases() // their bases as remembered: owner, at, first and last seen (ticks), structures, hall, gone, expansion
enemy.armySeen(30) // groups of their fighters seen in the last 30 seconds, newest first: at, tick, count, types, health
enemy.workersSeen(90)[0]?.at // where a worker of theirs was last seen
enemy.techSeen() // types seen, what they require, and what trains them: a gryphon means an aviary
map.sinceLooked({ x: 120, z: 40 }) // seconds since a place was in sight: Infinity for never
own.lostNear(view.home()!, 20, 60) // what of mine died near home in the last minute: a raid
own.income('gold') // gathered a minute, of late
events.pings(5) // pings heard in the last five seconds| Part | What it holds |
|---|---|
enemy | structures() ({ gone: true } adds destroyed ones), bases(), expansionsSeen(), armySeen(), workersSeen(), heroes, mostSeen(type), techSeen(), sawType |
map | lastLooked(point), sinceLooked, inSight, explored, mines(), look |
own | lost, lostNear, attackSent(at, count), attacks, gathered, history, income(kind, seconds) |
events | pings, damage, deaths since the last think |
Army sightings and workers last armyFor (180 s); losses, events, attacks and gone buildings keepFor (300 s). Set them with defineBrain({ knowledge: { armyFor, keepFor, mergeRadius, historyEvery, limits, army } }), or knowledge: false for a brain that remembers nothing. knowledge.forget(olderThan) forgets on demand; knowledge.data is the plain KnowledgeMemory.
Strength and the threat map
const { strength, threat } = ai.view
strength.of(unit) // by its stats and the health it has left; 0 for what does not fight
strength.of('gryphon') // a type, at full health
view.mine.fighters().strength() // a group: the strength of each, summed
strength.odds(view.mine.fighters(), view.enemies.fighters()) // 0..1: the chance of winning, an estimate
strength.odds(view.mine.fighters(), sighting.types) // against an army the knowledge saw: types with counts
strength.counterFor(seen, view.typesOf('soldier')) // what answers them best, the best first
threat.at(expansion.at) // { friendly, enemy, net }: the strength that reaches a place
threat.at(point, { layer: 'air', remembered: true }) // what reaches the air there, their towers seen before counted
threat.hot()[0] // the cell where the enemy is strongest among what is mine: where the raid is- Strength (
defaultStrength):sqrt(toughness × offence) × hero. Toughness is health left raised by armour or magic resist; offence is damage a second, a little more for reach and speed; heroes count more per level. A seen unit's own stats (upgrades, items, buffs) count. Replace it withAiOptions.strengthorBrainDef.strength, or declareUnitTypeDef.ai.strength. - Odds: Lanchester's square law,
A² / (A² + B²), with each unit read against the other side's armour and what it can hit. Declared counters (UnitTypeDef.ai.counters: ['air', { target: 'siege', weight: 1 }]) weigh in. It is an estimate: it ignores spells, terrain and focus fire. Against fought-out matchups of melee's units it is within 0.12; check your own units withpackages/bench/bench/odds.bench.ts. - Counters:
counterFor(enemies, candidates)ranks types: 1 is average, 0 cannot hit them, above 1 is the answer. - The threat map (
ai.threat,ThreatMap): a grid of 8-unit cells holding friendly and enemy strength that can reach each cell, on two layers (ground,air).at(point),around(point, radius),hot(),cells(). Built from what is in sight;{ remembered: true }adds remembered towers.
Goals and the picker
ai.goals.think() (the goals() module) scores every goal, takes them best first, and gives each the units it claims from the pool (ai.goals.pool()) and the money it names (held in the purse), until nothing scores above min (0.05). Several goals run at once on different units. A goal that claims units and gets none is skipped (why: 'nothing to claim').
- Commitment: a picked goal keeps its claim for
commitment(5 s) unless another beats it bymargin(0.15); anurgentgoal breaks it at once. - Who holds a unit:
ai.goals.holder(unit); rules and modules take units withai.goals.take(units, why, by?), read withtaken(),ruled(id),release(id). - Changing goals live:
ai.goals.add(goal),remove(id). - Reading it:
ai.goals.report(),best,scores. - Defaults:
BrainDef.picking(min,margin,commitment). Goals of the brain's definition survive a load; goals in the seat's options (AiOptions.goals) do not.
The report
ai.report() (AiReport) is plain data: brain, player, tick, thinks, profile, the running goal, every goal with each consideration's raw value and curved value, knowledge, roles, economy, plans and purse, squads, words not yet taken, last commands, the last fifty decisions, and each module's sections. In inspect(world, { player }) it is Inspection.ai with timing. ai.decide(line, { kind, goal }) writes a decision; ai.explain(goal) gives a goal's row as a sentence. The decision log is kept in a save (BrainMemory.areas.decisions).
The debug panel's AI tab shows the report where the session has the debug tools. The renderer draws no overlay of it on the map (squads, the threat map, remembered bases) yet.
The melee brain
meleeBrain plays a melee from your definitions alone. Its modules, in order:
| Module | What it does |
|---|---|
rules, words | Its rules (meleeBrain.with({ rules })), and the words attack, defend, retreat, hold, pause |
defence, team | Counts raids and reads the team's board |
economy | Workers, base by base |
melee.heroes | Revives a fallen hero, trains the next; its price held at priority 35 |
melee.build | Its build ladder (MELEE_LADDER, meleeBuild({ ladder })) |
melee.production | Composition, counters, supply, research |
melee.army | The army's goals (Attack waves) |
melee.surrender | Gives up when it cannot come back (settings.army.surrender) |
goals | The picker |
scouting, waves, squads, micro | As described on the other pages |
meleeBrain.with({ without: ['melee.heroes', 'scouting'] }) drops modules. meleeArmyOf(ai) reads its army (MeleeArmy). A save made with the older melee player (legacy) is read into it.
The lanes brain
lanesBrain plays heroes in a game of lanes: rules, words, team, lanes, goals, squads, micro. It commands its heroes only; minions walk the lanes on their own. It reads lanes from its seat (GameSession.lanes, view.lanes(), LaneSide, onLane(lane, at), laneAt(lane, along)).
import { lanesBrain, lanesBrainOf } from '@v12-engine/engine/ai'
world.computers.seat(2, { brain: lanesBrain })
export const careful = lanesBrainOf({ id: 'mygame.careful', lanes: { backAt: 0.5, help: { reach: 40 }, camps: false } })| Goal | Score | What its hero does |
|---|---|---|
lanes.push:<lane> | 1 | Walks behind (3) cells behind its side's front; never under an enemy tower without its minions; falls back below backOdds (0.3). One hero a lane |
lanes.back | 10, urgent | Under backAt (0.35) health, goes home (a recall ability where safe) and rests to returnAt (0.85) or restFor (40 s) |
lanes.help | 1.3 | Joins an ally's hero fighting within help.reach (30) at odds help.odds (0.4) or better |
lanes.camp | 0.6 | With no wave on any lane, takes the nearest camp it can beat within camps.reach (50) |
Its heroes last-hit minions (lastHits: false to stop), then hit heroes not under a tower, then buildings (lanesTargets). Every number is LanesPlayOptions (settings.lanes). The example's lanes game is apps/example/src/games/lanes, played by tests/aiLanes.test.ts.
A computer player from nothing
The kit is optional. Anything with think (and save, restore, inspect) is a ComputerPlayer:
createComputerSystem(world, player, (session, context) => new MyComputer(session, options), { every: 1 })It plays through the session it is handed, under its fog. context has a seed, the budget and whether the world profiles. Pass snapshot: 'lean' for the lean picture. To seat it with world.computers.seat, on a server and from a save, list it as a brain: defineComputer(id, make) in Rules.brains.