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.
What It Demonstrates
Section titled “What It Demonstrates”createBehavioralFsmfor 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’sWeakMap, where a stray assignment can’t overwrite it. - The client object is the context: each handler receives the critter as
ctx. Handlers readctx.xandctx.y, writectx.vxandctx.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")andfsm.handle(critterB, "tick")resolve independently.fsm.currentState(critterA)may return"chase"whilefsm.currentState(critterB)returns"idle".
States
Section titled “States”| 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 |
Key Pattern
Section titled “Key Pattern”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:
The game loop dispatches an input to each critter every frame:
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.
Interacting With the Demo
Section titled “Interacting With the Demo”- 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