DEV Community

loading...

Building a game server in elixir

Sushant Bajracharya
My key strengths: Discipline and Focus
・2 min read

I am not an expert so take this post with a grain of salt like every other posts of mine.

https://github.com/sushant12/snake_ladder/tree/v0.2.0

Okay, now that it is out of the way let me tell u what I think a game server is first. I think that a game server is a process that keeps the state of the game and their implementation depends on the type game itself.

As a kid, I used to play snake and ladders a lot. So, I built one but with minimal rules and two players only.I am not going to go through the code one by one , what I would like to tell you is what approach I took to build it.

Since I am building a 2P game, I have to keep track of who is what. So, whoever visits the root url is "Player 1" because a random token and a foreman=true is appended to the url. Player 2 will have just the random token in their url.

When someone visits the root url, I am treating it as start of a new tournament which will start a new "GameServer" which is a GenServer process. The "GameServer" is a child of DynamicSupervisor which was started with "mix phx.server". The state is kept in sync between the connected players via phoenix pubsub.

I know that the game will need to have structures so that's why the "game" and "player" struct. The "game" struct would store the list of players, dice state, game token and current players turn. The "player" struct stores the player name and their position. The "game" struct has functions to help manipulate/update itself. For eg: updating the dice state when user rolls a dice.

I have used liveview to dynamically show the changes in the UI. I do need to show some animations like rolling a dice when clicked on "roll", moving the piece, etc for which I will use js hooks.

So, that's about it for now. I have couple more things that I want to implement like cleaning off zombie game servers, notifying user when a player leaves the game, etc. I guess when I finish implementing it, it will be a time for new blog.

:)

Discussion (0)