Skip to content

Dungeon Critters

Dungeon Critters spawns up to 80 animated critters on a canvas dungeon floor, each independently driven by one shared FSM definition. It demonstrates createBehavioralFsm. You define the behavior once and pass a client object per call, while the FSM tracks each client’s state separately in an internal WeakMap.

  • createBehavioralFsm for shared behavior: one FSM instance controls every critter (35 at startup, 80 max) without per-critter instantiation.
  • Per-client state via WeakMap: the FSM doesn’t write state onto the critter object itself. State stays inside the FSM’s WeakMap, where a stray assignment can’t overwrite it.
  • The client object is the context: each handler receives the critter as ctx. Handlers read ctx.x and ctx.y, write ctx.vx and ctx.vy, and record timestamps. The client is both the lookup key and the data the handlers mutate.
  • Multiple clients in different states simultaneously: fsm.handle(critterA, "tick") and fsm.handle(critterB, "tick") resolve independently. fsm.currentState(critterA) may return "chase" while fsm.currentState(critterB) returns "idle".
             playerDetected        playerInRange
  idle ──────────────────► alert ──────────────► chase
    ▲  ◄──── fidget ──────── │  ▲                  │
    │                        │  │ playerLostContact │ playerLostContact
    │   patrol ◄─────────────┘  └──────────────────┘
    ▲     │  ▲
    │     │  │ playerDetected            attacked
    │     └──┘                              │
    └──────────── flee ◄────────────────── chase
                   │
                   └── (timer: FLEE_DURATION_MS) ──► idle
State Color Behavior
idle dim grey Stationary; occasional random fidget; drifts back toward home territory if it strayed
patrol green Moves toward a random waypoint within its home territory circle
alert amber Stops and faces the player with a blinking ! indicator. Auto-disengages after 2.5s
chase red Pursues the cursor at full speed; critter inflates visually
flee near-white Runs away from the click point for 2s then returns to idle

One FSM definition, created once, drives every critter. An input payload map declares each input’s payload tuple, so handlers receive typed payloads without annotations or casts:

import { createBehavioralFsm } from "machina";

export type CritterInputs = {
    tick: [payload: TickPayload];
    playerDetected: [];
    playerInRange: [];
    playerLostContact: [];
    attacked: [payload: TickPayload];
};

export function createCritterBehavior() {
    return createBehavioralFsm<CritterClient, CritterInputs>()({
        id: "critter-behavior",
        initialState: "idle",

        states: {
            idle: {
                // ctx IS the critter — read and write its properties directly
                _onEnter({ ctx }) {
                    ctx.vx = 0;
                    ctx.vy = 0;
                    ctx.fidgetTime = Date.now();
                },

                tick({ ctx }) {
                    // Return a state name string to transition
                    if (Math.random() < 0.4) {
                        return "patrol";
                    }
                },

                // Shorthand: input name → target state string
                playerDetected: "alert",
            },

            chase: {
                // `payload` is a typed TickPayload via CritterInputs — no cast
                tick({ ctx }, payload) {
                    const { playerX, playerY } = payload;
                    const dir = directionTo(ctx.x, ctx.y, playerX, playerY);
                    ctx.vx = dir.dx * CHASE_SPEED;
                    ctx.vy = dir.dy * CHASE_SPEED;
                },

                playerLostContact: "alert",

                // Function handler — needed here to capture playerX/playerY before
                // transitioning, since _onEnter does not receive the triggering args.
                attacked({ ctx }, payload) {
                    const { playerX, playerY } = payload;
                    const dir = directionTo(ctx.x, ctx.y, playerX, playerY);
                    ctx.fleeDirection = { dx: -dir.dx, dy: -dir.dy };
                    return "flee";
                },
            },

            // ... other states
        },
    });
}

The game loop dispatches an input to each critter every frame:

const fsm = createCritterBehavior();

// Each call resolves independently — critters stay in their own states
for (const critter of critters) {
    fsm.handle(critter, "tick", { playerX, playerY, dt });
}

// State is a WeakMap lookup, not a property on the critter
const state = fsm.currentState(critter); // "idle" | "patrol" | "alert" | "chase" | "flee"

Timers stay out of the FSM. With 50 or more critters, independent setTimeout chains would be unmanageable. _onEnter stamps Date.now() on the client instead, and tick handlers compare elapsed time. One requestAnimationFrame loop drives everything.

The FSM sets velocity, and the game loop integrates position. Handlers write ctx.vx and ctx.vy to express behavioral intent. The game loop applies x += vx and clamps to canvas bounds. The handlers stay out of the pixel math.

  • Move the cursor over critters to trigger detection and chase
  • Click to blast critters within 80px. A chasing critter flees, and the others ignore the blast
  • Click directly on a critter to select it and open the inspector panel
  • Sensing range slider: adjust the detection radius live for all critters
  • Show sensing radius: toggle the detection circle visualization
  • Spawn: add 10 more critters, up to the cap of 80

examples/dungeon-critters/