File size: 1,255 Bytes
eee16fe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import { EntityStateEnum } from '../enum/EntityStateEnum';
export interface State {
onTick(): void;
onStart?(): void;
onEnd?(): void;
name: EntityStateEnum;
}
//TODO: add state durantion/delay based on tick per second
export class StateMachine {
private states: Map<EntityStateEnum, State> = new Map();
private currentState: State | null = null;
addState(state: State) {
this.states.set(state.name, state);
return this;
}
getCurrentState() {
return this.currentState;
}
getCurrentStateName() {
return this.currentState?.name;
}
overrideState(state: Partial<State>) {
const oldState = this.states.get(state.name!);
if (!oldState) return;
const newState = {
...oldState,
...state,
};
this.states.set(newState.name, newState);
return this;
}
gotoState(name: EntityStateEnum) {
if (name === this.currentState?.name) return;
const state = this.states.get(name);
if (!state) return;
this.currentState?.onEnd?.();
this.currentState = state;
this.currentState.onStart?.();
}
tick() {
this.currentState?.onTick();
}
}
|