Skip to content

AI for missions and campaigns ​

A campaign's enemies don't play a fair melee game. A base sits where the map put it and sends waves on a schedule; a camp holds its ground; a patrol walks the road; an ambush waits in the woods; a boss keeps his guard by him; an ally defends its town. Each is a computer seat with a brain made for the mission, and the mission's script tells it when the story moves.

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

// a classic campaign enemy base: builds and trains from what the map gave it, never expands, never scouts
// (it is told where the player is), never surrenders, and attacks on the mission's schedule
export const bloodfangBase = meleeBrain.with({
	id: 'ford.bloodfangBase',
	without: ['scouting'],
	settings: {
		economy: { expansions: 0 },
		army: { surrender: false, raid: false, harass: false, creep: false },
		waves: {
			waves: [
				{ group: { grunt: 4 }, after: 240 },
				{ group: { grunt: 4, axethrower: 2 }, after: 180 },
				{ group: { grunt: 6, axethrower: 2, catapult: 1 }, after: 150, repeat: true }
			]
		}
	}
})

List it in Rules.brains, and seat it as the mission starts: world.computers.seat(ENEMY, { brain: bloodfangBase, enemyBases: [world.map.point('hall')] }). Four minutes in, four grunts come for the player's hall; three minutes later a bigger wave; then the biggest, again and again. Between waves it rebuilds what it lost.

Two kinds of mission enemy ​

KindMade withIt…
A basemeleeBrain.with({ … })gathers, builds, trains, rebuilds, defends and attacks; you tune when and with what
Placed forcesmissionBrain({ modules })builds and trains nothing: holds, guards, patrols, ambushes, sends what spawns

A mission can have both on one seat (a base, plus a patrol of its own units), or several seats (an enemy base, a neutral fort that turns hostile, an ally). Every brain a game seats goes in Rules.brains, so a save finds it by its id.

Common tasks ​

Attack on the mission's schedule ​

ts
settings: {
	waves: {
		groups: [{ id: 'raiders', units: { wolfRider: 4 } }],
		waves: [
			{ group: 'raiders', after: 300, target: 'weakestBase' },
			{ group: { grunt: 6, shaman: 2 }, after: 120, repeat: true, gatherFor: 20, rally: 'war camp' }
		]
	}
}

after counts from the wave before (from the start for the first). Scripted waves replace the melee brain's own attacks. target: nearestBase (default), weakestBase, expansion, army, a point or a name. See Attack waves.

Waves that grow with each one sent ​

ts
waves: { waves: (ai, index) => ({ group: { grunt: 3 + index, catapult: index >= 3 ? 1 : 0 }, after: 120 }) }

Waves only on harder difficulties ​

ts
waves: [
	{ group: { grunt: 4 }, after: 240 },
	{ group: { grunt: 2, knight: 2 }, after: 60, when: { difficulty: ['hard', 'insane'] } } // skipped on easy and normal
]

Hold the attack until the story says so ​

A classic enemy waits until the player reaches a point, or a timer runs out. Pause the seat and resume it from the mission:

ts
world.computers.seat(ENEMY, { brain: bloodfangBase, enemyBases: [world.map.point('hall')] })
world.computers.pause(ENEMY) // sits still, kept in a save

defineSequence({ id: 'ford.theyNotice', steps: [
	waitFor(enteredArea, (_world, { area, entity }) => area === 'ford.bridge' && entity.owner === PLAYER),
	...talk(PLAYER, [{ speaker: 'scout', text: 'line.theyAreComing', seconds: 4 }]),
	(world) => world.computers.resume(ENEMY)
] })

While paused it gathers and builds nothing either. To let it build up while its army waits, start its first wave late (after), and send it early when the story says: world.computers.tell(ENEMY, 'attack', { at: 'hall' }). A wave whose when does not hold as its turn comes is skipped, not held.

Tell the enemy what to do from the script ​

ts
world.computers.tell(ENEMY, 'attack', { at: 'hall', seconds: 90 }) // everything at the hall, now
world.computers.tell(ENEMY, 'defend', { at: 'citadel' }) // come home: the citadel is hit
world.computers.tell(ENEMY, 'retreat') // fall back (the boss fell, the horn sounded)
world.computers.tell(ENEMY, 'hold', { seconds: 60 })

Words of your own reach the brain's rules: when.told('horn').do(…). See Script a computer player.

A camp that holds its ground ​

ts
import { guard, holdPosition, missionBrain, patrol } from '@v12-engine/engine/ai'

export const trollCamp = missionBrain({
	id: 'ford.trollCamp',
	modules: [
		holdPosition('troll camp', { radius: 14 }), // fights what comes in, goes back after
		guard('chieftain', { units: { type: 'trollGuard' } }), // his guard stays by him
		patrol(['ford west', 'ford east'], { units: { named: ['watch 1', 'watch 2'] } }) // two walk the ford
	]
})

A mission brain builds, trains and gathers nothing: it plays what the map placed. Places are the map's names: a region, a point, or a named unit.

Reinforcements the mission spawns ​

The script spawns; the brain sends what arrives.

ts
const fromThePit = missionBrain({ id: 'ford.pit', modules: [holdPosition('camp'), waveFrom('pit', { group: { grunt: 3, axethrower: 1 }, every: 90, first: 180 })] })

const reinforce = defineTimer({ id: 'ford.reinforce', run: (world) => {
	const pit = world.map.point('pit')
	for (const type of ['grunt', 'grunt', 'grunt', 'axethrower']) world.spawn(type, ENEMY, pit)
} })
world.timers.every(90, reinforce, { first: 120 })

waveFrom sends a group once it is whole, or every every seconds with what is there. Stop the timer when the camp falls (world.timers.cancel(id)), and the waves stop with it.

Ambushes on the road ​

ts
missionBrain({
	id: 'ford.woods',
	modules: [
		ambush('dark woods', { radius: 10, then: 'stay', units: { type: 'shadowStalker' } }), // springs when a rival comes within 10
		ambush('old bridge', { trigger: { told: 'caravanAtBridge' }, then: { say: 'attack', data: { at: 'caravan' } }, once: true })
	]
})

A mission's sequence can spring the second one: world.computers.tell(ENEMY, 'caravanAtBridge').

A boss and his guard ​

ts
missionBrain({
	id: 'm.warlord',
	modules: [
		holdPosition('throne room', { units: { named: ['warlord'] } }),
		guard('warlord', { radius: 8, units: { named: ['guard1', 'guard2', 'guard3'] } }),
		fleeWhen({ units: { type: 'warlord', max: 0 } }, { to: 'gate' }), // the guards run once he falls
		surrenderWhen({ units: { type: 'trollGuard', max: 0 } })
	],
	settings: { micro: { targets: [{ match: 'hero', weight: 3 }], heroesFlee: false } } // he goes for the hero, and never runs
})

The boss casts his spells by the kit's guess of each (a heal on the hurt, harm on the nearest foe), or as AbilityDef.ai says. See Micro.

A boss with a brain all of its own is one module: the examples' Black Dragon (showcase-dragon: src/examples/showcase/dragon/brain.ts of the examples starter, apps/examples here) plays a dragon that keeps its distance, picks who to shoot and when to cast each ability, and points its summons at their prey, with switches and dials the player changes from the example's card while it fights (tuning.ts: a component on the dragon, changed by a command, read by the brain with view.component).

An ally that fights beside the player ​

ts
world.sides.setRelation(PLAYER, TOWN, 'ally')
world.computers.seat(TOWN, {
	brain: meleeBrain,
	settings: { team: { defendUsers: true, answerPings: true }, army: { surrender: false }, economy: { expansions: 0 } }
})

It builds and fights as a melee player, comes to the player's help when called, and answers the player's pings (push, hold, retreat). For an ally that only holds its town, seat a mission brain with holdPosition('town').

Neutral units that turn hostile ​

A fort that was neutral, and takes up arms when the player attacks the shrine:

ts
defineListener({
	id: 'm.betrayal',
	event: entityDied,
	run(world, { entity }) {
		if (world.nameOf(entity) !== 'shrine') return
		for (const unit of world.find({ owner: world.neutral, area: 'm.fort' })) world.setOwner(unit, ENEMY)
		world.computers.tell(ENEMY, 'attack', { at: 'hall' })
	}
})

A part with refill: true takes in units that come to its seat later. Or give the fort its own player and turn it: world.sides.setRelation(PLAYER, FORT, 'enemy').

Keep the enemy still in a cinematic ​

A cinematic played with hold: true holds the whole game, computers included. For a talk played without it, pause the seat for its length: world.computers.pause(ENEMY), then resume.

One difficulty for the whole campaign ​

The campaign's difficulty (chosen in its menu, CampaignDef.difficulties) reaches each mission as MissionContext.difficulty. Seat with it, and change the mission itself as you like:

ts
defineCampaign({
	…,
	difficulties: ['easy', 'normal', 'hard'],
	missions: [
		{
			id: 'ford',
			name: 'The Ford',
			map: () => fordMap,
			onStart: (world, { fresh, difficulty }) => {
				if (!fresh) return
				world.computers.defaults = { difficulty } // every seat of this mission
				world.computers.seat(ENEMY, { brain: bloodfangBase, enemyBases: [world.map.point('hall')] })
				if (difficulty === 'hard') world.spawn('ogre', ENEMY, world.map.point('camp'))
				if (difficulty === 'easy') world.player(ENEMY).resources.gold = 0
			}
		}
	]
})

The difficulty also changes how the brain plays: how often it thinks, how soon its army goes, how well it fights (Difficulty and personality). A difficulty of your own: Rules.ai.difficulties.

The same enemy, across missions ​

Make one brain, and vary it per mission with .with:

ts
export const bloodfang = meleeBrain.with({ id: 'campaign.bloodfang', without: ['scouting'], settings: { army: { surrender: false } } })
export const bloodfangAtTheFord = bloodfang.with({ id: 'campaign.bloodfang.ford', settings: { waves: { waves: fordWaves } } })
export const bloodfangAtTheGate = bloodfang.with({ id: 'campaign.bloodfang.gate', settings: { waves: { waves: gateWaves } } })

export const rules: Rules = { ...game, brains: [bloodfang, bloodfangAtTheFord, bloodfangAtTheGate, trollCamp] }

Each needs its own id, since a save remembers a seat by it. A brain's id the game no longer lists leaves the seat empty when an old save loads.

On the map, without code ​

A map's computer player can carry its own profile: MapPlayer.data.ai (difficulty, personality, settings, brain), waves included (settings.waves). The editor's Rules panel can tell a computer a word ({ tell: { computer, word } }), which its brain's rules hear.

See why it did that ​

Open the debug panel (🐞 or Alt+Shift+D), pick the computer's player under Entities, and open the AI tab: its goals, its squads, its waves and the next one's time, its decisions. Show on the map draws its squads and where it thinks you are. See Script a computer player: debugging.

Test a mission's enemy ​

ts
import { thinkOnce, watchComputer } from '@v12-engine/engine/testing'

thinkOnce runs one think of a brain in a world you made; watchComputer follows a seat over time; checkComputerSave checks it survives a save. See Testing your rules.

Reference ​

What a mission script does to a computer ​

CallWhat it does
world.computers.seat(player, { brain, enemyBases, difficulty, settings })Seats it; kept in the world and its saves
world.computers.pause(player), resumeStill, then playing again
world.computers.tell(player, word, data)attack, defend, retreat, hold, pause, resume, or a word of yours
world.computers.unseat(player)No more computer on that seat
world.computers.defaultsDifficulty and personality every later seat takes
world.sides.setRelation(a, b, how)ally, enemy, neutral
world.setOwner(entity, player)A unit changes sides

Settings worth changing for a mission base ​

SettingFor
without: ['scouting']It needs no scout: tell it where the player is (enemyBases)
economy: { expansions: 0 }It stays in the base the map gave it
army: { surrender: false }It plays to the last
army: { raid: false, harass: false, creep: false }Only the waves you wrote
wavesWhen it attacks, with what, where
plans: { order: [...] }What it builds first (Build plans)
defence: { towers, radius }How it defends its base
micro: { targets, heroesFlee }How its units fight

Mission parts (missionBrain) ​

holdPosition, guard, patrol, ambush, waveFrom, fleeWhen, surrenderWhen: each takes units (who), when (while), weight and refill. Every field: Script a computer player: mission parts.