Hardcoding nested if/else statements for character actions (running, jumping, attacking, damaged) creates fragile spaghetti code where bugs multiply with every new feature. A **Finite State Machine (FSM)** encapsulates behavior into isolated state classes with formal transitions, entry hooks, and exit cleanup routines.
1. FSM State Pattern Implementation
// Modular State Interface & State Machine
class PlayerStateMachine {
constructor(player) {
this.player = player;
this.currentState = null;
}
transitionTo(newState) {
if (this.currentState) this.currentState.onExit();
this.currentState = newState;
this.currentState.onEnter();
}
update(delta) {
if (this.currentState) this.currentState.onUpdate(delta);
}
}