Bash.tv → GitHub → itch.io

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

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).