Skip to content

AI build orders and production ​

Tell a computer what you want built or trained, and its build plan works out the rest: the steps through the tech tree, the spot, the builder and the money.

Quick start ​

ts
world.computers.seat(2, {
	settings: {
		plans: {
			order: ['farm', 'barracks', { type: 'footman', count: 4 }], // followed first, then it plays on its own
			build: { wants: [{ id: 'flyers', type: 'gryphon', count: 4 }] } // it builds the keep, lumber mill and aviary on the way
		}
	}
})

Player 2 builds a farm, a barracks and four footmen, then keeps four gryphons alive for the rest of the game, building whatever gryphons need.

Common tasks ​

Want something when a condition holds ​

ts
wants: [{ id: 'outpost', type: 'tower', count: 1, near: 'the ford', when: { time: { after: 300 } } }]

near is a point, the name of an entity, or a function. when is a condition.

Want something from a rule ​

ts
import { build, defineBrain, placements, rules, when } from '@v12-engine/engine/ai'

export const turtle = defineBrain({
	id: 'mygame.turtle',
	modules: [
		rules([
			when({ underAttack: true })
				.once()
				.do((ai) => ai.plans.want({ type: 'tower', count: 3, priority: 50, by: 'the first raid' }))
		]),
		build()
	],
	settings: {
		plans: {
			build: {
				wants: [
					{ id: 'flyers', type: 'gryphon', count: 4 },
					{ id: 'outpost', type: 'tower', count: 1, near: 'the ford', when: { time: { after: 300 } } }
				],
				// where each kind goes, by type or by role: a name, or a function
				placement: {
					barracks: 'cluster',
					farm: 'behind',
					tower: (ai, type, site) => {
						const ford = ai.view.named('the ford')
						return ford && ai.view.canPlace(type.id, ford) ? { x: ford.x, z: ford.z } : placements.nearHome(ai, type, site)
					}
				}
			}
		}
	}
})

ai.plans.drop(id) takes a want out again.

Choose where buildings go ​

ts
settings: { plans: { build: { placement: { tower: 'atEdge', farm: 'behind', ziggurat: 'onLayer:blight' } } } }

See the placement table. A type can also declare it (UnitTypeDef.ai.placement).

Set the army mix ​

ts
settings: { plans: { production: { composition: { footman: 2, rifleman: 1 }, counters: 0.5 } } }

Shares by type id or tag ({ ranged: 1, melee: 1 }). It still leans towards what counters the enemy units it has seen; counters: 0 trains the mix whatever it sees.

Choose what it researches ​

ts
settings: { plans: { production: { research: ['ironSwords', 'plating'], researchSpare: 300 } } }

Workers and expansions ​

ts
world.computers.seat(2, {
	settings: { economy: { workersPer: (ai, base, index) => ({ gold: index === 0 ? 6 : 4 }), expandWhen: { time: { after: 180 } } } }
})

Defend the base ​

ts
world.computers.seat(2, { settings: { defence: { odds: 0.8, towers: 2, recall: false } } })

Turn off repairing or rebuilding ​

ts
settings: { plans: { build: { repair: false, rebuild: false } } }

Reference ​

Want (Want) ​

Set with ai.plans.want(want) or plans.build.wants in any settings layer.

FieldWhat it does
idIts name, for drop, the report and the save
typeA unit or building type
countHow many to have (those on their way count); a number or a function of the brain
whenA condition to wait for
near, withinWhere (point, entity name or function) and how far from there
placementHow its spot is chosen (overrides the type's and the brain's)
priorityHow important it is
spareMoney to keep after it: a luxury that never saves up
keepOnce met, rebuilt when lost (rebuild: false to not rebuild)
byWho wants it, for the report

A want of a unit gets its buildings from the build plan and is trained by the production plan. ai.plans.build.list(), get(id) and status(id) read the wants.

The tech path ​

techPath(view, type) reads requires (must stand finished), trains and builds (who makes what), upgradesTo (morphs) and provides (a keep counts as a town hall) and gives the steps in order (TechStep: build, morph, train). requires is all-of; there is no either-or. A cycle in your definitions is refused with a message naming it (TechPath.cycle); what nothing can make is impossible.

Each think (the build() module runs ai.plans.build.think()), every want whose condition holds is advanced by its first possible step, most important first. A builder is the idle worker first, then the one carrying least, then the nearest.

The purse ​

ai.purse (Purse, also view.me.purse) is the one money ledger, rebuilt each think: the player's resources, less what builders on their way will pay (promised), less what is held (reserve(id, cost, priority)). What is left is free. Everything that spends goes through spend(cost, priority) and affords(cost, spare, priority), so the same gold is never spent twice. The most important want it cannot pay for holds its price; anyone less important waits, anyone more important may spend it. The report shows it (PurseReport).

Placements ​

PlacementStrategy is a function (ai, type, site) => point | undefined. The named ones (PlacementName):

NameWhere
nearHomeRings around home, keeping the way to the mine clear (the default)
byResourceOn the nearest deposit it is built on (a cursed mine)
atEdgeAt the edge of the base facing the enemy
behindAway from the enemy
cluster, cluster:<type>Beside another of its type, or of the type named
onLayer:<layer>Where the whole footprint is on a painted layer (onLayer:blight)

Which applies, first that says: the want's, the type's UnitTypeDef.ai.placement, the brain's table by type then role (BuildPlanOptions.placement, the seat's AiOptions.placement over it), the role's default (tower at the edge, supply behind, a topper on its deposit), then the rings. Every placement asks view.canPlace, which says no on unexplored ground: a worker is sent to look first. A want with no spot for siteTimeout seconds (60) is given up. rings(ai, type, centre, options), placements and enemyDirection(ai, from) help you write your own.

The production plan ​

ai.plans.production (ProductionPlan, the production() module, after build()).

OptionDefaultWhat it does
compositioneven sharesThe army it wants, by type id or tag (Composition)
counters1How much counters to seen enemies pull the mix
queue2Units queued at each building
supplyAheadonWants another supply building before it runs out (production.supply, priority 90)
supplyMargin4Free supply kept beyond the next unit
upkeepTier1 (UPKEEP_TIER)Trains no further into upkeep than this tier; false ignores upkeep
upkeepSpare600 (UPKEEP_SPARE)With this much free, upkeep is ignored
researchmost-usedUpgrade ids in order, or a function; left out, the upgrade most of its units benefit from
researchSpare200Money kept after research

Each soldier type gets an urge, target × (1 + counters × (counter − 1)) − share (CompositionReport), and the most urgent is trained. A type that cannot hit what the enemy fields is not trained. train(building, type) and research(building, upgrade, spare) queue directly; trainable(), wanted() and nextResearch() read what it would do.

The build order ​

plans.order is followed first: the first item not had is a want at priority 1000, and ai.plans.following is true meanwhile, holding back the brain's own wants. Counts of a type add up along it. Once every item is had, the order is done for good.

Repair ​

repair (on by default): a worker is sent to a damaged building no enemy reaches, one a think, when the purse has the cost (RuleSettings.economy.repairCost).

Economy (economy settings) ​

OptionDefaultWhat it does
workers8Workers on the money at each base
lumberjacks3Workers on the other resource at home
workersPerBy resource, or a function of the base (overrides the two above)
saturateonNo more than the deposits serve (a mine: slots × (1 + walk / gather))
trainWorkersonHalls train workers up to what the bases want
expansionsHalls to build past the first, by a free mine a worker can reach
expandWhen4 min and a barracksWhen to expand (a condition)
workersFleeonRaided workers run to a safe base and come back after 5 s clear

Defence (defence settings) ​

OptionDefaultWhat it does
radius16 (defendRadius)Rival units this near a building are intruders (creeps never are)
odds2/3Odds the defending squad must reach; the nearest free fighters first
recallonA raid more than home can meet calls the attack wave home
quiet15Seconds clear before a raid is over
towerAfter2Raids on a base before it wants towers there
towers1Towers wanted at such a base (the cheapest tower its workers build)

The melee player's build ​

The melee brain's construction is wants on this plan (melee.build, a ladder as data: MELEE_LADDER). Priorities: hall 100, barracks 80, altar 60, the building its best counter needs 50, another hall 40 (once the home mine is under 35%, expandAt), a hero's price held at 35, workshop 30, next hall tier 20, second barracks 10. meleeBuild({ ladder }) gives a ladder of your own.

What a save keeps ​

Standing wants' memory, wants added as plain data during the game, and which want was saving up (BrainMemory.areas.plans). A want with code in it (a count or when function) must come from the brain's definition, or use keep, to survive a load.