Guess the Coordinates
Explore how to implement the guess_coordinate feature within a Phoenix Channel using Elixir. Learn to pattern match tuple responses to broadcast game updates, manage errors with reply tuples, and coordinate client-server interactions for a multiplayer game scenario. This lesson helps you understand real-time communication handling alongside persistent state management in an Elixir web application.
We'll cover the following...
For this final piece, we need to pass a player and a coordinate into Game.guess_coordinate/3. We should show the result of a successful guess to both players, so we broadcast those. If a guess fails, we return a :reply tuple.
This is exactly what we’ve done for the past few handle_in/3 clauses, but this one has a twist. The response we get back from Game.guess_coordinate/3 will be a tuple, but we need to use a map for our brodcast’s payload. This means we’ll need to do a little pattern matching to destructure the tuple and build it back up again as a map:
def handle_in("guess_coordinate", params, socket) do
%{"player" => player, "row" => row, "col" => col} = params
player = String.to_existing_atom(player)
case Game.guess_coordinate(via(socket.topic), player, row, col) do
{:hit, island, win} ->
result = %{hit: true, island: island, win: win}
broadcast! socket, "player_guessed_coordinate",
%{player: player, row: row, col: col, result: result}
{:noreply, socket}
{:miss, island, win} ->
result = %{hit: false, island: island, win: win}
broadcast! socket, "player_guessed_coordinate",
%{player: player, row: row, col: col, result: result}
...