DEV Community

Sushant Bajracharya
Sushant Bajracharya

Posted on

1

Building a game server in elixir

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.

:)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay