Guess the Coordinates
Learn how to tackle guessing coordinates.
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}
{:noreply, socket}
:error ->
{:reply, {:error, %{player: player, reason: "Not your turn."}}, socket}
{:error, reason} ->
{:reply, {:error, %{player: player, reason: reason}}, socket}
end
end
IEx session
Get hands-on with 1400+ tech skills courses.