|
@@ -1,3 +1,4 @@
|
|
|
+import Func from '../ECS/Function';
|
|
|
import StateHandler from './StateHandler';
|
|
|
|
|
|
class StateMachine<T> {
|
|
@@ -36,25 +37,53 @@ class StateMachine<T> {
|
|
|
this.currentState = null;
|
|
|
}
|
|
|
|
|
|
- public addState(label: T, handler: StateHandler<T>): void;
|
|
|
+ /**
|
|
|
+ *
|
|
|
+ * @param label 状态机标识
|
|
|
+ * @param handler 状态机句柄
|
|
|
+ * @param context 上下文
|
|
|
+ */
|
|
|
+ public addState(label: T, handler: StateHandler<T>, context?: Func<T>): void;
|
|
|
+ /**
|
|
|
+ *
|
|
|
+ * @param label 状态机标识
|
|
|
+ * @param onStart 进入状态机
|
|
|
+ * @param onUpdate 状态机执行中
|
|
|
+ * @param onStop 离开状态机
|
|
|
+ * @param context 上下文
|
|
|
+ */
|
|
|
public addState(
|
|
|
label: T,
|
|
|
onStart: Function | null,
|
|
|
onUpdate: Function | null,
|
|
|
onStop: Function | null,
|
|
|
+ context?: Func<T>, // 上下文
|
|
|
): void;
|
|
|
public addState(
|
|
|
label: T,
|
|
|
query: Function | StateHandler<T> | null,
|
|
|
- onUpdate?: Function | null,
|
|
|
+ onUpdate?: Function | Func<T> | null,
|
|
|
onStop?: Function | null,
|
|
|
+ context?: Func<T>,
|
|
|
): void {
|
|
|
let newState;
|
|
|
+ if (onUpdate instanceof Func<T>) context = onUpdate;
|
|
|
if (query instanceof Function || query === null) {
|
|
|
- newState = new State<T>(label, query, onUpdate!, onStop!);
|
|
|
+ if (onUpdate instanceof Func<T>) throw new Error('参数传递错误');
|
|
|
+ newState = new State<T>(
|
|
|
+ label,
|
|
|
+ query?.bind(context || this),
|
|
|
+ onUpdate?.bind(context || this),
|
|
|
+ onStop?.bind(context || this),
|
|
|
+ );
|
|
|
} else {
|
|
|
const { stateIn, stateRunning, stateExit } = query;
|
|
|
- newState = new State<T>(label, stateIn, stateRunning, stateExit);
|
|
|
+ newState = new State<T>(
|
|
|
+ label,
|
|
|
+ stateIn?.bind(context || this),
|
|
|
+ stateRunning?.bind(context || this),
|
|
|
+ stateExit?.bind(context || this),
|
|
|
+ );
|
|
|
}
|
|
|
this.stateMap.set(label, newState);
|
|
|
if (this.currentState == null) {
|