Add a Second Player

Learn how to add a second player.

We'll cover the following

Add another player

To add a second player, we just need to pass that player’s name to the Game.add_player/2 function along with the via tuple that maps to the game PID.

We want both players to know about successfully adding a second player. However, if we fail to add the second player, only that player needs to know. This is a case where we can use broadcast!/3 on success and :reply tuple if something goes wrong.

Fortunately, we have an easy way to derive the via tuple and address the right game process. The socket.topic will always be a string that begins with “game:” and ends with the first player’s name. We can do a little binary pattern matching to extract just the name. We only need this player’s name to get the via tuple from Game.via_tuple/1:

defp via("game:" <> player), do: Game.via_tuple(player)

With that information, let’s define a new handle_in/3 clause for the "add_player" action:

def handle_in("add_player", player, socket) do
  case Game.add_player(via(socket.topic), player) do
    :ok ->
      broadcast! socket, "player_added", %{message: "New player just joined: " <> player}
      {:noreply, socket}
    {:error, reason} ->
      {:reply, {:error, %{reason: inspect(reason)}}, socket}
    :error -> {:reply, :error, socket} end
end

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

Get hands-on with 1400+ tech skills courses.