State Machine
Keeps an enemy, the player or the whole game in exactly one state at a time (idle, chase, attack, stunned) with clear rules for moving between them.
Files: state-machine.js (the component, no dependencies) and state-machine.test.mjs (3 tests).
Copy state-machine.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createStateMachine } from "./state-machine.js";
const ai = createStateMachine({
initial: "patrol", context: enemy,
states: {
patrol: { update(e, dt) { e.walk(dt); if (e.seesPlayer()) return "chase"; } },
chase: { enter(e) { e.alert(); }, update(e, dt, m) { if (m.elapsed > 5) return "patrol"; }, on: { HIT: "stunned" } },
stunned:{ enter(e) { e.flash(); }, update(e, dt, m) { if (m.elapsed > 1) return m.previous; } },
dead: { final: true },
},
on: { DIE: "dead" }, // works from any state
});
ai.update(dt); ai.send("HIT");
API
createStateMachine({ initial, states, context, on }) → machinestate: { enter(ctx, machine, payload), update(ctx, dt, machine) → next state name or nothing, exit(ctx, machine), on: { EVENT: “target” | { target, guard(ctx, payload) } }, final }machine.update(dt)runs the state’s update; a returned name changes statemachine.send(event, payload) → true if it changed statemachine.go(name, payload)change state directlymachine.can(event) / machine.is(name)machine.state / machine.previous / machine.elapsed (seconds in this state) / machine.history (last 10)machine.onChange(fn) → offfn(to, from, event)
Final states ignore events. Changing to the current state runs exit and enter again.
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes, no engine code involved. |
Tests
Node tests: enter and exit order, update returning a state, events and guards, events from any state, final states, elapsed time, history, unknown states.
Run them with node --test toolkit/components/state-machine/ (Node 20 or newer, nothing to install).