Position the Islands
Explore how to position islands in a multiplayer game using Phoenix Channels to maintain secret and secure state changes. Learn to convert JavaScript strings to Elixir atoms safely with String.to_existing_atom, manage game state with GenServer, and use channel.push to communicate between frontend and backend. Gain hands-on experience by setting up persistent connections, joining channels, and updating player boards while understanding Elixir's approach to real-time game state management.
We'll cover the following...
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" ...