DEV Community


Posted on

An Online Multiplayer Game Example

Hey everyone! It's been a little while, but here I am with a new project: a simple game server made entirely with Node.

Source code and docs here.

Let's go over the server script:


// HTTP Server

var express = require("express"); // Load the express package
var app = express(); // Create an app with express
var up = true; // Unused value... I'll remove it in the future.
var data = { // The cube's data.
    x: 0, // "X" position of the cube.
    y: 0 // "Y" position of the cube.

app.get("/updatePos", (req, res) => { // Create a listener for /updatePos
    res.json(data); // Return the cube's data.

app.get("/setPos/:x/:y", (req, res) =>  { // ^
    data.x = parseInt(req.params.x); // Sets the "X" position
    data.y = parseInt(req.params.y); // Sets the "Y" position
    res.status(200); // Sets the result status as a success
    res.json({data: "Hello, world!"}); // Just so it returns something.

app.listen(8080, () => { // Start listening.
    console.log("Hosted server at localhost:8080"); // Let the user know the server started

I explained each line of code briefly with comments so you can understand it a bit better. Also, don't forget to read the file so you know it's dependencies.

Have a nice day! :D

Top comments (0)