Skip to content

Script a computer player ​

Give a computer rules ("when the hero nears the camp, attack"), build a mission's enemy out of ready parts, or write a brain of your own from modules and goals.

Quick start ​

ts
import { meleeBrain, when } from '@v12-engine/engine/ai'

// the melee brain with two rules of the mission's, and no scouting: it knows where everything is
const redHand = meleeBrain.with({
	id: 'mygame.redHand',
	rules: [
		when({ units: { role: 'hero', of: 'enemy', near: 'camp hall', within: 30 } })
			.once()
			.named('the hero nears')
			.do({ say: 'attack', data: { at: 'camp hall' } }),
		when({ underAttack: { near: 'camp hall', reach: 8 } })
			.every(10)
			.do({ say: 'defend', data: { at: 'camp hall' } })
	],
	without: ['scouting']
})

List the brain in Rules.brains and seat it (world.computers.seat(ENEMY, { brain: redHand })). It plays a normal melee game, attacks the camp hall once a hero comes near, and defends it when hit.

Common tasks ​

Tell a computer what to do ​

ts
world.computers.tell(ENEMY, 'attack', { at: 'the ford', seconds: 60 })
WordDataWhat it does
attack{ at?, seconds? }The army attacks there (else the nearest rival building it knows, else enemyBases[0]); 60 s
defend{ at?, seconds? }The army fights there (home if left out); 30 s
retreat{ seconds? }The army comes home, fighting nothing on the way; 15 s
hold{ seconds? }The army stands where it is; 30 s
pauseThe brain sits still until told resume
resumePlays again

at is a point, or the name of an entity or region. Words of your own are read by your modules (ai.told(word), ai.takeTold(word)) or rules (when.told(word)).

A computer for a mission ​

ts
import { ambush, fleeWhen, guard, holdPosition, missionBrain, patrol, surrenderWhen, waveFrom, when } from '@v12-engine/engine/ai'

export const redHand = missionBrain({
	id: 'campaign.redHand',
	modules: [
		holdPosition('camp hall', { radius: 14, units: { type: 'grunt' } }),
		guard('camp hall', { units: { type: 'axethrower' } }),
		patrol(['ford west', 'ford east'], { units: { named: ['watch 1', 'watch 2'] } }),
		ambush('far bank', { then: { say: 'attack' }, once: true }),
		waveFrom('war pit', { group: { grunt: 3, axethrower: 1 }, every: 90 }),
		fleeWhen({ units: { role: 'hero', max: 0 } }, { to: 'camp hall' }),
		surrenderWhen({ units: { type: 'grunt', max: 0 } })
	],
	rules: [
		when({ units: { role: 'hero', of: 'enemy', near: 'camp hall', within: 30 } })
			.once()
			.do({ say: 'attack' })
	]
})

A mission brain builds, trains and gathers nothing unless you add the kit's module for it (economy(), scouting(), defence()). See the parts.

A rule that does code ​

ts
when({ resource: { id: 'gold', min: 500 } })
	.every(30)
	.do((ai) => ai.plans.want({ type: 'tower', count: 2 }))

Write your own module ​

ts
import { defineBrain, type AiModule } from '@v12-engine/engine/ai'

// a module: one named part of a think, made for each brain so that two seats never share state
const holdTheCamp = (radius: number) => (): AiModule => ({
	id: 'camp.hold',
	think(ai) {
		const camp = ai.view.named('camp')
		const foes = camp ? ai.view.enemies.near(camp, radius) : ai.view.enemies
		const first = foes.first()
		if (first)
			ai.send({ type: 'order', entities: [...ai.view.mine.fighters().ids()], order: { type: 'attackMove', point: { x: first.x, z: first.z } } })
	}
})

export const campGuard = defineBrain({ id: 'campaign.campGuard', modules: [holdTheCamp(20)], every: 1 })

ai.view is what the seat sees this think (see the view). Commands land next tick.

Add a goal: something it may choose to do ​

ts
import { consider, curve, defineGoal, meleeBrain } from '@v12-engine/engine/ai'

// a raid on the enemy's workers when my army is idle and their base is lightly held
const raid = defineGoal({
	id: 'mygame.raid',
	scope: 'army',
	// each consideration gives 0..1; the score is their product, times the weight
	considerations: [
		consider('idle army', (ai) => ai.goals.pool().fighters().idle().strength() / Math.max(1, ai.view.mine.fighters().strength()), curve.linear()),
		consider('workers seen', (ai) => ai.knowledge.enemy.workersSeen(90).length, curve.saturate(6)),
		consider('their base held', (ai) => ai.threat.at(ai.knowledge.enemy.bases()[0]?.at).enemy, curve.inverse(300))
	],
	claims: { units: (ai, available) => available.fighters().idle().items.slice(0, 6) },
	commitment: 20, // seconds it keeps its units once picked
	run: (ai, claimed) => {
		if (!claimed.first) return // send orders once, then let the squad watch them
		const { at } = ai.knowledge.enemy.workersSeen(90)[0]
		ai.squads.make('raid', claimed.units).attack(at, { avoid: 'army' })
	}
})

export const raiding = meleeBrain.with({ id: 'mygame.raiding', goals: [raid] })

The brain scores every goal each think and gives units to the best ones. See the picker.

Squads and tasks ​

ts
ai.squads
	.make('raid', units, { reinforce: true })
	.gather(ai.view.named('rally')!, { minForces: 0.8, seconds: 20, then: { kind: 'harass', data: { at: ai.options.enemyBases![0] } } })

A squad is a named group with one task, watched every think: it regroups when strung out, falls back home when the odds drop under retreatAt (0.3), and refills from idle units with reinforce. See tasks.

Micro: focus fire, kiting, potions ​

ts
import { defineBrain, micro, squads } from '@v12-engine/engine/ai'

const raiders = defineBrain({
	id: 'mygame.raiders',
	modules: [squads(), micro()],
	settings: {
		micro: {
			targets: [
				{ match: 'worker', weight: 5 },
				{ match: 'healer', weight: 2 },
				{ match: 'hero', weight: 1, when: { time: { after: 600 } } }
			],
			unitsFlee: 0.2,
			heroesFlee: false,
			shopping: [{ item: 'healingPotion' }, { item: 'boots', when: { resource: { id: 'gold', min: 500 } } }],
			heroes: [
				{ type: 'paladin', skills: ['stomp', 'holyLight', 'stomp', 'devotionAura'] },
				{ type: 'archmage', chance: 0.5 }
			]
		}
	}
})

Tell the AI how to cast your ability ​

Give the ability an ai function (AbilityDef.ai), or the brain a spells entry: spells: { holyLight: (ai, caster, foes, friends, level) => aim }. Otherwise the kit reads the effects: a heal on the most hurt friend, harm on the nearest foe, an area where it catches a few.

Tell the AI what a unit is for ​

ts
{ id: 'ghoul', ai: { role: ['gatherer', 'soldier'], counters: ['air'], priority: 1.5 } }

Roles are inferred from the definition; declare them where the guess is wrong (UnitTypeDef.ai: { role, tags, counters, priority, strength, placement }).

See why it did that ​

  • Debug panel (🐞 or Alt+Shift+D) › Entities › the computer's player › AI tab: goals as bars (hover for considerations), decisions, squads, plans, knowledge, economy, timings.
  • In code: ai.report() (AiReport), ai.explain(goal) as a sentence, ai.decisions (the last fifty, also logged under category ai at debug).

Test a brain ​

thinkOnce, expectDecision, watchComputer, fairPlay, recordDecisions and checkComputerSave (@v12-engine/engine/testing) test one brain in a world; simulate and winRates play brains against each other. See Testing your rules.

Reference ​

defineBrain ​

defineBrain({ id, modules, every, settings, goals, rules, conditions, knowledge, snapshot, strength, picking }). every is seconds between thinks (or a function of the options). brain.with({ goals, rules, modules, without, settings, … }) gives a variant: goals, rules and modules added, without drops modules by id, the rest replaces. The melee brain's modules are listed in the reference.

Module (AiModule) ​

FieldWhat it does
idIts name; another module finds it with ai.module(id) or a key (moduleKey<T>(id))
think(ai)Its work each think
phasehear, sense, plan, decide, act or fight; left out, the phase of the module before
before, afterOrder within a phase, by id
everyThinks, offsetRun every N thinks
save, restore, version, migrateWhat it remembers in a save
inspectIts section of the report
disposeLet go of what it holds outside the brain

A module that keeps state is a function returning the module, so two seats never share it.

Rules (when) ​

when(condition).do(action) fires as the condition turns true (not every think it stays true). once() fires only the first time; every(seconds) fires again while it holds; priority(n) checks it earlier; named(id) names it in the log and report. The action is (ai, data) => void or { say: word, data }. when.told(word) fires once per time the word is told. A brain of your own lists rules([...]) then words() among its modules. A save remembers what fired, so a once rule never fires twice.

Who may move a unit: a rule that orders units takes them first, ai.goals.take(ids, 'told', { id: 'rule:ambush', seconds: 20 }), until the time is up or ai.goals.release('rule:ambush'). Goals claim, rules take from goals, the defence takes from both, micro never retasks.

Conditions ​

Plain data (or (ai) => boolean), shared with build plans, waves and a map's mission rules. evaluate(condition, ai) asks one. A range is { min?, max? }.

ConditionTrue when
{ all: [...] }, { any: [...] }, { not: c }All hold (true for none); at least one; the other does not
{ resource: { id, min?, max? } }It has that much of the resource
{ units: { type?, role?, tag?, of?, near?, within?, finished?, known?, min?, max? } }So many units (of: mine, enemy in sight, ally; known adds remembered buildings) near a name, point or region (within 16); at least one with no bound
{ supply: { free?, used?, cap? } }Its supply is in the ranges
{ time: { after?, before? } }Seconds into the game
{ underAttack: true }, { underAttack: { seconds?, near?, reach? } }Its units were hit in the last seconds (5), near a place (reach 16)
{ seen: { type?, role?, within? } }A rival unit of that type or role was seen within the seconds (ever if left out)
{ difficulty: 'hard' }, { difficulty: ['easy', 'hard'] }It plays on that difficulty (normal when none)
{ told: word }The word was told and not yet taken
{ chance: 0.3 }This often, by the brain's own seeded numbers
{ hero: { type?, alive?, level? } }One of its heroes matches
{ wave: { min?, max? } }It has sent so many attacks
{ objective: { id, status } }Its objective is open, done or failed (or one of a list)
{ report: { path, equals?, min?, max? } }The value at the path of Rules.report ('waves.next')
{ component: { id, entity?, type?, path?, equals?, min?, max? } }A replicated component's value on a named entity, or its first of a type
{ region: { name, of?, type?, role?, min?, max? } }So many units in the named region
{ is: id, args? }Your own condition (Rules.ai.conditions, or BrainDef.conditions) says yes

An unknown form or is is false, and logged once.

Mission parts ​

missionBrain({ id, modules, rules, … }) runs rules, words, your parts, goals, squads and micro. Each part puts one goal on the picker (id mission.<part>:<place>, or its id).

PartWhat its units do
holdPosition(place, { radius })Hold the place: fight what comes within radius (a region's size, else 10), go back after
patrol(points)Walk a round of places, fighting what they meet
guard(entity, { radius })Stay by an entity (by name or id), fight what comes near (radius 12); let go once it is gone
ambush(place, { radius, trigger, then, once })Wait, then spring when a rival comes within radius (or trigger holds). then: return (default), stay, or an action
waveFrom(place, { group, every, minForces, first, target })Gather what spawns there and send it as a wave when group is whole (4 if left out) or every every seconds; trains nothing
fleeWhen(condition, { to })While it holds, run to to (else home); urgent, takes units from any part
surrenderWhen(condition)Give up once it holds

Every part also takes units (data { named, type, role, tag, near, within, count } or (ai, available) => units; left out, the fighters at its place), when (lets go while false), weight (1) and refill (take units that come later). Units are taken once and remembered by id; a word that borrowed them gives them back. packages/engine/tests/aiMission.test.ts has three missions written this way.

Goal (defineGoal) ​

FieldDefaultWhat it does
idIts name
scopearmy, economy, squad, hero, or your own word; groups the report
considerationsconsider(name, read, curve); the score is their product × weight
weight1What it is worth at its best
claimsunits: (ai, available) => units, money
commitment5Seconds it keeps its claim once picked
margin0.15How much more another must score to take over during commitment
urgentBreaks a commitment the moment it scores more
cooldownSeconds before it may be picked again after it lost its units
run(ai, claimed)Each think it holds its claim; claimed.first on the first
stop(ai, why, claimed)Told why: beaten, urgent, done, told, removed

Curves: curve.linear(max), saturate(k) (0.63 at k), inverse(k) (½ at k), step(at), band(low, high), custom(fn). A 0 vetoes the goal, and later considerations are not asked, so put cheap ones first. Cache expensive work with ai.cache(key, compute).

Squad tasks ​

TaskDone when / notes
attack(point | entity, { avoid, then })cleared with nothing left to fight; lost when the target is gone; avoid: 'army' goes round their army and towers
attackMove(point)As attack, without the regroup
defend(point, radius)Never over by itself
hold(point?)Stands and fights what comes in reach
move(point)arrived
escort(entity)lost when it dies
harass(point)Round their army, workers first
scout(points)Each place looked at once
gather(point, { minForces, seconds, then })Waits for a share or the time, then then
retreat(to?)retreated; home if left out
creep(camp)Until the camp is cleared
patrol(points)Never over by itself
drop(point, transports, { then })Carried by transports to land it cannot walk to; landed

Any task takes then, the task after. Squad options (SquadOptions, or settings.squads): regroupWhen (0.4), spread, retreatAt (0.3, false fights to the last), home (20), reinforce (off), micro (false leaves the units alone).

Your own task: defineTask<Data, Memory>({ id, start, think, done?, where?, handles?, fighting? }), then squad.task(MY_TASK, data). List it in settings.squads.tasks so a loaded game resumes it. Inside a task, squad.order(order, units?), squad.fight(at, units?, target?), squad.idleUnits(), mayResend() and squad.finish(done). The kit's tasks are keys too: ATTACK, DEFEND_TASK, HOLD, MOVE, ESCORT, HARASS, SCOUT_TASK, GATHER, RETREAT, CREEP, PATROL, CAPTURE.

Who owns a squad: one a goal makes (claimed.squad(name, units, options)) is disbanded when the goal stops; one a rule or module makes (make(name, units, { owner })) holds its units until disbanded. A unit is in one squad at a time. Read them with ai.squads.named(name), all(), idle(), of(owner), squadOf(unit), pool().

Micro options (MicroOptions, settings.micro) ​

OptionDefaultWhat it does
targetscasters, healers 2; heroes 1.5; siege 1Ranked TargetRules (match a role, building, a tag or a type; weight; when), or a TargetPicker
targetHeroesonHeroes weigh more as targets
focusEvery4Seconds between picking a new target
kite'ranged'Ranged units step back from melee; false for none
unitsFlee, heroesFlee0.25, 0.35Health share at which a unit leaves the fight to heal
returnAt0.8Health share at which it comes back
removeInjuries, ignoreInjuredSend the hurt home between fights; never send them
spellsAim per ability, or false to cast nothing
potions, takeItems, buyItems, shoppingDrink under 45% health or 25% mana; pick up items; buy ShoppingItems at a shop within 60
hireUnits, hiringHire HiringItems at a tavern within 60
smartArtillerySiege shoots buildings, stays behind the squad
heroesHeroPlans: which hero next (chance), skills per level, items