Search⌘ K

Player One’s Turn

Explore how to model a two-player game’s state transitions in Elixir by managing alternate player turns and detecting game-winning conditions. This lesson guides you through implementing state checks and transitions from a player's turn to the next or game over, using pattern matching and OTP Behaviours.

:player1_turn

Not all state transitions are one-way. State machines often need to revisit previous states based on events in the system. Taking turns in a game is a perfect example of this. In a two-person game, the state transitions back and forth between one player’s turn and the other until one of them wins.

We’re at the point where both players have set their islands, and the game is in :player1_turn. When it’s the first player’s turn, that player may guess a coordinate and may win the game. No other events are permissible.

When :player1 guesses a coordinate, the state should transition to :player2_turn. And if :player1 wins, the state should transition to :game_over. We’ll focus on the transition from :player1_turn to :player2_turn first.

...