|
| 1 | +module fsm{ |
| 2 | + /** |
| 3 | + * 具有字符串约束的简单状态机。 使用此功能时必须遵循一些规则: |
| 4 | + * - 在调用update之前必须设置initialState(使用构造函数) |
| 5 | + * - 如果在子类中实现更新,则必须调用super.update() |
| 6 | + * |
| 7 | + * @abstract |
| 8 | + * @class SimpleStateMachine |
| 9 | + * @template TEnum |
| 10 | + */ |
| 11 | + export abstract class SimpleStateMachine{ |
| 12 | + protected elapsedTimeInState: number = 0; |
| 13 | + protected previousState: string; |
| 14 | + private _stateCache: {[key: string]: StateMethodCache}; |
| 15 | + private _stateMethods: StateMethodCache; |
| 16 | + |
| 17 | + private _currentState: string; |
| 18 | + public get currentState(): string{ |
| 19 | + return this._currentState; |
| 20 | + } |
| 21 | + |
| 22 | + public set currentState(value: string){ |
| 23 | + if (this._currentState == value) |
| 24 | + return; |
| 25 | + |
| 26 | + this.previousState = this._currentState; |
| 27 | + this._currentState = value; |
| 28 | + |
| 29 | + if (this._stateMethods.exitState != null) |
| 30 | + this._stateMethods.exitState(); |
| 31 | + |
| 32 | + this.elapsedTimeInState = 0; |
| 33 | + this._stateMethods = this._stateCache[this._currentState]; |
| 34 | + |
| 35 | + if (this._stateMethods.enterState != null) |
| 36 | + this._stateMethods.enterState(); |
| 37 | + } |
| 38 | + |
| 39 | + protected set initialState(value: string){ |
| 40 | + this._currentState = value; |
| 41 | + this._stateMethods = this._stateCache[this._currentState]; |
| 42 | + |
| 43 | + if (this._stateMethods.enterState != null) |
| 44 | + this._stateMethods.enterState(); |
| 45 | + } |
| 46 | + |
| 47 | + constructor(){ |
| 48 | + this._stateCache = {}; |
| 49 | + } |
| 50 | + |
| 51 | + public update(){ |
| 52 | + if (this._stateMethods.tick != null) |
| 53 | + this._stateMethods.tick(); |
| 54 | + } |
| 55 | + |
| 56 | + public setEnterMethod(stateName: string, enterState: Function, tickState: Function, exitState: Function){ |
| 57 | + let state = new StateMethodCache(); |
| 58 | + state.enterState = enterState; |
| 59 | + state.tick = tickState; |
| 60 | + state.exitState = exitState; |
| 61 | + |
| 62 | + this._stateCache[stateName] = state; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + export class StateMethodCache{ |
| 67 | + public enterState: Function; |
| 68 | + public tick: Function; |
| 69 | + public exitState: Function; |
| 70 | + } |
| 71 | +} |
0 commit comments