Skip to content

Economy: resources, supply and races ​

The resources a game is played with, supply, the tech tree, the races a player picks from, and the commands a player's screen sends the rules. The rules around them are in Core engine.

Quick start ​

ts
export const myMode: Rules = {
	// ...
	resources: [
		{ id: 'crystals', name: 'Crystals', start: 200, upkeep: true },
		{ id: 'souls', name: 'Souls', start: 1 }
	],
	currency: 'crystals', // what shop prices, bounties, revives and sales are in; the first resource if left out
	units: [
		{ id: 'crystalNode', kind: 'resource', resource: { id: 'crystals', amount: 5000, slots: 1, entered: true } /* ... */ },
		{ id: 'pylon', supplyGiven: 8 /* ... */ },
		{ id: 'zealot', cost: { crystals: 100 }, supply: 2, requires: ['gateway'] /* ... */ }
	]
}

Players start with 200 crystals and 1 soul, workers gather crystals from the node, a pylon gives 8 supply, and a zealot costs 100 crystals and 2 supply and needs a finished gateway.

Common tasks ​

Set costs and pay from code ​

ts
cost: { crystals: 100, souls: 2 }

A player's resources has the same shape; pay, shortOf, refund and earn work on both.

Change the supply cap ​

ts
settings: { supply: { max: 150, of: (world, unit) => (unit.def.hero ? 0 : unit.def.supply ?? 0) } }

The supplyCap hook ({ player, pool, cap }) changes the cap each tick: a starting amount, an upgrade, your own rule. of is asked of queued units too (QueuedUnit: { def, owner, queued: true }).

Add a second supply pool ​

ts
settings: { supply: { pools: { command: { name: 'Command', max: 3 } } } }
// a unit takes: supply: { command: 1 }; a building gives: supplyGiven: { command: 2 }

Each pool is counted, capped, hooked and refused (supplyBlocked with its pool) like food, kept in player.supplies, and shown on the HUD (ui.resources().supplies).

Workers that gather only one kind ​

ts
{ id: 'ghoul', harvester: { ids: ['lumber'] } }

The canHarvest hook ({ worker, source, allowed, reason }) can still refuse a source.

A building that sits on a resource (a cursed mine) ​

ts
{ id: 'cursedMine', builtOn: 'gold', dropOff: ['gold'], gatherers: 5 }

It goes up over a free resource of that kind, makes it its owner's alone, and workers gather round it and hand in on the spot. The resource stands free again when it is destroyed.

A building that builds itself ​

ts
{ id: 'ziggurat', buildsItself: true }

The builder is free once it is placed.

Tech: requirements, upgrades and morphs ​

ts
{ id: 'knight', requires: ['blacksmith', 'lumbermill'] }    // must stand finished
{ id: 'townhall', upgradesTo: 'keep', trains: ['peasant'] }  // morphs into a keep
{ id: 'keep', provides: ['townhall'] }                        // counts as a town hall for requirements

Research in code: UpgradeDef.apply(world, entity, level) runs on units there when a level finishes and on every unit made while the player has it.

Add a fountain and a marketplace ​

ts
const market = presetMarket({
	rates: [
		{ sell: 'lumber', buy: 'gold', rate: 0.5 },
		{ sell: 'gold', buy: 'lumber', rate: 0.5, hotkey: 'L' }
	],
	cooldown: 2
})
export const rules: Rules = {
	...game,
	units: [...units, presetFountain('healingWaters'), { ...marketplace, abilities: market.map((ability) => ability.id) }],
	abilities: [...abilities, ...market]
}

presetFountain(aura) keeps a passive aura on everyone near it (place it for the neutral player, aura affects: 'all'). Each trade sells amount (100) at rate (exchanged event; counts as resourcesSpent, on: 'trade'). exchange(world, player, sold, bought, amount, rate) does it in code.

Leave rubble and drop loot piles ​

ts
export const rules: Rules = {
	...game,
	packs: [
		remainsPack({
			rubble: (world, dead) => (dead.def.footprint?.w === 3 ? { type: 'rubble-3', amount: 120 } : null),
			piles: (world, dead, killer) => (dead.def.bounty ? { type: 'gold-pile', amount: 25 } : null),
			reach: 0.8
		})
	]
}

Rubble blocks the way until workers gather it. A pile goes to the first unit that walks over it (pileTaken). Types: rubbleType({ id, footprint, kind, amount }), pileType({ id, kind, amount }); a pile's contents are pileOf ({ kind, amount }).

Add races ​

ts
export const myMode: Rules = {
	// ...
	races: [defineRace({ id: 'human', name: 'Human' }), defineRace({ id: 'undead', name: 'Undead', icon: 'skull' })],
	units: [
		{ id: 'footman', race: 'human' /* ... */ },
		{ id: 'ghoul', race: 'undead' /* ... */ },
		{ id: 'goldmine' /* ... */ } // of no race: everyone's
	]
}

A player can make only what is of no race or of theirs. Pick a race when the world is made (PlayerInit.race, createWorldFromMap({ races: { 1: 'undead' } }), random for a seeded draw) or change it later (setRace(world, player, race)). How do I add a race walks through one.

Give a race its own start and rules ​

ts
defineRace({
	id: 'undead',
	name: 'Undead',
	resources: { gold: 900 },
	startingBase: { hall: 'gravehold', workers: { type: 'acolyte', count: 3 }, units: [{ type: 'ghoul', count: 1 }], onMine: 'cursedMine' },
	hooks: undeadHooks // run only for this race's players
})

Add a command of your own ​

ts
import { defineCommand, id } from '@v12-engine/engine'

export const sellTower = defineCommand('sellTower', { tower: id }, (world, player, command) => {
	// `command.tower` is a number here: the fields were checked before this runs
	const tower = world.get(command.tower)
	if (!tower || tower.owner !== player) return
	// ...
})

// in the Rules: commands: [sellTower]; on the player's screen:
session.send(sellTower.make({ tower: 12 }))

Editor ​

  1. Open the Data panel and pick Races (with editable: { races: 'all' }).
  2. Change names, starting resources, and the Start group: hall, worker type, counts, what goes on the mine.
  3. Copy as new makes a race of its own; toggle inherits.hooks and inherits.onStart to keep the original's code.
  4. For a map, fix a player's race or the races offered in Map settings › Players (the editor).

Reference ​

Resources ​

FieldWhat it does
id, nameIts id and name
startWhat each player starts with
upkeepArrives cut by the army's upkeep (economy.upkeep(world, player))

Looks come from the view: GameView.hud.resources (a HUD chip and a minimap colour); a model part shows while a worker carries one (carrying: 'crystals'). The score counts what each player gathered, spent and lost to upkeep (Score).

Gathering ​

  • A worker gathers every kind, or those it names (harvester.ids; gathers(def, kind)). canHarvest(world, worker, source) asks the hook.
  • A tree is worked from its free side; one no one can walk to is given up and not tried again by that order (the last eight, outOfReach).
  • A builder blocked on its way tries once more through the crowd, then is told cannotReachSite.
  • builtOn buildings: resourceAt, resource.under, entity.on (kept in a save). construct refuses help on buildsItself buildings.

Supply ​

SettingWhat it does
supply (unit type)What it takes; a number, or by pool
supplyGiven (building)What it gives when finished
RuleSettings.supply.maxThe most a player can have
RuleSettings.supply.of(world, unit)What a unit takes
RuleSettings.supply.poolsPools of your own
supplyCap hookChanges the cap each tick

Races ​

Field / callWhat it does
race (unit, upgrade)Whose it is; none means everyone's
raceOf(world, player)The race a player plays (neutral players and creeps play none)
setRace(world, player, race)Change it during the game; saved
isAvailable(world, player, kind, id)Whether a player may make it; available hook overrules ({ player, kind, id, race, available }). The screen agrees via own.availability and availableToPlayer
resourcesStarting resources over the game's
startingBaseA classic melee start as data (StartingBaseData), or { spawn(world, player, at) }; spawnStartingBase places either
onStart(world, player)Runs after the start is placed
hooksRun only for events of its players (the event's player, else the owner of its entity, caster, attacker, worker, buyer, hero, producer, source or target); of(event) overrides

In a lobby the server offers a race per seat (seatSettingsOf(game), Random with two or more), unless the game offers its own race setting. The choice reaches makeWorld (context.seats); mapMode hands it to the world (racesOfSeats). A map can fix a player's race (MapPlayer.race; ModeSeat.fixed, ServerSeat.fixed) and list those offered (GameMap.races, CreateWorldOptions.randomRaces). checkRaces refuses a start naming a unit the game has not. Mods add races with game.races.add(...).

The example's melee has two: humans and the Restless (apps/example/src/games/melee/undead.ts), the Restless built from race hooks and a blight system (melee/blight.ts). Tests: apps/example/tests/races.test.ts, undead.test.ts, packages/engine/tests/resources.test.ts, packages/engine/tests/presetBuildings.test.ts.

Commands ​

TopicWhat to know
Fieldsid, ids, number, index, bool, string, point, optional(...), oneOf(...), object({...}): a runtime check and a TypeScript type at once
RejectionsA command that does not match, or names another player's unit or one that never existed (world.made), is refused with commandRejected. On a server each counts against the sender (onCheat)
The senderplayer is stamped by the session, never read from the command
The engine'scoreCommands; give yours the same type to replace one
surrenderPuts the player out (playerSurrendered, playerDefeated) unless beforeSurrender calls it off
pauseUses one of the player's pauses (RuleSettings.talk.pauses.each 3, .seconds 60; pausesLeft(world, player)), unless beforePause refuses or shortens it (pauseAsked)