Online multiplayer code

Using some code from pumpkinhead’s multiplayer game I have made some code to help make your own multiplayer game.

To use it you can start by forking this repl (or make an account first).

Then you can follow instructions starting on line 21 to add variables to be sent from and to clients.
If you aren’t exactly sure what to do this repl has two variables x and y for you to see how to add your own.

Then click this button (in the circled area)

Then in box 1 put serverKey and in box 2 will be your server’s access code. Then click “Add new secret” to save it.
The serverKey is basically the password for a client to connect to the server, when it first joins the client will send its serverKey and it is only allowed to fully connect if it has the correct key. This is useful to make outdated clients unable to connect to the server.

Then in your wick project put this code below in the highest layer’s frame

window.ServerConnection = class {
    
    constructor (domain, data) {
        
        this.socket = new WebSocket(domain);
        this.connected = false;
        this.players = {};
        this.myId = null;
        this.connectionStatus = null;
        this.onInitData = data.onInitData || null;
        this.onUpdateData = data.onUpdateData || null;
        this.onInit = data.onInit;
        this.onClose = data.onClose;
        this.onUpdate = data.onUpdate;
        this.onJoin = data.onJoin;
        this.onQuit = data.onQuit;
        this.connectCode = data.connectCode;
        
        this.socket.onopen = () => {
            console.log("Websocket opened");
            this.connectionStatus = "opened";
        };
        
        this.socket.onerror = (err) => {
            console.error("Error opening socket", err);
            this.connectionStatus = "error";
            this.connected = false;
        };
        
        this.socket.onclose = (ev) => {
            console.log("Connection closed because: " + ev.reason);
            if (this.connectionStatus === "error") {
                this.connectionStatus = "closed/error";
            } else { this.connectionStatus = "closed"; }
            this.connected = false;
            this.onClose(ev.reason);
        };
        
        this.socket.onmessage = (msg) => {
            let dat = JSON.parse(msg.data);
            
            if (dat.type === "connect") {
                this.connected = true;
                this.connectionStatus = "connected";
                this.sendToSocket({type:"sendConnectCode",code:this.connectCode});
                return;
            }
            
            if (this.connected === false) {return}
            
            if (dat.type === "init") {
                this.connectionStatus = "finished";
                this.myId = dat.id;
                this.players[this.myId] = {id:this.myId};
                for (let i=0;i<dat.data.players.length;i++) {
                    this.players[dat.data.players[i].id] = {};
                    let player = this.players[dat.data.players[i].id];
                    for (data in dat.data.players[i]) {
                        player[data] = dat.data.players[i][data];
                    }
                    this.onInit(player);
                }
                if (this.onInitData !== null) {
                    this.onInitData(dat.data);
                }
                return;
            }
            
            if (this.connectionStatus !== "finished") {return}
            
            if (dat.type === "update") {
                
                for (let i=0;i<dat.data.players.length;i++) {
                    let player = this.players[dat.data.players[i].id];
                    if (this.myId === player.id) {continue;}
                    for (data in dat.data.players[i]) {
                        if (data === "id") {continue;}
                        player[data] = dat.data.players[i][data];
                    }
                    this.onUpdate(player);
                }
                if (this.onUpdateData !== null) {
                    this.onUpdateData(dat.data);
                }
                return;
            }
            
            if (dat.type === "player_connected") {
                if (dat.id !== this.myId) {
                    this.players[dat.id] = {};
                    this.players[dat.id].id = dat.id;
                    this.onJoin(this.players[dat.id]);
                }
                return;
            }
            
            if (dat.type === "player_disconnected") {
                this.onQuit(this.players[dat.id]);
                delete this.players[dat.id];
                return;
            }
        };
        
    }
    
    sendToSocket (data) {
        this.socket.send(JSON.stringify(data));
    }
    
    update (data) {
        if (this.connectionStatus === "finished") {this.sendToSocket({type:"update",data:data});}
    }
    
};

Then to create the server connection use code like this

const server = new ServerConnection(`ADDRESS`, {
    onInit : onInit, // function (player)
    onClose : onClose, // function (msg)
    onUpdate : onUpdate, // function (player)
    onJoin: onJoin, // function (player)
    onQuit: onQuit, // function (player)
    onInitData: onInitData, // function (data)
    onUpdateData: onUpdateData, // function (data)
    connectCode : "SERVER_KEY"
});

Replace ADDRESS with the address of your repl found here (run it first) but replace the https with wss

Replace SERVER_KEY with what you put in box 2 from here

Then insert before the const server... line the functions

onInit
let onInit = (player) => {
    
};

player is the player object with values from what you added to the server code
This function is called for each player in the server when you joined the server, you will want to use it to create the players on you client

onClose
let onClose = (msg) => {
    
};

msg is the message string from the server when an your connection closed/failed
This function is called when you lose or fail connection, useful for alerting the user of an error

onUpdate
let onUpdate = (player) => {
    
};

player is the player object with values from what you added to the server code
This function is called for each player in the server every update tick, you will want to use it to update the players on you client

onJoin
let onJoin = (player) => {
    
};

player is the player object with values from what you added to the server code
This function is called when a new player joins that is not you, you will want to use it to create the new player on your client

onQuit
let onQuit = (player) => {
    
};

player is the player object with values from what you added to the server code
This function is called when a player quits, you will want to use it to remove the player on your client

onInitData (not required)
let onInitData = (data) => {
    
};

data is the initiation data received from the server
This function is called when your client receives initiation data from the server, good for creating your player

onUpdateData (not required)
let onUpdateData = (data) => {
    
};

data is the update data received from the server
This function is called when your client receives update data from the server

This wick file can show you how you can use the above functions to make a multiplayer game
OnlineMultiplayerPreview2-22-2022_20-16-47.wick (3.0 KB)
And this repl is what is needed for it to work https://replit.com/@5omeone3lse/WickServerClassShowcase#index.js
note that I removed the address and server key

3 Likes

thnx someonelse
your contributions are allways well accepted!

how to send a chat message from player to server, and then broadcast it to all players?

TLDR,
a text chat

I dont know how it works, We have to atleast have someone that knows how to do it. Theres already one out there but it only appears to you.

i need help with the insert befor const server