跳到內容

aifsmjs — 狀態機

aifsmjs 是一個小型、嚴格的 FSM(有限狀態機)函式庫。核心哲學是定義與實作分離:狀態圖是純 JSON 資料,guards/actions/effects 在 runtime 注入,因此整個 machine definition 可以被序列化、跨 Worker 傳輸,或存進資料庫。

生命週期是一個純函數:step() 按固定順序執行 guards → exit → action → entry,不可中斷、可確定性重放。

終端機視窗
npm install aifsmjs
import { setup, createRuntime, assign } from "aifsmjs";
type Ctx = { ticks: number };
type Evt = { type: "NEXT" };
// 1. 定義是純資料:setup<Ctx, Evt>() 讓 States 從 states 的 key 自動推斷
const trafficLight = setup<Ctx, Evt>().defineMachine({
id: "trafficLight",
initial: "red",
context: { ticks: 0 },
states: {
red: { on: { NEXT: { target: "green", actions: ["bump"] } } },
green: { on: { NEXT: { target: "yellow", actions: ["bump"] } } },
yellow: { on: { NEXT: { target: "red", actions: ["bump"] } } },
},
});
// 2. 實作在 runtime 注入
const runtime = createRuntime(trafficLight, {
actions: {
bump: assign(({ context }) => ({ ticks: context.ticks + 1 })),
},
});
// 3. 發送事件
runtime.send({ type: "NEXT" });
console.log(runtime.getSnapshot().value); // "green"
console.log(runtime.getSnapshot().context); // { ticks: 1 }

角色受擊後的硬直與無敵時間,是遊戲裡最常見的狀態機。下方示範中,hit 與 invulnerable 的 entry action 只負責排入 effect,由 effect 呼叫 aifsmjs/timer 的 after(),時間到再送出 RECOVER 與 EXPIRE;這兩個狀態都沒有處理 HIT,所以無敵期間的攻擊直接被忽略。攻擊每 1.1 秒自動發生一次,點擊或輕觸畫面也會送出 HIT,狀態列由 aifsmjs/inspect 的 logger 列出最近 3 次轉移。

互動示範載入中…

CharacterBrain:受擊、無敵時間與狀態檢視
示範原始碼
src/demos/fsm-character.ts
/**
* CharacterBrain: hit, invulnerability frames and state inspection with aifsmjs.
*
* A character patrols (idle <-> walk). A hit sends it to `hit`, whose entry action enqueues
* an effect that starts an `aifsmjs/timer` `after()` for the stun; the timer sends RECOVER,
* and `invulnerable` starts the i-frame window the same way, ending in EXPIRE. Neither `hit`
* nor `invulnerable` handles HIT, so hits that arrive meanwhile are ignored: that is the
* i-frame rule, written as data. Hits arrive on their own every 1.1 s, and a click or tap
* sends one too.
*
* The `logger` middleware from `aifsmjs/inspect` feeds the last 3 transitions to the readout.
* Run-to-completion (0.6.0): nothing here reads a nested send()'s result; the readout reads
* getSnapshot() after the outermost call returns.
*/
import { assign, createRuntime, setup } from 'aifsmjs';
import { logger } from 'aifsmjs/inspect';
import { after } from 'aifsmjs/timer';
import { ColorMatrixFilter, Container, Graphics, type Application } from 'pixi.js';
import type { DemoContext, DemoHandle } from './types';
const ARENA = { width: 800, height: 400 };
const GROUND_Y = 300;
const PATROL = { left: 220, right: 580 };
const WALK_SPEED = 90; // px per second
const IDLE_MS = 900;
const WALK_MS = 1800;
const STUN_MS = 350;
const IFRAME_MS = 1500;
const AUTO_HIT_MS = 1100;
const FLASH_MS = 260;
const IMPACT_MS = 380;
const MAX_STEP_MS = 50;
type Ctx = { hits: number };
type Evt = { type: 'MOVE' | 'STOP' | 'HIT' | 'RECOVER' | 'EXPIRE' };
// The machine is plain data: states, events and named actions. The code lives in createRuntime.
const brain = setup<Ctx, Evt>().defineMachine({
id: 'characterBrain',
initial: 'idle',
context: { hits: 0 },
states: {
idle: { on: { MOVE: 'walk', HIT: { target: 'hit', actions: ['countHit'] } } },
walk: { on: { STOP: 'idle', HIT: { target: 'hit', actions: ['countHit'] } } },
hit: { entry: ['armStun'], on: { RECOVER: 'invulnerable' } },
invulnerable: { entry: ['armIFrames'], on: { EXPIRE: 'idle' } },
},
});
/**
* A timer queue driven by update(), injected into after() in place of setTimeout, so the stun
* and i-frame windows pause with the demo (offscreen, Pause, reduced motion).
*/
function createDemoClock() {
type Timer = { at: number; fn: () => void };
let now = 0;
const timers = new Set<Timer>();
return {
setTimeout(fn: () => void, ms: number): Timer {
const timer = { at: now + ms, fn };
timers.add(timer);
return timer;
},
clearTimeout(handle: unknown): void {
timers.delete(handle as Timer);
},
advance(ms: number): void {
now += ms;
for (const timer of [...timers]) {
if (timer.at > now) continue;
timers.delete(timer);
timer.fn();
}
},
};
}
function readColors(cssColor: DemoContext['cssColor']) {
return {
body: cssColor('--sl-color-accent'),
ground: cssColor('--sl-color-gray-4'),
hit: cssColor('--sl-color-orange'),
ignored: cssColor('--sl-color-gray-3'),
};
}
const READOUT = {
'zh-TW': (state: string, hits: number, ignored: number, log: string) =>
`狀態:${state}|命中 ${hits}、無敵中忽略 ${ignored}|最近轉移:${log || '—'}`,
en: (state: string, hits: number, ignored: number, log: string) =>
`State: ${state} | hits ${hits}, ignored while invulnerable ${ignored} | recent: ${log || '—'}`,
};
export function mount(app: Application, { lang, setStatus, cssColor }: DemoContext): DemoHandle {
const clock = createDemoClock();
const recent: string[] = []; // newest first
const timerOptions = (signal: AbortSignal) => ({ signal, setTimeout: clock.setTimeout, clearTimeout: clock.clearTimeout });
const runtime = createRuntime(
brain,
{
actions: {
countHit: assign(({ context }) => ({ hits: context.hits + 1 })),
// Entry actions stay pure: they only enqueue effects, which run after the commit.
armStun: ({ enqueue }) => enqueue.effect('stunTimer'),
armIFrames: ({ enqueue }) => enqueue.effect('iFrameTimer'),
},
effects: {
// `signal` is the runtime's own: dispose() aborts it, which cancels a pending after().
stunTimer: (_effect, { signal }) => {
after(STUN_MS, () => runtime.send({ type: 'RECOVER' }), timerOptions(signal));
},
iFrameTimer: (_effect, { signal }) => {
after(IFRAME_MS, () => runtime.send({ type: 'EXPIRE' }), timerOptions(signal));
},
},
},
{
middleware: [
logger((line) => {
recent.unshift(line); // "[HIT] walk → hit"
recent.length = Math.min(recent.length, 3);
}),
],
},
);
// Scene: ground, an impact ring, and the character (body with eye holes, under a flash filter).
const arena = new Container();
const ground = new Graphics();
const impact = new Graphics();
const hero = new Container();
const body = new Graphics();
const flash = new ColorMatrixFilter();
flash.enabled = false;
body.filters = [flash];
hero.addChild(body);
arena.addChild(ground, hero, impact);
app.stage.addChild(arena);
let colors = readColors(cssColor);
const paint = () => {
ground.clear().moveTo(60, GROUND_Y).lineTo(ARENA.width - 60, GROUND_Y).stroke({ width: 2, color: colors.ground });
body.clear().roundRect(-26, -64, 52, 64, 16).fill(colors.body);
body.roundRect(2, -50, 7, 12, 3).roundRect(14, -50, 7, 12, 3).cut(); // eyes, facing right
const [r, g, b] = [colors.hit >> 16, (colors.hit >> 8) & 0xff, colors.hit & 0xff].map((c) => c / 255);
flash.matrix = [0, 0, 0, 0, r, 0, 0, 0, 0, g, 0, 0, 0, 0, b, 0, 0, 0, 1, 0]; // solid colour, same alpha
};
const fit = () => {
const scale = Math.min(app.screen.width / ARENA.width, app.screen.height / ARENA.height);
arena.scale.set(scale);
arena.position.set((app.screen.width - ARENA.width * scale) / 2, (app.screen.height - ARENA.height * scale) / 2);
};
fit();
app.renderer.on('resize', fit);
let x = (PATROL.left + PATROL.right) / 2;
let facing = 1;
let stateMs = 0; // time in the current state
let sinceHit = 0;
let ignored = 0;
let flashMs = 0;
let clockMs = 0; // for bobbing and blinking
let ring = { age: IMPACT_MS, landed: false };
runtime.subscribe((snap) => {
stateMs = 0;
if (snap.value === 'hit') flashMs = FLASH_MS;
});
let shown = '';
const report = () => {
const { value, context } = runtime.getSnapshot(); // read after the outermost send() returned
const text = READOUT[lang](value, context.hits, ignored, recent.join(' · '));
if (text !== shown) setStatus((shown = text));
};
/** One incoming hit: HIT is only handled by idle and walk, so can() tells if it lands. */
const strike = () => {
const landed = runtime.can({ type: 'HIT' });
if (!landed) ignored++;
runtime.send({ type: 'HIT' });
ring = { age: 0, landed };
report();
};
app.canvas.addEventListener('pointerdown', strike);
app.canvas.style.cursor = 'pointer';
/** Poses the character for the current state and draws the impact ring. */
const place = () => {
const state = runtime.getSnapshot().value;
const shake = state === 'hit' ? Math.sin(clockMs * 0.09) * 5 : 0;
const bob = state === 'walk' ? -Math.abs(Math.sin(clockMs * 0.012)) * 6 : Math.sin(clockMs * 0.004) * 1.5;
hero.position.set(x + shake, GROUND_Y + bob);
hero.scale.x = facing;
hero.alpha = state === 'invulnerable' && Math.floor(clockMs / 80) % 2 === 0 ? 0.35 : 1; // i-frame blink
flash.enabled = flashMs > 0;
flash.alpha = flashMs / FLASH_MS;
const t = ring.age / IMPACT_MS;
impact.clear();
if (t < 1) {
impact.circle(x, GROUND_Y - 34, 30 + t * 40).stroke({ width: 4, color: ring.landed ? colors.hit : colors.ignored, alpha: 1 - t });
}
};
paint();
place(); // the first frame is drawn even if the demo never plays (reduced motion)
report();
return {
update(deltaMS) {
const ms = Math.min(deltaMS, MAX_STEP_MS);
clockMs += ms;
stateMs += ms;
clock.advance(ms); // may send RECOVER or EXPIRE from a pending after()
const state = runtime.getSnapshot().value;
if (state === 'idle' && stateMs >= IDLE_MS) runtime.send({ type: 'MOVE' });
if (state === 'walk' && stateMs >= WALK_MS) runtime.send({ type: 'STOP' });
if (state === 'walk') {
x += facing * WALK_SPEED * (ms / 1000);
if (x <= PATROL.left || x >= PATROL.right) facing = x <= PATROL.left ? 1 : -1;
}
if (state === 'hit') x = Math.min(Math.max(x - facing * 120 * (ms / 1000), PATROL.left), PATROL.right); // knockback
sinceHit += ms;
if (sinceHit >= AUTO_HIT_MS) {
sinceHit = 0;
strike();
}
flashMs = Math.max(0, flashMs - ms);
ring.age += ms;
place();
report();
},
onThemeChange() {
colors = readColors(cssColor);
paint();
place();
},
dispose() {
app.renderer.off('resize', fit);
app.canvas.removeEventListener('pointerdown', strike);
app.canvas.style.cursor = '';
runtime.dispose(); // aborts its signal: pending after() timers are cancelled
body.filters = [];
flash.destroy();
arena.destroy({ children: true });
},
};
}
MachineDefinition(純資料)+ Implementations(runtime 注入)
↓
step(def, snapshot, event, impl)
→ guards → exit → action → entry
→ 回傳新 snapshot(不可變)
Subpath 用途
aifsmjs 核心:setup、createRuntime、assign、step
aifsmjs/guards and、or、not、stateIn guard 組合器(guard 必須是同步函式)
aifsmjs/effects createEnqueuer() 與 runEffects()
aifsmjs/inspect 只觀察、不修改轉移的 middleware:logger、persist、recorder
aifsmjs/replay 事件序列回放
aifsmjs/pbt fast-check fc.commands 整合,屬性測試
aifsmjs/timer after() 與 createScheduler()
  • send() / reset() 採 run-to-completion:在 middleware、effect handler 或 listener 內呼叫的 send() / reset() 會排入佇列,等目前事件的通知全部跑完才執行。巢狀呼叫回傳的是當下已 commit 的 snapshot,請在最外層呼叫回傳後再讀 getSnapshot()(或用 subscribe),並把 try/catch 放在最外層呼叫;佇列中事件的錯誤會從最外層呼叫丟出。
  • 通知途中被移除的 listener(unsubscribe、once、signal、dispose())在這一輪不會再被呼叫;仍需收到目前事件時,請用 queueMicrotask(off) 延後移除。
  • object context 的 action 應回傳 plain-object partial(或 undefined),merge 會保留 context 的 prototype;回傳 false、0 等 primitive 會丟出 InvalidActionResultError。
  • 轉移替換 sub-machine 時,會先建立新 child 再 dispose 舊 child;新 child 初始化失敗時,舊 child 仍然有效。
  • after() / createScheduler().after() 的 ms 必須是 >= 0 的有限數值(否則丟出 RangeError),fn 必須是函式(否則丟出 TypeError);超過 2^31-1 ms(約 24.8 天)的延遲會被截為上限。要表達「永不」,就不要排程。
  • defineMachine、createRuntime 與 runtime 方法的參數誤用會丟出 InvalidDefinitionError:沒有具名實作時 impl 也要傳 {},事件必須是帶 string type 的物件,listener 必須是函式。
  • 遊戲場景切換:FSM 管理 lobby → game → paused → gameOver,emit 事件到渲染層
  • 多步驟表單:每個步驟是一個 state,guards 驗證欄位再允許 NEXT 轉移
  • 與 aiecsjs 搭配:ECS 裡的 entity 可以帶一個 FSM snapshot 管理行為狀態(例如角色的 idle / walk / attack)
  • 與 aibridgejs 搭配:machine definition 可直接 JSON 序列化後透過 bridge 傳到另一個 context