Change a rule with a hook, or listen to an event
A hook runs at a named moment of a rule and can change what happens. A listener hears an event afterwards and changes nothing. List them in your rules' hooks and listeners.
ts
// in src/rules.ts
import { defineHook, defineIds, defineListener, entityDied, type Rules } from '@v12-engine/engine'
export const UNIT = defineIds('scout', 'wall')
/** Buildings take half of every blow: a change to the rule, before the damage lands */
const stoneWalls = defineHook({
hook: 'beforeDamage',
id: 'mygame.stoneWalls',
// among the hooks of the same moment, the lower runs first; the engine's own are at 0
priority: 10,
run(_world, event) {
if (event.target.def.kind === 'building') event.amount *= 0.5
}
})
/** Nobody attacks a scout on purpose: the rule asked before an attack order, and refused */
const scoutsAreSacred = defineHook({
hook: 'canAttack',
id: 'mygame.scoutsAreSacred',
run(_world, event) {
if (event.ordered && event.target.def.id === UNIT.scout) event.cancelled = true
}
})
/** What happened, heard: a death is logged */
const deathsLogged = defineListener({
id: 'mygame.deathsLogged',
event: entityDied,
run(world, { entity }) {
world.log.info('mygame', 'died', { type: entity.def.id, owner: entity.owner })
}
})
export const rules: Rules = {
id: 'my-game',
name: 'My game',
units: [
{ id: UNIT.scout, name: 'Scout', kind: 'unit', radius: 0.4, sight: 10, stats: { health: 100, moveSpeed: 5 } },
{ id: UNIT.wall, name: 'Wall', kind: 'building', radius: 0.5, sight: 2, footprint: { w: 1, d: 1 }, stats: { health: 500 } }
],
hooks: [stoneWalls, scoutsAreSacred],
listeners: [deathsLogged],
victory: null
}Done: buildings take half damage, nobody can be ordered to attack a scout, and every death is logged.
Take out one of the engine's hooks
ts
withoutHooks: ['bounty']The engine's are in coreHooks: bounty, experience, loot, onCast, onHit, onKill, undying, mapPathsClear.
Add a moment of your own
Declare it with defineHookType and run it with world.hooks.run. Add an event of your own with defineEvent.
Reference
Hook moments (HookEvents) | beforeDamage, afterDamage, beforeDeath, death, beforeAttack, canAttack, canCast, beforeCast, afterCast, beforeBuff, buffEnd, beforeHeal, beforeOrder, beforeProduce, canPlace, canTarget, canHarvest, beforeXp, beforeTrade, beforeTalk, stats… |
|---|---|
| What a hook can change | Fields of its event: amount, cancelled, cancel(reason). |
| Order | Lower priority runs first. The engine's own are at 0. |
Events (WorldEvents) | entityDied, abilityCast, enteredArea, objectiveChanged, gameOver… |
See Hooks and Events and listeners in depth, and Add a system for something that runs every tick.