Set the Islands

Learn how to set islands in the game.

We'll cover the following

Mark the islands as set

Once players are done moving their islands around, they need to mark their islands as a set in place. The Channel only needs to pass an atom that represents the player down to Game.set_islands/2 and pattern match on the result to send the right response.

A player successfully setting his islands is something we want both players to know about, so we use broadcast!/3 to respond when Game.set_islands/2 succeeds. If it fails, we want to let only that player know, so we use a :reply tuple.

To make it easier for any front-end code to display all the islands once they are set successfully, we will also have to send a :reply tuple with the full map of the islands. We send this only to the caller since we would not want the opponent to see this.

def handle_in("set_islands", player, socket) do
  player = String.to_existing_atom(player)
  case Game.set_islands(via(socket.topic), player) do
    {:ok, board} ->
      broadcast! socket, "player_set_islands", %{player: player}
      {:reply, {:ok, %{board: board}}, socket}
    _ -> {:reply, :error, socket}
  end
end

Note: Run the app below and open the SPA link in two separate browser tabs. Run the following commands as instructed.

Get hands-on with 1200+ tech skills courses.