Skip to content

Grass cookbook: real-world recipes ​

Forty-one things games do with grass and bushes, each a whole file you can paste: wind, fire, putting fire out, hiding, cutting and growing, looks that change in play, and maps. Every block is type-checked against the engine by the docs' tests.

RecipeWhat it uses
Wind and movement
A gust from an explosiongust, a listener on entityDied
A gust on one screen: a dragon flies overclient.gust, onGame
A storm that gets up and dies downworld.setEnvironment with over, a timer
A whirlwind unit that pushes the grass round itgust from a system
Grass that parts and leaves trailsthe look's walked group
A herd of deer that shakes the bushesan event of your own, disturb
Fire
Burn a patch from codeignite
A fire arrowthe foliage effect, act: 'ignite'
A fireball that burns grass and treesdamage, foliage and burn effects
A torch-bearer who lights what he walks throughignite from a system
A lightning storm that lights dry grassa timer, world.rng, foliageAt
A campfire that never spreadsthe foliageIgnite hook
A controlled burn that stops at a sizefoliageIgnited, foliageIgnite, world state
Fire that only runs downwindthe foliageIgnite hook and the map's wind
Fire that hurts, credited to who lit itfire.damage, foliageAt(...).by
Hear a fire go out, and count what burntfoliageBurnt, foliageFireOut
Stopping fire
A water spell that puts fire outact: 'extinguish', extinguish
A rain spell that brings rain for a whileabilityCast, the weather, a timer
A firebreak cut ahead of the frontburningCells, firebreak
A fire brigade that runs to the firea system, burningCells, orders
A river or road that fire does not crossflammable: 0, what never burns
Put every fire out as the game endsstopFire, gameOver
Hiding and ambushes
Tall grass that hides unitsconceals
Grass that only hides small unitsconcealsTaller, heightOf
An ambush that springs when its cover burnsfoliageIgnited, foliageRuined
Rustling gives a hidden unit away to those close byconceal.rustle
A scout who sees into the grassa buff, conceal.seenBy
Cutting, crushing, growing
A mowerruin from a system, ruined
Tanks that crush the wheattrample: 'crush', tramples
A quake that flattens a circleact: 'ruin', how: 'crush'
Grass that grows back after a minuteregrows, grows
A druid who makes a burnt field bloomact: 'regrow', regrow
A farm: harvest wheat, let it grow, count itruin, foliageRuined, earn
Clear grass under a building, and grow it back afterconstructionStarted, entityDied, clearFoliage
Looks that change in play
Seasonsworld.setEnvironment({ bushes }), a timer
A blight that spreads and turns the grass purplesetFoliage from a system, a style's look
A setting that thins the grass on one screena setting, client.foliage(layer).setLook
Day and nightworld.night, the look's tint
A patch that changes as a hero walks inan area, enteredArea, setFoliage
Maps and tools
Paint a meadow from code as the map startsonStart, world.setCells, the world's numbers
Grass wherever the ground is painted greenon, growOnTiles
Ask what grass is at a point, to decidefoliageAt, burningCells

Before you start ​

Every recipe builds on the meadow of the overview: a layer of cells named grass, the foliage pack, and a look for the layer. A few words come back again and again:

  • A cell is one square of the map's grid, one world unit a side. Cell (x, z) has the index z * width + x; the calls take a shape or a list of indices.
  • radius is in cells, from the middle of the shape. A circle of radius 2 is about four cells across.
  • The rules (src/rules.ts, @v12-engine/engine) decide what happens, the same on every machine. The look (src/view.ts, @v12-engine/client) is only what each screen draws.

Where each kind of piece goes:

A recipe exportsRegister it with
A system, a timer, an ability, a buff, a component, an area, an eventgame.system(x), game.timer(x), game.ability(x), game.buff(x), game.component(x), game.area(x), game.event(x)
A listener, a hookcreateGame({ listeners: [x], hooks: [y] })
A pack, a layer of cellsgame.pack(x), game.cellLayer(x)
Code for when the map startsgame.onStart(x)
A lookfoliage(...) in ground.cellLayers of your view
Code for one screenstartApp({ onGame }) in src/main.ts

Code in the rules uses the world's own numbers (world.rng) and exactMath for sines and cosines, never Math.random or Math.sin: every machine in a game must work out the same thing.

Wind and movement ​

A gust from an explosion ​

When a powder keg blows up, a ring of wind bursts out over the grass, on the screen of every player who sees it.

ts
// src/rules.ts
import { defineListener, entityDied, gust } from '@v12-engine/engine'

export const kegBlast = defineListener({
	event: entityDied,
	id: 'mygame.kegBlast',
	run(world, { entity }) {
		if (entity.def.id !== 'powderKeg') return
		// radius is in cells; strength 1 is a gale (at most 3); lasts is in seconds
		// with no `around`, the gust blows outwards from the middle, as a blast does
		gust(world, { x: entity.pos.x, z: entity.pos.z }, { radius: 7, strength: 2, lasts: 0.8 })
		// a gust only bends grass on the screens: it changes nothing of the world and is not saved
	}
})

A gust on one screen: a dragon flies over ​

A dragon sweeps over the player's base as the game opens, a row of gusts along its path. The rules know nothing of it, so it is this screen's alone: client.gust.

ts
// src/main.ts: give it to startApp({ ..., onGame: dragonFlyover })
import type { GameClient } from '@v12-engine/client'

export function dragonFlyover(client: GameClient): () => void {
	let step = 0
	// a gust every fifth of a second, 2 cells further along each time, from west to east
	const timer = setInterval(() => {
		// `around` is the way it blows, in degrees from north, clockwise: 90 is east
		client.gust({ x: 4 + step * 2, z: 20 }, { radius: 4, strength: 1.2, around: 90, lasts: 0.6 })
		if (++step > 20) clearInterval(timer)
	}, 200)
	// what onGame gives back runs as the game ends: stop it if it is still flying
	return () => clearInterval(timer)
}

At most four gusts blow at once on a screen; a new one takes the place of the one nearest its end.

A storm that gets up and dies down ​

The wind rises over ten seconds, blows for half a minute, and falls away again. The fire goes by the same wind.

ts
// src/rules.ts
import { defineTimer, type World } from '@v12-engine/engine'

// what the timer does when it goes off: the wind drops over ten seconds
export const stormEnds = defineTimer({
	id: 'mygame.stormEnds',
	run(world) {
		world.setEnvironment({ wind: { around: 200, strength: 0.15 } }, { over: 10 })
	}
})

export function startStorm(world: World): void {
	// around: where it blows towards, in degrees from north; strength 0 (still) to 1 (a gale)
	// `over` has every screen ease into it: the grass leans further and the waves get bigger as it rises
	world.setEnvironment({ wind: { around: 200, strength: 1, gusts: 0.7 } }, { over: 10 })
	// ten seconds to rise and thirty to blow: then it ends
	world.timers.after(40, stormEnds)
}

Register the timer with game.timer(stormEnds) so a saved game finds its code, and call startStorm(world) from wherever the storm should begin.

A whirlwind unit that pushes the grass round it ​

A gyrocopter, a whirlwind or a dust devil bends the grass under it wherever it goes.

ts
// src/rules.ts
import { gust, type System } from '@v12-engine/engine'

export const rotorWash: System = {
	name: 'mygame.rotorWash',
	// `every` counts ticks: 6 ticks is a fifth of a second at the usual 30 ticks a second
	every: 6,
	update(world) {
		for (const unit of world.units.values()) {
			if (unit.def.id !== 'gyrocopter') continue
			// a short ring outwards from the rotor; each gust lasts a little longer than the gap between them, so they join
			gust(world, { x: unit.pos.x, z: unit.pos.z }, { radius: 3, strength: 0.9, lasts: 0.3 })
		}
	}
}

A screen draws at most four gusts at a time, so this suits a few such units, not a swarm. Each gust is a small message to the players who see it.

Grass that parts and leaves trails ​

Every unit a player sees bends the grass as it goes. With flatten the grass also lies down under feet and rises again a few seconds later: a trail behind anyone who moves.

ts
// src/view.ts: put it in ground.cellLayers.grass
import { foliage, presetFoliage } from '@v12-engine/client'

export const grass = foliage({
	...presetFoliage.tallGrass,
	walked: {
		bend: 1, // how far it bends away from a walker (1 as made)
		radius: 'size', // a bigger unit parts a wider path
		flatten: 0.8, // how far it lies down under feet, 0 to 1
		recover: 6, // seconds to stand up again: the trail closes behind them
		trail: true
	}
})

This is the screen's alone and changes nothing in the game: the grass still hides who stands in it. For trampling the rules see, see Tanks that crush the wheat.

A herd of deer that shakes the bushes ​

Deer are units, so the bushes already shake where they walk. To shake a whole thicket when the herd is startled, the rules send an event of your own and each screen shakes its bushes.

ts
// src/rules.ts: game.event(herdStartled), and the listener in createGame({ listeners })
import { damaged, defineEvent, defineListener } from '@v12-engine/engine'

// 'everyone': every player's screen is told of it, with this plain data
export const herdStartled = defineEvent<{ x: number; z: number }>({ id: 'mygame.herdStartled', replicate: 'everyone' })

export const deerHit = defineListener({
	event: damaged,
	id: 'mygame.deerHit',
	run(world, { target }) {
		if (target.def.id === 'deer') world.events.emit(herdStartled, { x: target.pos.x, z: target.pos.z })
	}
})
ts
// src/main.ts: startApp({ ..., onGame: shakeOnStartle })
import type { GameClient } from '@v12-engine/client'
import { herdStartled } from './rules'

export function shakeOnStartle(client: GameClient): () => void {
	// gives back what stops listening, which runs as the game ends
	return client.on(herdStartled, ({ x, z }: { x: number; z: number }) => {
		const bushes = client.foliage('bush')
		// a few shakes round the spot, as the herd bolts
		for (const [dx, dz] of [[0, 0], [2, 1], [-2, 1], [1, -2]]) bushes?.disturb({ x: x + dx, z: z + dz }, 2)
	})
}

disturb shakes as one running through would (strength 1); it is this screen's alone.

Fire ​

The foliage pack burns a style where its flammable is over 0. A burning cell lights the cells about it, more often downwind, uphill and in dry grass, burns for its style's burns seconds, then is burnt.

Burn a patch from code ​

ts
// src/rules.ts
import { type Entity, ignite, type World } from '@v12-engine/engine'

export function burnTheField(world: World, arsonist?: Entity): number {
	// a rectangle 12 cells wide and 6 deep, its middle at (40, 30); `by` is who lit it, and any fire damage is theirs
	const caught = ignite(world, 'grass', { kind: 'rect', x: 40, z: 30, width: 12, depth: 6 }, { by: arsonist })
	// the cells that caught: none on water, roads, under buildings, or where the style does not burn
	return caught.length
}

A fire arrow ​

No code: the foliage effect sets the grass where the arrow lands alight, lit by the caster.

ts
// src/rules.ts: game.ability(fireArrow), and give it to a unit's `abilities`
import type { AbilityDef } from '@v12-engine/engine'

export const fireArrow: AbilityDef = {
	id: 'fireArrow',
	name: 'Fire Arrow',
	target: 'point',
	range: 9,
	cooldown: 12,
	effects: [
		{ type: 'damage', amount: 40, radius: 1 },
		// a radius of 1.5 cells: about three cells across catch, then the fire spreads by the grass's rules
		{ type: 'foliage', act: 'ignite', radius: 1.5 }
	]
}

A fireball that burns grass and trees ​

One cast hurts who it hits, lights the grass and sets alight the trees there.

ts
// src/rules.ts
import type { AbilityDef } from '@v12-engine/engine'

export const fireball: AbilityDef = {
	id: 'fireball',
	name: 'Fireball',
	target: 'point',
	range: 10,
	cooldown: 20,
	manaCost: 90,
	effects: [
		{ type: 'damage', amount: 120, radius: 2.5 },
		{ type: 'foliage', act: 'ignite', radius: 2.5 }, // the grass, on every layer of the foliage pack
		{ type: 'burn', act: 'light', radius: 2.5 } // trees and huts: needs the burning pack
	]
}

Trees burn with burningPack: see Let trees burn. Burning grass and burning trees can also be set to light each other; that page says how.

A torch-bearer who lights what he walks through ​

ts
// src/rules.ts
import { ignite, type System } from '@v12-engine/engine'

export const torches: System = {
	name: 'mygame.torches',
	every: 10, // a third of a second
	update(world) {
		for (const unit of world.units.values()) {
			if (unit.def.id !== 'torchbearer' || !unit.alive) continue
			// the cell he stands in, and a little round it; already burning or burnt cells are left alone
			ignite(world, 'grass', { kind: 'circle', x: unit.pos.x, z: unit.pos.z, radius: 0.8 }, { by: unit })
		}
	}
}

With fire.damage on the pack he is hurt by his own fire if he stops: keep him walking, or give him a buff that resists it.

A lightning storm that lights dry grass ​

Every twenty seconds a bolt falls on a random cell, and lights it if the grass there is dry. The world's own numbers pick the cell, so every machine picks the same one.

ts
// src/rules.ts: game.timer(lightning), and start it in game.onStart
import { defineTimer, foliageAt, ignite, type World } from '@v12-engine/engine'

export const lightning = defineTimer({
	id: 'mygame.lightning',
	run(world) {
		const { width, depth } = world.terrain
		// world.rng: the same numbers in the same order on every machine and in a replay
		const x = world.rng.int(0, width - 1) + 0.5
		const z = world.rng.int(0, depth - 1) + 0.5
		world.fx('lightning', { at: { x, z } }) // a flash of your view's, where it falls
		const cell = foliageAt(world, 'grass', x, z)
		// only dry grass catches: a style that burns easily, standing whole
		if (cell && (cell.style.flammable ?? 0) >= 0.8 && cell.state === 'whole') ignite(world, 'grass', [cell.cell])
	}
})

export function startLightning(world: World): void {
	// every 20 seconds, 30 times, the first after 20
	world.timers.every(20, lightning, { times: 30 })
}

A campfire that never spreads ​

No grass within three cells of a campfire ever catches, whoever lights it and however the fire comes.

ts
// src/rules.ts: createGame({ hooks: [campfireSafe] })
import { defineHook, foliageIgnite } from '@v12-engine/engine'

export const campfireSafe = defineHook({
	hook: foliageIgnite,
	id: 'mygame.campfireSafe',
	run(world, event) {
		// asked of every cell about to catch: keep it quick
		for (const fire of world.find({ type: 'campfire' })) {
			const dx = fire.pos.x - event.x
			const dz = fire.pos.z - event.z
			// event.x and event.z are the cell's middle, in cells
			if (dx * dx + dz * dz < 3 * 3) return event.cancel()
		}
	}
})

A controlled burn that stops at a size ​

A ranger burns off a field before the enemy can hide in it, and the fire he starts burns no more than 200 cells.

ts
// src/rules.ts: game.component(burnt), listeners: [countBurn], hooks: [capBurn]
import { defineComponent, defineHook, defineListener, foliageIgnite, foliageIgnited } from '@v12-engine/engine'

const LIMIT = 200

// state of the whole game, saved with it: how many cells the ranger's fires have lit
export const burnt = defineComponent<{ cells: number }>({ id: 'mygame.controlledBurn', default: () => ({ cells: 0 }) })

export const countBurn = defineListener({
	event: foliageIgnited,
	id: 'mygame.countBurn',
	run(world, { cells, by }) {
		// `by` is the id of whoever lit the fire these cells caught from
		if (world.get(by)?.def.id === 'ranger') world.state(burnt).cells += cells.length
	}
})

export const capBurn = defineHook({
	hook: foliageIgnite,
	id: 'mygame.capBurn',
	run(world, event) {
		// the cells of his fire that would catch next are refused once the field has had its share
		if (event.by?.def.id === 'ranger' && world.state(burnt).cells >= LIMIT) event.cancel()
	}
})

A fire that has reached its size burns out where it is. For a cap on every fire at once, the pack's fire.maxBurning says how many cells may burn together.

Fire that only runs downwind ​

The pack already makes a fire likelier to go downwind (fire.wind). This hook refuses every try against the wind, so a front runs away from where it started and never back.

ts
// src/rules.ts: hooks: [downwindOnly]
import { defineHook, exactMath, foliageIgnite } from '@v12-engine/engine'

export const downwindOnly = defineHook({
	hook: foliageIgnite,
	id: 'mygame.downwindOnly',
	run(world, event) {
		const wind = world.map.environment?.wind
		// only a spread has a cell it comes from; in still air every way is allowed
		if (event.cause !== 'spread' || event.from === undefined || !wind?.strength) return
		const { width } = world.terrain
		// the way from the burning cell to the one about to catch
		const dx = event.x - ((event.from % width) + 0.5)
		const dz = event.z - (Math.floor(event.from / width) + 0.5)
		// downwind on the map: `around` is degrees from north (-z), clockwise (90 is +x)
		const turn = (wind.around * Math.PI) / 180
		const along = dx * exactMath.sin(turn) - dz * exactMath.cos(turn)
		if (along < 0) event.cancel() // against the wind
	}
})

Fire that hurts, credited to who lit it ​

The pack hurts whoever stands in a burning cell, and the damage is dealt by whoever lit that fire: a kill by fire is theirs. A system of your own can add to it, here more harm to heroes.

ts
// src/rules.ts: game.pack(...) in place of your foliagePack, and game.system(scorchHeroes)
import { foliageAt, foliagePack, type System } from '@v12-engine/engine'

// 8 damage a second to every unit in a burning cell, as magic damage
export const grassPack = foliagePack({ layer: 'grass', fire: { damage: 8, damageType: 'magic' } })

export const scorchHeroes: System = {
	name: 'mygame.scorchHeroes',
	every: 30, // once a second
	update(world) {
		for (const unit of world.units.values()) {
			if (!unit.def.hero || !unit.alive) continue
			const cell = foliageAt(world, 'grass', unit.pos.x, unit.pos.z)
			// `by` is the id of who lit the fire this cell burns of; the extra 12 is theirs too
			if (cell?.burning) world.damage(unit, 12, world.get(cell.by))
		}
	}
}

Hear a fire go out, and count what burnt ​

A score for the arsonist, and a message once the last cell goes out.

ts
// src/rules.ts: game.component(fireTally), listeners: [tallyBurnt, fireIsOut]
import { defineComponent, defineListener, foliageBurnt, foliageFireOut } from '@v12-engine/engine'

export const fireTally = defineComponent<{ burnt: number }>({ id: 'mygame.fireTally', default: () => ({ burnt: 0 }) })

export const tallyBurnt = defineListener({
	event: foliageBurnt,
	id: 'mygame.tallyBurnt',
	run(world, { cells }) {
		// the cells that finished burning this tick, now black
		world.state(fireTally).burnt += cells.length
	}
})

export const fireIsOut = defineListener({
	event: foliageFireOut,
	id: 'mygame.fireIsOut',
	run(world, { layer }) {
		// told when the last burning cell of a layer goes out: burnt out, put out or stopped
		if (layer !== 'grass') return
		const { burnt } = world.state(fireTally)
		for (const player of world.players.values()) world.message(player.id, `The fire is out: ${burnt} cells burnt`, 'info')
	}
})

Stopping fire ​

A water spell that puts fire out ​

The quickest way is data: the foliage effect with act: 'extinguish' puts out what burns where it lands. The same is one call from code, for a well, a bucket or a trigger.

ts
// src/rules.ts: game.ability(waterSplash)
import { type AbilityDef, extinguish, type World } from '@v12-engine/engine'

// no code: cast it on the fire, and every cell burning within 3 cells stops
export const waterSplash: AbilityDef = {
	id: 'waterSplash',
	name: 'Water Splash',
	target: 'point',
	range: 8,
	cooldown: 10,
	manaCost: 40,
	aim: { shape: 'circle', radius: 3 }, // the circle the player sees while aiming
	effects: [{ type: 'foliage', act: 'extinguish', radius: 3 }]
}

// from code: the same, anywhere
export function douse(world: World, x: number, z: number): number {
	// the cells that were burning there: they stop as they are, burnt, and grow back as their style says
	return extinguish(world, 'grass', { kind: 'circle', x, z, radius: 3 }).length
}

Putting fire out does not wet the grass round it: unburnt grass beside the splash can still catch from a front that reaches it. Douse the edge of a fire, or cut a firebreak ahead of it.

A rain spell that brings rain for a while ​

The spell puts the fire out where it lands, and rain falls over the whole map for twenty seconds. Rain damps every fire while it falls, unless the pack says fire: { weather: false }.

ts
// src/rules.ts: game.ability(rainDance), game.timer(rainStops), listeners: [rainFalls]
import { abilityCast, type AbilityDef, defineListener, defineTimer, type MapEnvironment } from '@v12-engine/engine'

export const rainDance: AbilityDef = {
	id: 'rainDance',
	name: 'Rain Dance',
	target: 'point',
	range: 12,
	cooldown: 60,
	effects: [{ type: 'foliage', act: 'extinguish', radius: 6 }]
}

// the timer is told the weather there was before, to put it back
export const rainStops = defineTimer<{ before: MapEnvironment['weather'] }>({
	id: 'mygame.rainStops',
	run(world, { before }) {
		world.setEnvironment({ weather: before }, { over: 6 }) // undefined: no weather, as the map had none
	}
})

export const rainFalls = defineListener({
	event: abilityCast,
	id: 'mygame.rainFalls',
	run(world, { ability }) {
		if (ability.id !== 'rainDance') return
		const before = world.map.environment?.weather
		// the rain comes on over 4 seconds on every screen; the fire in the rules is damped at once
		world.setEnvironment({ weather: { kind: 'rain', amount: 0.9 } }, { over: 4 })
		world.timers.after(20, rainStops, { before })
	}
})

A firebreak cut ahead of the front ​

Find the middle of what burns, look downwind, and cut a line across the wind a few cells ahead. Cut grass does not burn.

ts
// src/rules.ts
import { burningCells, exactMath, firebreak, type Entity, type World } from '@v12-engine/engine'

export function cutAhead(world: World, by?: Entity, ahead = 6): number[] {
	const burning = burningCells(world, 'grass') // the pack's own list: read it, don't keep or change it
	const wind = world.map.environment?.wind
	if (!burning.length || !wind) return []
	const { width, depth } = world.terrain
	// the middle of the fire, in cells
	let x = 0
	let z = 0
	for (const cell of burning) {
		x += (cell % width) + 0.5
		z += Math.floor(cell / width) + 0.5
	}
	x /= burning.length
	z /= burning.length
	// downwind, and across it
	const turn = (wind.around * Math.PI) / 180
	const down = { x: exactMath.sin(turn), z: -exactMath.cos(turn) }
	const cells: number[] = []
	for (let i = -10; i <= 10; i++) {
		// two cells thick: a strong wind with `fire.jump` set can leap a gap of one
		for (const extra of [0, 1]) {
			const cx = Math.floor(x + down.x * (ahead + extra) - down.z * i)
			const cz = Math.floor(z + down.z * (ahead + extra) + down.x * i)
			if (cx >= 0 && cz >= 0 && cx < width && cz < depth) cells.push(cz * width + cx)
		}
	}
	return firebreak(world, 'grass', cells, { by })
}

A fire brigade that runs to the fire ​

Firefighters walk to the nearest burning cell and douse it, and go on to the next while anything burns.

ts
// src/rules.ts: game.system(fireBrigade)
import { burningCells, extinguish, type System } from '@v12-engine/engine'

export const fireBrigade: System = {
	name: 'mygame.fireBrigade',
	every: 15, // twice a second
	update(world) {
		const burning = burningCells(world, 'grass')
		if (!burning.length) return
		const { width } = world.terrain
		for (const unit of world.units.values()) {
			if (unit.def.id !== 'firefighter' || !unit.alive) continue
			// the nearest burning cell's middle
			let best = Infinity
			let target = { x: 0, z: 0 }
			for (const cell of burning) {
				const x = (cell % width) + 0.5
				const z = Math.floor(cell / width) + 0.5
				const d = (x - unit.pos.x) ** 2 + (z - unit.pos.z) ** 2
				if (d < best) [best, target] = [d, { x, z }]
			}
			if (best <= 2 * 2) {
				// close enough: the hose puts out a circle of 2 cells round where he stands
				extinguish(world, 'grass', { kind: 'circle', x: unit.pos.x, z: unit.pos.z, radius: 2 })
			} else if (!unit.orders.length) {
				// idle: walk there. A unit that is walking already keeps its way
				unit.order('move', target)
			}
		}
	}
}

A river or road that fire does not cross ​

Some ground never burns by itself: grass on water, on the road tile, under a building and on cells that block the way. For a line of your own, paint a style that does not burn.

ts
// src/rules.ts
import { defineCellLayer, type GameStart, presetFoliageStyles, setFoliage } from '@v12-engine/engine'

export const grassLayer = defineCellLayer({
	id: 'grass',
	name: 'Grass',
	values: [
		{ value: 1, name: 'Dry grass', foliage: presetFoliageStyles.dryGrass },
		// the same grass to look at, but wet: flammable 0 never catches, so a front stops at it
		{ value: 2, name: 'Wet bank', foliage: { ...presetFoliageStyles.meadow, flammable: 0 } }
	]
})

// game.onStart(wetBanks): a band 3 cells wide along both banks of a river that runs down x = 30
export const wetBanks: GameStart = (world) => {
	setFoliage(world, 'grass', { kind: 'rect', x: 26.5, z: 32, width: 3, depth: 64 }, 2)
	setFoliage(world, 'grass', { kind: 'rect', x: 33.5, z: 32, width: 3, depth: 64 }, 2)
}

Set fire.jump on the pack and a strong wind can carry a fire over a gap of one cell, so make a break two cells or more across.

Put every fire out as the game ends ​

ts
// src/rules.ts: listeners: [fireOutAtEnd]
import { defineListener, gameOver, stopFire } from '@v12-engine/engine'

export const fireOutAtEnd = defineListener({
	event: gameOver,
	id: 'mygame.fireOutAtEnd',
	run(world) {
		// every fire of every layer of the pack: what burns is left burnt, and nothing more catches
		const wasBurning = stopFire(world)
		world.log.info('fire', 'fires put out as the game ended', { cells: wasBurning })
	}
})

The same call ends a mission's burning village once its objective is done.

Hiding and ambushes ​

Tall grass that hides units ​

A unit standing in a style that conceals is hidden from every team with no unit in the same patch and none within two cells.

ts
// src/rules.ts: game.cellLayer(grassLayer), game.pack(grassPack)
import { defineCellLayer, foliagePack, presetFoliageStyles } from '@v12-engine/engine'

export const grassLayer = defineCellLayer({
	id: 'grass',
	name: 'Grass',
	values: [
		{ value: 1, name: 'Meadow', foliage: presetFoliageStyles.meadow }, // hides nobody
		{ value: 2, name: 'Tall grass', foliage: presetFoliageStyles.tallGrass } // conceals: true
	]
})

// reach: how near, in cells, an enemy must be to see in from outside the patch
export const grassPack = foliagePack({ layer: 'grass', conceal: { reach: 2 } })
ts
// src/view.ts: ground.cellLayers.grass
import { foliage, presetFoliage } from '@v12-engine/client'

// value 1 drawn as a meadow, value 2 as tall grass
export const grass = foliage({ ...presetFoliage.meadow, styles: { 2: presetFoliage.tallGrass } })

A patch is a run of touching cells of a hiding style. Grass that is cut, crushed, burning or burnt hides nobody; growing grass hides again.

Grass that only hides small units ​

Waist-high grass hides a wolf, not a giant: with concealsTaller: false, a unit taller than the style's height is seen over it.

ts
// src/rules.ts
import { defineCellLayer, foliagePack, hasTag } from '@v12-engine/engine'

export const grassLayer = defineCellLayer({
	id: 'grass',
	name: 'Grass',
	// height is in cells, to the rules: what a unit's height is measured against
	values: [{ value: 1, name: 'Waist-high grass', foliage: { conceals: true, concealsTaller: false, height: 1.2 } }]
})

export const grassPack = foliagePack({
	layer: 'grass',
	conceal: {
		// how tall a unit stands: twice its radius when left out. Here, what your game tags `large` stands 3 tall
		heightOf: (_world, unit) => (hasTag(unit, ['large']) ? 3 : unit.def.radius * 2)
	}
})

An ambush that springs when its cover burns ​

Bandits wait hidden in the wheat. The moment their cell burns or is cut, they are seen anyway, so they charge.

ts
// src/rules.ts: listeners: [ambushOnFire, ambushOnCut]
import { defineListener, foliageAt, foliageIgnited, foliageRuined, type World } from '@v12-engine/engine'

const VILLAGE = { x: 48, z: 12 } // where they charge

function spring(world: World): void {
	for (const bandit of world.find({ type: 'bandit' })) {
		const cell = foliageAt(world, 'grass', bandit.pos.x, bandit.pos.z)
		// whole or growing grass still hides; anything else (burning, burnt, cut, flattened) does not
		const hidden = cell && (cell.state === 'whole' || cell.state === 'growing')
		if (!hidden) bandit.order('attackMove', VILLAGE) // fight whatever they meet on the way
	}
}

export const ambushOnFire = defineListener({ event: foliageIgnited, id: 'mygame.ambushOnFire', run: (world) => spring(world) })
export const ambushOnCut = defineListener({ event: foliageRuined, id: 'mygame.ambushOnCut', run: (world) => spring(world) })

Rustling gives a hidden unit away to those close by ​

A unit hidden in grass shakes it as it moves. Here only an enemy within six cells sees the grass shake, so a player can tell something is near without seeing what.

ts
// src/rules.ts: game.pack(grassPack)
import { foliagePack } from '@v12-engine/engine'

export const grassPack = foliagePack({
	layer: 'grass',
	conceal: {
		// asked for each team that does not see the hidden unit: true shakes the grass on that team's screens
		rustle: (world, hidden, team) =>
			world.query({ near: hidden, radius: 6, where: (unit) => world.player(unit.owner).team === team, limit: 1 }).length > 0,
		rustleEvery: 0.5 // seconds between shakes while it moves; stepping in is told at once
	}
})

Only where a hidden unit moves is told, never who it is. The rules also hear it as the rustled event.

A scout who sees into the grass ​

For fifteen seconds, the scout's team sees every unit hidden in grass within ten cells of him.

ts
// src/rules.ts: game.buff(keenEye), game.ability(keenEyeCast), game.pack(grassPack)
import { type AbilityDef, type BuffDef, foliagePack, hasBuff } from '@v12-engine/engine'

export const keenEye: BuffDef = { id: 'keenEye', name: 'Keen Eye', duration: 15 }

export const keenEyeCast: AbilityDef = {
	id: 'keenEyeCast',
	name: 'Keen Eye',
	target: 'none',
	cooldown: 40,
	effects: [{ type: 'buff', buff: 'keenEye', on: 'caster' }]
}

export const grassPack = foliagePack({
	layer: 'grass',
	conceal: {
		// asked only of units the grass would otherwise hide from `team`
		seenBy: (world, hidden, team) =>
			world
				.query({ near: hidden, radius: 10, where: (unit) => world.player(unit.owner).team === team && hasBuff(unit, 'keenEye') })
				.some((unit) => unit.alive)
	}
})

Cutting, crushing, growing ​

A mower ​

A mower cuts the grass it drives over to stubble, with mown stripes on the ground. Cut grass hides nobody and does not burn: a mown strip is a firebreak.

ts
// src/rules.ts: game.system(mowing)
import { ruin, type System } from '@v12-engine/engine'

export const mowing: System = {
	name: 'mygame.mowing',
	phase: 'resolve', // after units have moved this tick
	every: 15, // twice a second
	update(world) {
		for (const unit of world.units.values()) {
			if (unit.def.id !== 'mower') continue
			// `by` names who cut it, in the foliageRuined event
			ruin(world, 'grass', { kind: 'circle', x: unit.pos.x, z: unit.pos.z, radius: 1.2 }, { how: 'cut', by: unit })
		}
	}
}
ts
// src/view.ts
import { foliage } from '@v12-engine/client'

// cut grass stands at a tenth of its height, with mown stripes painted under it
export const lawn = foliage({ ruined: { stubble: 0.1, paint: { cut: 'mown' } } })

Tanks that crush the wheat ​

Wheat is laid flat for good under heavy units. Crushed wheat hides nobody until it grows back.

ts
// src/rules.ts
import { defineCellLayer, foliagePack, hasTag, presetFoliageStyles } from '@v12-engine/engine'

export const grassLayer = defineCellLayer({
	id: 'grass',
	name: 'Grass',
	// the wheat preset has trample: 'crush' already; it grows back two minutes after it is crushed
	values: [{ value: 1, name: 'Wheat', foliage: { ...presetFoliageStyles.wheat, regrows: 120 } }]
})

export const grassPack = foliagePack({
	layer: 'grass',
	// who crushes it: every unit that walks when left out. Here only what your game tags `heavy`
	tramples: (_world, unit) => hasTag(unit, ['heavy'])
})

On the screen, any unit bends the wheat as it passes (the look's walked). Only those tramples says crush it to the rules.

A quake that flattens a circle ​

ts
// src/rules.ts
import type { AbilityDef } from '@v12-engine/engine'

export const quake: AbilityDef = {
	id: 'quake',
	name: 'Quake',
	target: 'point',
	range: 8,
	cooldown: 30,
	effects: [
		{ type: 'damage', amount: 80, radius: 4 },
		// lays the grass flat in a circle 4 cells round, about eight across: it hides nobody until it grows back
		{ type: 'foliage', act: 'ruin', how: 'crush', radius: 4 }
	]
}

Grass that grows back after a minute ​

ts
// src/rules.ts
import { defineCellLayer } from '@v12-engine/engine'

export const grassLayer = defineCellLayer({
	id: 'grass',
	name: 'Grass',
	values: [
		{
			value: 1,
			name: 'Meadow',
			// 60 seconds after it is burnt, cut or crushed it starts to grow; 15 seconds later it stands whole.
			// It hides and burns again as soon as it starts growing
			foliage: { flammable: 0.6, regrows: 60, grows: 15 }
		}
	]
})

A druid who makes a burnt field bloom ​

ts
// src/rules.ts
import { type AbilityDef, type Entity, regrow, type World } from '@v12-engine/engine'

// no code: burnt, cut or crushed grass in a circle of 6 cells rises again over 8 seconds
export const bloom: AbilityDef = {
	id: 'bloom',
	name: 'Bloom',
	target: 'point',
	range: 8,
	cooldown: 45,
	effects: [{ type: 'foliage', act: 'regrow', over: 8, radius: 6 }]
}

// from code: the whole map, over 20 seconds, as a spring comes
export function spring(world: World, druid?: Entity): number {
	const { width, depth } = world.terrain
	return regrow(world, 'grass', { kind: 'rect', x: width / 2, z: depth / 2, width, depth }, { over: 20, by: druid }).length
}

A farm: harvest wheat, let it grow, count it ​

Harvesters cut the wheat they walk through; each cell cut is one food for their owner, and the wheat grows back.

ts
// src/rules.ts: game.cellLayer(fields), game.system(harvesting), listeners: [harvest]
import { defineCellLayer, defineListener, earn, foliageRuined, presetFoliageStyles, ruin, type System } from '@v12-engine/engine'

export const fields = defineCellLayer({
	id: 'grass',
	name: 'Grass',
	// regrows: 45 seconds after the harvest it starts to grow again, whole 20 seconds later
	values: [{ value: 1, name: 'Wheat', foliage: { ...presetFoliageStyles.wheat, trample: 'none', regrows: 45, grows: 20 } }]
})

export const harvesting: System = {
	name: 'mygame.harvesting',
	every: 15,
	update(world) {
		for (const unit of world.units.values())
			if (unit.def.id === 'harvester') ruin(world, 'grass', { kind: 'circle', x: unit.pos.x, z: unit.pos.z, radius: 1 }, { how: 'cut', by: unit })
	}
}

export const harvest = defineListener({
	event: foliageRuined,
	id: 'mygame.harvest',
	run(world, { cells, how, by }) {
		const harvester = world.get(by)
		// stubble is not cut again, so a cell counts once until it has grown back
		if (how === 'cut' && harvester?.def.id === 'harvester') earn(world.player(harvester.owner).resources, 'food', cells.length)
	}
})

The game needs a food resource (game.resource({ id: 'food', name: 'Food' })).

Clear grass under a building, and grow it back after ​

On the screen grass keeps off buildings by itself, and grass under a building never burns. To the rules it is still there and still hides; this takes it away as the building goes up, and grows it back from ash once it is destroyed.

ts
// src/rules.ts: listeners: [clearForBuilding, regrowAfterBuilding]
import { clearFoliage, constructionStarted, defineListener, type Entity, entityDied, regrow, ruin, setFoliage } from '@v12-engine/engine'

// the ground a building stands on, and a cell round it
const footprint = (building: Entity) => ({ kind: 'circle' as const, x: building.pos.x, z: building.pos.z, radius: building.def.radius + 1 })

export const clearForBuilding = defineListener({
	event: constructionStarted,
	id: 'mygame.clearForBuilding',
	run(world, building) {
		clearFoliage(world, 'grass', footprint(building)) // value 0: no grass, and nothing grows back by itself
	}
})

export const regrowAfterBuilding = defineListener({
	event: entityDied,
	id: 'mygame.regrowAfterBuilding',
	run(world, { entity }) {
		if (entity.def.kind !== 'building') return
		const area = footprint(entity)
		setFoliage(world, 'grass', area, 1) // meadow again...
		ruin(world, 'grass', area, { how: 'scorch' }) // ...burnt black where the building stood...
		regrow(world, 'grass', area, { over: 60 }) // ...rising out of the ash over a minute
	}
})

Looks that change in play ​

A look changed from the rules is changed for every player: world.setEnvironment({ bushes }), eased in over over seconds and kept in a save. It replaces the map's whole bushes field, so these recipes keep what was there and change only their part.

Seasons ​

Every two minutes the meadow turns: green, gold, brown and frosted, and green again.

ts
// src/rules.ts: game.timer(nextSeason), and in game.onStart: world.timers.every(120, nextSeason, {})
import { defineTimer } from '@v12-engine/engine'

// the tips' colour for each season: red, green, blue, each 0 to 1
const SEASONS: [number, number, number][] = [
	[0.5, 0.76, 0.26], // spring
	[0.82, 0.74, 0.32], // summer: dry gold
	[0.66, 0.42, 0.2], // autumn
	[0.84, 0.88, 0.9] // winter: frost
]

export const nextSeason = defineTimer({
	id: 'mygame.nextSeason',
	run(world) {
		// which season: from the game's time, so a loaded save goes on where it was
		const season = Math.floor(world.time / 120) % SEASONS.length
		const bushes = world.map.environment?.bushes ?? {}
		const grass = bushes.grass || {}
		world.setEnvironment(
			// the grass layer's tips eased to the season's colour on every screen over 30 seconds
			{ bushes: { ...bushes, grass: { ...grass, colors: { ...grass.colors, tip: SEASONS[season] } } } },
			{ over: 30 }
		)
	}
})

A blight that spreads and turns the grass purple ​

Blighted grass is a style of its own, purple and see-through at the tips, and it creeps into the grass beside it.

ts
// src/rules.ts: game.cellLayer(grassLayer), game.system(blightSpreads)
import { defineCellLayer, setFoliage, type System } from '@v12-engine/engine'

export const grassLayer = defineCellLayer({
	id: 'grass',
	name: 'Grass',
	values: [
		{ value: 1, name: 'Meadow', foliage: { flammable: 0.6, regrows: 90 } },
		{ value: 3, name: 'Blight', color: [0.5, 0.2, 0.6], foliage: { flammable: 0, speed: 0.8 } } // slows, never burns
	]
})

export const blightSpreads: System = {
	name: 'mygame.blightSpreads',
	every: 60, // every two seconds
	update(world) {
		const { width, depth, cells } = world.terrain
		const layer = cells.grass
		if (!layer) return
		const next: number[] = []
		// every meadow cell beside a blighted one turns, one time in ten
		for (let z = 1; z < depth - 1; z++)
			for (let x = 1; x < width - 1; x++) {
				const at = z * width + x
				if (layer[at] !== 1) continue
				const touches = layer[at - 1] === 3 || layer[at + 1] === 3 || layer[at - width] === 3 || layer[at + width] === 3
				if (touches && world.rng.next() < 0.1) next.push(at)
			}
		// one call for all of them; a style with `speed` cuts the navigation again where it changed, so not every tick
		if (next.length) setFoliage(world, 'grass', next, 3)
	}
}
ts
// src/view.ts
import { foliage, presetFoliage } from '@v12-engine/client'

export const grass = foliage({
	...presetFoliage.meadow,
	styles: {
		// a fourth number on a colour is how much of it is seen: these tips fade out
		3: { colors: { foot: [0.2, 0.08, 0.25], tip: [0.75, 0.35, 0.95, 0.3], vary: 0.2 }, scatter: [], wind: { sway: 0.4 } }
	}
})

A setting that thins the grass on one screen ​

A player on a slow laptop ticks Thin grass and their screen draws a third of the tufts. Other players and the rules see nothing change. The built-in Tall grass setting (Settings › View) already does this for every layer; this is how to make one of your own.

ts
// src/view.ts: hud: { settings: { add: [thinGrassSetting] } }
import type { GameClient, SettingDef } from '@v12-engine/client'

export const thinGrassSetting: SettingDef = { id: 'mygame.thinGrass', label: 'Thin grass', kind: 'toggle', default: false, section: 'view' }

// src/main.ts: startApp({ ..., onGame: thinGrass })
export function thinGrass(client: GameClient): () => void {
	const apply = (thin: boolean) =>
		// a change on this screen alone, laid over the game's look; it stays until changed again
		client.foliage('grass')?.setLook(thin ? { density: 1.5, levels: { mid: 20, far: 40 } } : { density: 5, levels: { mid: 60, far: 100 } })
	apply(client.settings.get<boolean>('mygame.thinGrass'))
	// told each time the player changes a setting; gives back what stops listening
	return client.settings.onChange((id, value) => {
		if (id === 'mygame.thinGrass') apply(value === true)
	})
}

Day and night ​

At night the grass darkens and turns blue on every screen, and comes back at dawn.

ts
// src/rules.ts: game.component(nightGrass), game.system(nightTint)
import { defineComponent, type System } from '@v12-engine/engine'

// what the grass was last set to, kept in a save
export const nightGrass = defineComponent<{ night: boolean }>({ id: 'mygame.nightGrass', default: () => ({ night: false }) })

export const nightTint: System = {
	name: 'mygame.nightTint',
	every: 150, // every five seconds is plenty: a dusk takes longer than that
	update(world) {
		const state = world.state(nightGrass)
		if (world.night === state.night) return
		state.night = world.night
		const bushes = world.map.environment?.bushes ?? {}
		const grass = bushes.grass || {}
		// `tint` multiplies every colour of the layer, bushes too; white is as made
		const tint: [number, number, number] = world.night ? [0.45, 0.55, 0.85] : [1, 1, 1]
		world.setEnvironment({ bushes: { ...bushes, grass: { ...grass, colors: { ...grass.colors, tint } } } }, { over: 20 })
	}
}

A patch that changes as a hero walks in ​

When a hero steps into the shrine's circle, the grass there turns to blossom.

ts
// src/rules.ts: game.area(shrine), listeners: [shrineBlooms]
import { defineArea, defineListener, enteredArea, setFoliage } from '@v12-engine/engine'

const SHRINE = { kind: 'circle' as const, x: 30, z: 30, radius: 5 }

// an area: the rules tell you who enters and leaves it
export const shrine = defineArea({ id: 'mygame.shrine', shape: SHRINE })

export const shrineBlooms = defineListener({
	event: enteredArea,
	id: 'mygame.shrineBlooms',
	run(world, { area, entity }) {
		if (area !== 'mygame.shrine' || !entity.def.hero) return
		// value 4 must be a style of the layer (a value it lists), with a look under styles[4]
		setFoliage(world, 'grass', SHRINE, 4) // painted again whole: what burnt there is grass again
	}
})

Maps and tools ​

Paint a meadow from code as the map starts ​

A round meadow in the middle, with patches of tall grass scattered by noise. The noise comes from the world's seed, so every machine paints the same field.

ts
// src/rules.ts: game.onStart(paintMeadow)
import type { GameStart } from '@v12-engine/engine'

// a smooth, repeatable noise from 0 to 1: the same cell and seed always give the same number
function noise(x: number, z: number, seed: number): number {
	const hash = (ix: number, iz: number) => {
		let h = (ix * 374761393 + iz * 668265263 + seed * 2246822519) | 0
		h = Math.imul(h ^ (h >>> 13), 1274126177)
		return ((h ^ (h >>> 16)) >>> 0) / 4294967295
	}
	const ix = Math.floor(x)
	const iz = Math.floor(z)
	const fx = x - ix
	const fz = z - iz
	const top = hash(ix, iz) + (hash(ix + 1, iz) - hash(ix, iz)) * fx
	const bottom = hash(ix, iz + 1) + (hash(ix + 1, iz + 1) - hash(ix, iz + 1)) * fx
	return top + (bottom - top) * fz
}

export const paintMeadow: GameStart = (world) => {
	const { width, depth } = world.terrain
	// the meadow: style 1 in a circle filling most of the map
	world.setCells('grass', { kind: 'circle', x: width / 2, z: depth / 2, radius: Math.min(width, depth) * 0.4 }, 1)
	// tall grass (style 2) where the noise is high, in patches about 8 cells across
	const tall: number[] = []
	const layer = world.terrain.cells.grass
	for (let z = 0; z < depth; z++)
		for (let x = 0; x < width; x++) {
			const at = z * width + x
			if (layer?.[at] === 1 && noise(x / 8, z / 8, world.seed) > 0.62) tall.push(at)
		}
	world.setCells('grass', tall, 2)
}

world.setCells paints any layer, unchecked; setFoliage checks the value is a style of the layer and makes the cells whole again.

Grass wherever the ground is painted green ​

The look grows grass on every cell painted with some tiles, and keeps up as the ground is painted. To have the rules see it (to hide and burn), paint those cells into the layer once.

ts
// src/rules.ts: game.onStart(grassFromTiles)
import { type GameStart, growOnTiles } from '@v12-engine/engine'

// every cell painted grass or darkGrass, with no grass of the layer on it yet, becomes style 2
export const grassFromTiles: GameStart = (world) => {
	growOnTiles(world, 'grass', ['grass', 'darkGrass'], 2)
}
ts
// src/view.ts
import { foliage, presetFoliage } from '@v12-engine/client'

// on: the screen grows grass on these tiles. `style: 2` draws it as style 2, the same as the rules see it
export const grass = foliage({ ...presetFoliage.meadow, on: { tiles: ['grass', 'darkGrass'], style: 2 }, styles: { 2: presetFoliage.tallGrass } })

A tile painted later grows grass on the screen at once, but nothing to the rules until growOnTiles is called again.

Ask what grass is at a point, to decide ​

Sheep run from fire, and a scripted scout picks a place to hide. foliageAt tells what is at a point; burningCells what burns now.

ts
// src/rules.ts: game.system(sheepFlee)
import { burningCells, foliageAt, type System, type Vec2, type World } from '@v12-engine/engine'

// whether a point hides who stands there now: a style that conceals, standing whole or growing back
export function hidesAt(world: World, at: Vec2): boolean {
	const cell = foliageAt(world, 'grass', at.x, at.z)
	return !!cell?.style.conceals && (cell.state === 'whole' || cell.state === 'growing')
}

// the nearest hiding place within `radius` cells of a point, or none
export function nearestCover(world: World, from: Vec2, radius = 10): Vec2 | undefined {
	for (let r = 0; r <= radius; r++)
		for (let dz = -r; dz <= r; dz++)
			for (let dx = -r; dx <= r; dx++) {
				const at = { x: from.x + dx, z: from.z + dz }
				if (hidesAt(world, at)) return at
			}
	return undefined
}

export const sheepFlee: System = {
	name: 'mygame.sheepFlee',
	every: 15,
	update(world) {
		const burning = new Set(burningCells(world, 'grass'))
		if (!burning.size) return
		for (const sheep of world.find({ type: 'sheep' })) {
			const here = foliageAt(world, 'grass', sheep.pos.x, sheep.pos.z)
			// on fire, or beside it: run 8 cells the other way from the burning cell next to it
			const near = here && [here.cell, here.cell + 1, here.cell - 1, here.cell + world.terrain.width, here.cell - world.terrain.width].find((cell) => burning.has(cell))
			if (near === undefined) continue
			const fx = (near % world.terrain.width) + 0.5
			const fz = Math.floor(near / world.terrain.width) + 0.5
			sheep.order('move', { x: sheep.pos.x + Math.sign(sheep.pos.x - fx) * 8, z: sheep.pos.z + Math.sign(sheep.pos.z - fz) * 8 })
		}
	}
}

These read the world itself, so they belong in your rules: systems, orders, creeps and scripted units. A computer player sees through its own eyes, as a player does: see Make the computer play.