Change how something behaves
There are seven ways to change what a game does. Try them in this order and stop at the first that does the job: the earlier ones are less code, show in the editor, and reload as you save.
Which one do I need?
| You want | Use | Where it goes |
|---|---|---|
| Another number, name or list: more health, a longer cooldown | A data value | The definition, settings, or a data file |
| An ability that does something else, made of what the engine can do | The engine's effects | AbilityDef.effects |
| One definition's number or choice worked out in code | A callback of the definition | A function field of the definition |
| To change or stop something as it happens, for everything | A hook | Rules.hooks |
| To do something once it has happened | A listener | Rules.listeners |
| Something that goes on every tick, or a new thing a unit can be told | A system or an order | Rules.systems, Rules.orders |
| To change a game that is not yours, or ship a change apart from it | A mod | composeGame |
Before any of them, look at the packs: heroes, stances, capture and burning are a line in packs. To take a rule of the engine's out, leave it out by name (Turn one of the engine's rules off).
The examples below are one game: an archer whose Frost arrow gets a little more of its own at each step.
1. A data value
Most of what a unit, ability, buff or item does is a field of its definition. The rules that are about no one unit (the supply cap, how long a corpse lies) are settings.
// in src/rules.ts
import { defineIds, type Rules } from '@v12-engine/engine'
export const UNIT = defineIds('archer')
export const ABILITY = defineIds('frostArrow')
export const rules: Rules = {
id: 'my-game',
name: 'My game',
units: [
{
id: UNIT.archer,
name: 'Archer',
kind: 'unit',
radius: 0.4,
sight: 9,
// she shoots too short: 6 becomes 8
stats: { health: 80, moveSpeed: 4, mana: 60, attackDamage: 12, attackSpeed: 1.2, attackRange: 8 },
attacks: [{ acquisitionRange: 9, damagePoint: 0.4, projectileSpeed: 20 }],
abilities: [ABILITY.frostArrow]
}
],
abilities: [
{ id: ABILITY.frostArrow, name: 'Frost arrow', target: 'unit', range: 7, manaCost: 20, cooldown: 5, effects: [{ type: 'damage', amount: 40 }] }
],
// a rule of the whole game: armies of 150 supply at most
settings: { supply: { max: 150 } },
// what the editor's Data panel may change, kept in data.json
editable: { units: 'all', abilities: 'all' },
victory: null
}Done: archers reach 8 cells and armies stop at 150 supply.
The same value can be kept out of the code, in a file the editor writes. In data.json, laid over the rules with layData(rules, dataFile):
{ "units": { "archer": { "stats": { "attackRange": 8 } } } }- Right when the engine already has a field for it. Look first:
UnitTypeDef,AbilityDef,BuffDefandRuleSettingshave more fields than you expect (targetableBy,spellImmune,corpse,drops). - Not when the value depends on what is going on in the game. That is a callback (step 3) or a hook (step 4).
- Which file: your code for what the game is;
data.jsonfor numbers a designer tunes in the editor;pack.jsonfor content shipped apart from the game. Which layer wins is below.
See Add a unit type and Mods and content packs.
2. The engine's effects in an ability
What an ability does is a list of effects, each a type and its fields: damage, heal, buff, missile, spawn, blink and many more. Put them together before you write code.
import type { AbilityDef, BuffDef } from '@v12-engine/engine'
/** A third slower for three seconds */
export const chilled: BuffDef = { id: 'chilled', name: 'Chilled', harmful: true, duration: 3, percent: { moveSpeed: -0.3 } }
/** An arrow that flies to its target, hurts it and chills it */
export const frostArrow: AbilityDef = {
id: 'frostArrow',
name: 'Frost arrow',
target: 'unit',
range: 7,
manaCost: 20,
cooldown: 5,
effects: [
{
type: 'missile',
speed: 20,
effects: [
{ type: 'damage', amount: 40, damageType: 'magic' },
{ type: 'buff', buff: 'chilled' }
]
}
]
}Done, with the buff in the rules' buffs and the ability in its abilities: the arrow flies, lands for 40 and slows its target for 3 seconds.
- Right when the ability is a new mix of things abilities already do. Effects are data: the editor's Data panel shows them, a
pack.jsoncan carry them, and a computer player knows how to use them. - Not when no effect does the thing. Then write one effect of your own with
defineEffectand use it like the engine's (Make an effect of my own). It is still one entry ineffects, so every ability can use it.
See Add an ability or a spell and Abilities for every effect.
3. A callback of the definition
Some fields of a definition take a function, asked whenever the engine needs the answer. It changes that one definition and nothing else.
import type { AbilityDef } from '@v12-engine/engine'
/** The arrow reaches a cell farther for each level, and two more by night */
export const frostArrow: AbilityDef = {
id: 'frostArrow',
name: 'Frost arrow',
target: 'unit',
range: 7,
manaCost: 20,
cooldown: 5,
maxLevel: 3,
rangeOf: (world, _caster, level) => 6 + level + (world.night ? 2 : 0),
effects: [{ type: 'damage', amount: [40, 60, 80] }]
}Done: the arrow's reach is worked out at every cast. range stays what the screen shows.
| Definition | Fields that take a function |
|---|---|
AbilityDef | rangeOf, castTimeOf, autoAim, ai, describe, piercesImmunity, channel.run, channel.interrupted |
BuffDef | onApply, onTick.run, onRemove, change, stacking, minHealth, dispellable, camouflage |
UnitTypeDef | corpse, spellImmune, drops, buildRate |
UpgradeDef | apply |
| An effect | amount and other numbers: a function of the cast, in place of a number (EffectValue) |
Some settings take a function too, for a rule of the whole game: settings: { combat: { missChance: () => 0 } }.
- Right when one definition needs a number or a choice that depends on the world, and the field for it is there.
- Not when the same change is for many definitions (a hook, step 4), or the field is not there. A function is code: it cannot be in
data.jsonor apack.json, and the editor's Data panel does not show it.
4. A hook
A hook runs inside the tick, at a named moment of a rule, and can change or cancel what is about to happen. It is for a rule that cuts across definitions.
import { defineHook, hasBuff } from '@v12-engine/engine'
/** Anything chilled is brittle: every blow it takes is a quarter harder */
export const brittle = defineHook({
hook: 'beforeDamage',
id: 'mygame.brittle',
run(_world, event) {
if (hasBuff(event.target, 'chilled')) event.amount *= 1.25
}
})Done, with brittle in the rules' hooks: every source of damage, the engine's and yours, hits a chilled unit harder.
- Right when the change must happen before the thing is settled: more or less damage, a cast refused, a death held off. Also to put your own rule in place of one of the engine's, by giving yours its id.
- Not when you only want to know that it happened (a listener, step 5), or the engine asks no hook at that moment.
canAttack,targetScoreandvisibleare asked very often: keep their handlers cheap.
See Hooks for every moment and what a handler can change, and Change a rule with a hook.
5. A listener
A listener hears an event once the tick is over. It cannot change what happened; it does what follows from it.
import { defineListener, earn, entityDied } from '@v12-engine/engine'
/** A fallen archer pays her side 20 gold back */
export const pension = defineListener({
id: 'mygame.pension',
event: entityDied,
run(world, { entity }) {
if (entity.def.id === 'archer') earn(world.player(entity.owner).resources, 'gold', 20)
}
})Done, with pension in the rules' listeners: each archer that dies pays 20 gold.
- Right when you react: pay, spawn, count, start a timer, tell the screen.
- Not when the answer has to change the thing itself. The archer is dead by the time the listener hears of it: to keep her alive, use the
beforeDeathhook.
See Events and listeners, which has events of your own and a table of hooks against events.
6. A system or an order
A system is code the world runs every tick, or every so many ticks. An order is a new thing a unit can be told to do, with its own start, tick and end.
import { hasBuff, type System } from '@v12-engine/engine'
/** Once a second, every unit that is not chilled mends 1 health */
export const mending: System = {
name: 'mygame.mending',
phase: 'resolve',
// in ticks: 30 of them a second
every: 30,
update(world) {
for (const entity of world.units.values()) if (entity.alive && !hasBuff(entity, 'chilled')) world.heal(entity, 1)
}
}Done, with mending in the rules' systems: units mend by themselves, and a chill stops it.
- Right when nothing sets it off: it goes on by itself, tick after tick (a system), or a player or a script must be able to tell a unit to do it and queue it like any other order (an
OrderBehavior). - Not when one moment sets it off (a hook or a listener), it lasts a while on one unit (a buff with
onTick), or it happens once later (a timer). A system costs time every tick whether anything happens or not.
See Add a system, Systems, Add an order and Orders and commands.
7. A mod
A mod makes any of the changes above to a game from outside it: the game's files stay as they are. composeGame gives the game with its mods on.
import { composeGame, type ModDef } from '@v12-engine/engine'
import { rules } from './rules'
import { brittle } from './brittle'
/** Longer bows and brittle ice, over the game as it is */
export const hardWinter: ModDef = {
id: 'hard-winter',
version: '1.0.0',
requires: ['my-game'],
apply(game) {
game.units.override('archer', (def) => ({ ...def, stats: { ...def.stats, attackRange: 9 } }))
game.hooks.add(brittle)
game.settings({ supply: { max: 200 } })
}
}
export const winterGame = composeGame(rules, [hardWinter])Done: what composeGame gives is a game like any other, with the id my-game+hard-winter.
- Right when the game is someone else's, or the change is a variant kept apart from it: another mode, a balance patch, a pack of content. Two mods that change the same thing without one requiring the other are refused before anyone plays.
- Not when it is your own game and the change is the game. Write it in the rules.
A mod of data alone can be a pack.json, with no code at all. See Make a mod and Mods and content packs.
Which data layer wins
A definition's value can be said in several places. Each row is laid over the rows above it, so the lowest row that says a value wins.
| Layer | How it gets there | Reach | What it may change |
|---|---|---|---|
| Your code | Rules: units, abilities, settings… | The game | Everything |
data.json | layData(rules, dataFile), where the game is made | The game | Fields the game lists in editable; the rest is logged |
| Mods | composeGame(rules, mods) | The game played with them | Everything, code too |
Content packs (pack.json) | contentPacks in the page, mergePackFiles on a server | The game played with them | Definitions as data; its data only editable fields |
A map's definitions | Laid as a world is made from the map (createWorldFromMap) | Worlds on that map | Fields the game lists in editable |
world.redefine(kind, id, …) | Called while the game runs | That world, and its saves | Any field of a definition, as data: editable or not |
- Under your own code are the lists of the packs you added (
heroesPack()…): a command, hook or system of yours with the same id takes the place of a pack's. - Current behaviour: a code pack's
settingsgo the other way.assembleGamelays each pack'ssettings(resolved)over the game'ssettings, in the order ofpacks, so where both say a value the pack's wins, and a later pack's over an earlier one's. A pack is handed the settings as they stand, so one written to keep the game's value can return it. The same holds for a mod'sgame.settingsand adata.json'srules: both change the game'ssettings, and the packs' are laid over those as the game is assembled. To change a value a pack sets, give the pack the value where you make it (heroesPack({ maxHeroes: 5 })). - Mods apply after the mods they require, otherwise in the order given. A content pack is a mod made of a file (
packFromJson): the packs a game names are put on as it loads, in the order named, over the mods already in it. Inside one pack its definitions go first, then itsdata, then itssettings. - What
world.redefinechanged is kept in the save and stays on top when the game's files reload. - Current behaviour:
Rules.editablegates files, notworld.redefine.layDatatakes only the fields the game lists ineditableand logs the rest; that coversdata.json, a pack'sdataand a map'sdefinitions, which all go through it.world.redefinetakes any field of a definition the game has, listed or not. The check is in the command the editor's Data panel sends (debug.redefine,redefineCommand), which refuses a field that is noteditableand is for players allowed the debug tools. Code of yours that callsworld.redefinedoes its own checking. - A
pack.jsonchanges the rules' knobs undersettings, and itsdata.rules(supply, heroes, upkeep, resources) as adata.json's are (Content packs). - Tunables are apart from all of this: they are numbers of the rules, not fields of a definition.
world.tunable(id)is whatworld.setTunableset in that world, else the value intuning.json(layTuning), else the tunable'sdefault(Testing).
What reloads as you save says which of these a running game takes without a page reload.