Files
rougelike-demo/client/assets/scripts/Framework/FSM/FSM.ts

140 lines
3.6 KiB
TypeScript
Raw Normal View History

2025-12-14 22:38:43 +08:00
import { IState } from "./IState";
/**
* (Finite State Machine)
*
*/
export class FSM {
/**
* Map,
*/
private _states: Map<string, IState>;
/**
*
*/
private _currentState: IState | null;
/**
*
*/
constructor() {
this._states = new Map<string, IState>();
this._currentState = null;
}
/**
*
* @param state
*/
addState(state: IState): void {
if (this._states.has(state.name)) {
console.warn(`[FSM] 状态 "${state.name}" 已存在,将被覆盖`);
}
this._states.set(state.name, state);
console.log(`[FSM] 添加状态: ${state.name}`);
}
/**
*
* @param stateName
*/
removeState(stateName: string): void {
if (!this._states.has(stateName)) {
console.warn(`[FSM] 状态 "${stateName}" 不存在,无法移除`);
return;
}
// 如果当前状态就是要移除的状态,先退出
if (this._currentState && this._currentState.name === stateName) {
this._currentState.onExit();
this._currentState = null;
}
this._states.delete(stateName);
console.log(`[FSM] 移除状态: ${stateName}`);
}
/**
*
* @param stateName
* @param params ,onEnter方法
*/
changeState(stateName: string, params?: any): void {
const newState = this._states.get(stateName);
if (!newState) {
console.error(`[FSM] 状态 "${stateName}" 不存在,无法切换`);
return;
}
// 退出当前状态
if (this._currentState) {
this._currentState.onExit();
}
// 切换到新状态
this._currentState = newState;
this._currentState.onEnter(params);
}
/**
*
* @returns ,null
*/
getCurrentState(): IState | null {
return this._currentState;
}
/**
*
* @returns ,null
*/
getCurrentStateName(): string | null {
return this._currentState ? this._currentState.name : null;
}
/**
*
* @param stateName
* @returns true,false
*/
hasState(stateName: string): boolean {
return this._states.has(stateName);
}
/**
*
* @param stateName
* @returns ,undefined
*/
getState(stateName: string): IState | undefined {
return this._states.get(stateName);
}
/**
*
* onUpdate方法,
* @param dt ()
*/
update(dt: number): void {
if (this._currentState && this._currentState.onUpdate) {
this._currentState.onUpdate(dt);
}
}
/**
*
*/
clear(): void {
// 退出当前状态
if (this._currentState) {
this._currentState.onExit();
this._currentState = null;
}
this._states.clear();
console.log('[FSM] 已清空所有状态');
}
}