Online Multiplayer in NodeJS
LeonDoesCode (270)

Multiplayer

So you've decided to venture into the realms of Online Multiplayers. Why not? You can get all you friends involved in the projects you make, or just show it off to others. Well, either way, let's take a look at how we would make one.

Modules

Firstly, we are going to need some Modules to help us along the way. Let's see:

const express = require('express');
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);

That should do the trick! We have:

  • express to display the static site to the Clients
  • http to listen for new Clients
  • socket.io to listen for events the Clients make

Simples! So now that we know what we are working with, let's make this Game!

Client

Here are the HTML and CSS before we begin, as they aren't super important, I won't explain them too much:

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Online Game</title>

    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>

  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>

    <script src="/socket.io/socket.io.js"></script>
    <script src="script.js"></script>
  </body>
</html>

A good thing to not is that you should not forget the <script src="/socket.io/socket.io.js"></script>. this is super important!

style.css

html, body {
  position: absolute;

  margin: 0;
  padding: 0;

  top: 50%;
  left: 50%;

  transform: translate(-50%, -50%);

  background-color: rgb(50, 50, 50);
}

This just makes it look nice. It also fills the background with the same as the canvas, and center said canvas in the middle of the window.

I'd say that the Client is always best to work on first. The reason for this, is that you can begin to layout what you are going to be using. This means you know what you will need on the Server before you start writing it. Obviously you will be adding stuff later, but it's a great way to begin the project. So let's begin:

const socket = io();

Firstly, we want to get our Client socket to communicate with the Server. Now we can create the setup function:

/* Setup */
function setup() {
  // Create the canvas
  createCanvas(600, 600);
  // Remove outline on players
  noStroke();
};

This is nothing special. All we do is define our setup function and createCanvas() a 600x600 canvas. We also remove the outline around our players by using noStroke():

/* Update & Events */
// Create the movement keys
const W = 87;
const A = 65;
const S = 83;
const D = 68;

Next we define our W, A, S, and D keys. The numbers 87, 65, 83, and 68 refer to each key's code. A good way of finding out a key's code is by using this website. All you have to do is press the key you want to get the code of, the nice thing is that the favicon of the page will change to the code's number so that it easier to see when you switch tabs:

// Get the update from the server
socket.on("update", data => {});

Now we get into the nitty gritty. We create an event called update which we will talk more about in the Server section. This event will give us the Game's current data to update the Client-Side with. talking about that:

  // Set the background to 50
  background(50);

  // Check if the movement keys are pressed, if so then send an event
  if(keyIsDown(W)) socket.emit("move", W);
  if(keyIsDown(A)) socket.emit("move", A);
  if(keyIsDown(S)) socket.emit("move", S);
  if(keyIsDown(D)) socket.emit("move", D);

We change the background color to 50 using background(). We then check if either of W, A, S, and/or D is down, if so, we send an event to the Server called move. We also send the key with it. Next:

  // Draw each player
  for(let playerID of Object.keys(data.players)) {
    // Get the the player from the player's id
    let player = data.players[playerID];

    // Draw the player
    fill(player.color.r, player.color.g, player.color.b);
    rect(player.pos.x, player.pos.y, player.size, player.size);
  }

We get all of the ids for all the players in data.players, we then get the player for the id and show them on the canvas. This allows us to see all the players. But what about us?

I'm glad you asked! Well, we do draw ourselves here, we do it along with the others. Because all the updating is done Server-Side (which may change depending on how you implement it), the only thing we do is get movement events, and draw the players on the Client-Side.

This is it for the Client-Side of things. Super simple! So let's get onto the Server-Side of things!

Server

The server will now have to do a few things based on how we wrote the Client. These include:

  • Sending an update event to the Clients
  • Receiving move events from the Clients
  • Updating the players

Not too much, so let's get cracking! Oh, and we covered Socket.io in another tutorial, so I won't be diving to far in in this one:

app.use(express.static("public"));

We first want to make it so that the Client is given the Game website. Then we can:

/* Server */
// Movement keys
const W = 87;
const A = 65;
const S = 83;
const D = 68;

// The data
let data = {players:{}};

let width = 600;
let height = 600;

We define a few variables and constants. These include the movement keys from earlier, the data including the players, and the width and height. Not too much so far:

io.on("connection", socket => {
  // New player connected
  console.log("player connected");

  // Create new player
  data.players[socket.id] = {
    pos:{x:Math.random()*100, y:Math.random()*100},
    speed:2,
    size:16,
    color:{r:Math.random()*255, g:Math.random()*255, b:Math.random()*255}
  };

  socket.on("disconnect", () => {
    // Player  disconnected
    console.log("player disconnected");
    // Delete player
    delete data.players[socket.id];
  });
});

Firstly, we get the connection and disconnect events. When we get a connection event, we create a new player and give it the socket.id. On the disconnect event, we delete the player from data.players using the socket.id:

  // Movement event
  socket.on("move", key => {
    // Get the current player
    let player = data.players[socket.id];

    // Check which movement key was pressed, and move accordingly
    if(key == W) player.pos.y -= player.speed;
    if(key == A) player.pos.x -= player.speed;
    if(key == S) player.pos.y += player.speed;
    if(key == D) player.pos.x += player.speed;

    // Check if player is touching the boundry, if so stop them from moving past it
    if(player.pos.x > width - player.size) player.pos.x = width - player.size;
    if(player.pos.x < 0) player.pos.x = 0;
    if(player.pos.y > height - player.size) player.pos.y = height - player.size;
    if(player.pos.y < 0) player.pos.y = 0;
  });

Next we get the move event. In this event, we check to see if any of the movement keys are pressed. We do this, just in case the Client sends us something which is not a movement key, think of it as extra security. If one of the keys is pressed, we add or subtract the player.speed from the player.pos x or y. We then also check to see if the player is at one of the boundaries. If so, then we stop the player from passing it. That's it!

Conclusion

It's pretty easy when you look at it. You also have the extra security of having things done Server-Side which is nice. The player stuff could be done better, but works great for a little "test" online game. Hope it helps in your ventures!

Have a great day!

P.S
If you have any suggestions for tutorials, leave them in the comments and I'll be sure to have a look. If you like one in the comments, then give it an up vote to show that you want to see it. It makes my life so much more easier. Thanks in advance!

You are viewing a single comment. View All
LeonDoesCode (270)

@Zavexeon Coolio! I'll see what I can do!