Position the Islands

Understand the details of setting an island’s coordinates.

Position the islands

Positioning islands requires a player, an island key, and the upper-left coordinate’s row and column value. This is an action that needs to be secret and only for the eyes of the player setting their island coordinate. Giving this information away is giving the game away.

As we define a new handle_in/3 clause to do this, we use a :reply tuple, so that only the player setting their island’s coordinates will see the response.

The "position_island" message originates in JavaScript. JavaScript doesn’t have an atom type, so we send the player and island key-value over as strings.

This means we need to convert them to atoms in the handle_in/3 function before we pass them into the game server.

Atoms are really appropriate in the Elixir world but don’t exist in JavaScript. We’re okay doing these translations here because this is a boundary of the system. There won’t be any other way to interact with the game engine from the web.

def handle_in("position_island", payload, socket) do
  %{"player" => player, "island" => island, "row" => row, "col" => col} = payload
  player = String.to_existing_atom(player)
  island = String.to_existing_atom(island)
  case Game.position_island(via(socket.topic), player, island, row, col) do
    :ok -> {:reply, :ok, 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.