Coding games using p5 is a tonne of fun, coding multiplayer games that you can get your mates to join in with, even better, coding multiplayer games where multiple rooms are required as it's so bloody popular, jackpot.
So if you're interested in just creating multiplayer games using p5 then I recommend you check out my blog How to code multiplayer games with p5! However, if you want to code multiplayer games and need separate rooms as your game is so damn popular, as you were.
I've coded up a few multiplayer games now, and a couple using p5.js and find myself in the unfortunate position of writing the same code, over and over. This boiler-plate code I've compiled into a nice little kick-starter repository, the contents of which I will go over in this blog.
The p5-multiplayer-game-starter-with-rooms is pretty much exactly what it claims to be, a repository to help you develop multiplayer games, it represents an opinionated approach to multiplayer game development using express, socket.io and p5.js.
- Clone the project
npm installin the root directory
npm startto get it running!
The project is pretty straightforward, it sets up a client
Player class and a server
Player. When the server player is created, that player is put into a room, the room-placement logic is very simple: if there are two or more players in a room it'll create a new room and place the player in it. This image from socket.io explains how the rooms work:
Every 16ms the server emits the current state of the game — in that particular room — to the client. If a new client joins the server a new
Player will be added to the game, it also automatically removes players when they leave the game. These are the standard features I frequently have to reproduce when creating a new multiplayer game, so I hope you find this as useful as I do!
Each client will be a player of your game, they all communicate with the server. The server will control all the game state, such as the position and the colour of the player. This information will be emitted to all of the clients in that particular room so that each client can render said player using p5.
Player 1 joins the game:
And it's as simple as that, of course this is just very basic code to put you in the right direction, you'll likely need something a little more elaborate when your game starts to blow up!
So there we go, what I recommend you do is having a play around with the repository, add some basic physics, get some interaction with the clients. This should give you the very basic building blocks of your next IO hit!
Thank you, if you like my rambling check out my personal blogging site at https://codeheir.com/