Connect the Channel to the Game

Learn how to connect to the Channel of the game.

Herewe begin to do the real work of getting our new game Channel talking to the game server. We build out new clauses of handle_in/3 that correspond to the public interface functions we wrote for IslandsEngine.Game. We pick the right communication strategy for each action and continue to check our work at each step, both in the browser consoles and in IEx.

The mechanics of making these connections are very easy. When we’re done, all the actions a player can take in the game will be exposed on the web through a Channel interface.

For all these new actions, we follow the same pattern we use for the "hello" function. We define a new clause of handle_in/3 that calls directly to the game server, define a function in the browser console that pushes a message to that clause, call the function, and check the response.

Now that we’re talking to the game server, though, we have the opportunity to check the game server state before and after we call the function in the console to make sure the action worked.

We’re ready to go, and we begin with initializing a new game.

Starting a new game

This is where we begin to expose the actual game to the web. We start with a clause of handle_in/3 that will match on the "new_game" action. Within this function, we directly call into the GameSupervisor.start_game/1 function to start the game and report back on the success or failure to start the GenServer.

We only need the first player’s name to start a new game. We decided in this chapter that the first player’s name will also be the subtopic of the channel. Because of this, we don’t need to pass in the player’s name to start the game. We can derive it from the topic stored on the socket struct.

Since there will be only one player at this point, we need to respond only to that one player. Sending back a :reply tuple fits the bill:

def handle_in("new_game", _payload, socket) do
  "game:" <> player = socket.topic
  case GameSupervisor.start_game(player) do
    {:ok, _pid} ->
      {:reply, :ok, socket}
    {:error, reason} ->
      {:reply, {:error, %{reason: reason}}, socket}

Note: Run the app below and open the SPA link in a separate browser tab. Run the below commands as directed.

Get hands-on with 1200+ tech skills courses.