GAME STATE
game-state.ts
Hierarchical state machine with enter/exit hooks, history, and save/load.
StarkWHAT THIS PATTERN TEACHES
How to manage complex game states (menus, gameplay, pause, cutscenes) with clean transitions, sub-states, and serialization for save games.
WHEN TO USE THIS
Any game with multiple modes (menu, play, pause, game-over) that need clean transitions.
AT A GLANCE
class StateMachine {
transition(to: string) {
this.current.exit()
this.current = this.states[to]
this.current.enter()
}
}FRAMEWORK IMPLEMENTATIONS
TypeScript
interface GameState {
name: string;
enter(): void;
exit(): void;
update(dt: number): void;
render(): void;
}
class StateMachine {
private states: Map<string, GameState> = new Map();
private current: GameState | null = null;
private history: string[] = [];
transition(to: string) {
if (this.current) {
this.history.push(this.current.name);
this.current.exit();
}
this.current = this.states.get(to) ?? null;
this.current?.enter();