Guess a Coordinate
Explore how to implement coordinate guessing in a stateful game using Elixir's GenServer and OTP. Understand managing player turns, validating inputs, updating nested game state with functional pipelines, and applying game rules to handle hits, misses, and win conditions within concurrent processes.
We'll cover the following...
Allow the players to guess coordinates
Guessing coordinates is the most important action in the game. In order to process a guess, we need to know which player is guessing. We also need to know the row and column values the player is guessing.
We start with a client function, guess_coordinate/4, that takes those values. This wraps a GenServer.call/2 with a tuple representing the four arguments and the action. We can see this here:
def guess_coordinate(game, player, row, col) when player in @players, do:
GenServer.call(game, {:guess_coordinate, player, row, col})
One of the tricky things to remember about guessing is that players guess against their opponent’s board. We’ve written a convenience function to get the key of a player’s opponent. From there, we get the opponent’s board with player_board/1.
defp opponent(:player1), do: :player2
defp opponent(:player2), do: :player1
We need to check a ...