/** * 通用有限状态机(Finite State Machine),适用于角色状态、AI 状态、UI 流程等。 */ export interface IStateHandler { OnEnter?: (this: void, ctx: TContext, fromState?: string) => void; OnUpdate?: (this: void, ctx: TContext, dt: number) => void; OnExit?: (this: void, ctx: TContext, toState: string) => void; } export interface IStateTransition { from: TStateId | "*"; to: TStateId; condition: (this: void, ctx: TContext) => boolean; } export class StateMachine { private ctx: TContext; private states: Record | undefined> = {}; private transitions: IStateTransition[] = []; private currentState: TStateId | undefined = undefined; private stateElapsed = 0; private paused = false; private history: TStateId[] = []; constructor(ctx: TContext) { this.ctx = ctx; } RegisterState(id: TStateId, handler: IStateHandler): void { this.states[id] = handler; } AddTransition( from: TStateId | "*", to: TStateId, condition: (this: void, ctx: TContext) => boolean ): void { this.transitions[this.transitions.length] = { from, to, condition }; } Start(initialState: TStateId): boolean { if (this.states[initialState] === undefined) { return false; } this.currentState = initialState; this.stateElapsed = 0; this.history[this.history.length] = initialState; const handler = this.states[initialState]; if (handler && handler.OnEnter) { handler.OnEnter(this.ctx, undefined); } return true; } ChangeState(nextState: TStateId): boolean { if (this.currentState === nextState || this.states[nextState] === undefined) { return false; } const prev = this.currentState; if (prev !== undefined) { const prevHandler = this.states[prev]; if (prevHandler && prevHandler.OnExit) { prevHandler.OnExit(this.ctx, nextState); } } this.currentState = nextState; this.stateElapsed = 0; this.history[this.history.length] = nextState; const nextHandler = this.states[nextState]; if (nextHandler && nextHandler.OnEnter) { nextHandler.OnEnter(this.ctx, prev); } return true; } Update(dt: number): void { if (this.paused || this.currentState === undefined) { return; } this.stateElapsed += dt; // 先检查条件转换 for (let i = 0; i < this.transitions.length; i++) { const tr = this.transitions[i]; if ( (tr.from === "*" || tr.from === this.currentState) && tr.to !== this.currentState && tr.condition(this.ctx) ) { this.ChangeState(tr.to); break; } } const handler = this.states[this.currentState]; if (handler && handler.OnUpdate) { handler.OnUpdate(this.ctx, dt); } } SetPaused(paused: boolean): void { this.paused = paused; } GetCurrentState(): TStateId | undefined { return this.currentState; } GetStateElapsed(): number { return this.stateElapsed; } GetHistory(): TStateId[] { return this.history; } }