To move the state machine to a new state, use the .enter(state) function.
State Composer does not provide built-in transition guards or complex transition definitions. Instead, it encourages implementing transitions as standard JavaScript functions. You can combine state checks, side effects, and transitions using logical operators or standard if statements.
Common Patterns:
- Standard Function: Use
if statements to check the current state and execute side effects before calling .enter(). - Logical Chaining: Use
&& to create concise transitions that only execute .enter() if a condition (like .is()) is met. - Guard Functions: Implement custom boolean functions to act as guards within your logic chains.
/* Pattern 1: Standard imperative function */
export const enterGameplay = () => {
if (!GameState.is("menu")) return
initializeGameplay()
GameState.enter("gameplay")
}
/* Pattern 2: Concise logical chaining */
export const returnToTitle = () =>
GameState.is("gameplay") && GameState.enter("title")
/* Pattern 3: Using custom guard functions */
const canStartGame = () => { /* returns boolean */ }
export const startGame = () =>
GameState.is("menu") && canStartGame() && GameState.enter("title")