unibutton/index.js
2024-10-06 09:47:52 -04:00

77 lines
No EOL
2.1 KiB
JavaScript

import express from "express";
import expressW from "express-ws";
import Game from "./game.js";
import NPC from "./common/npc.js";
import Player from "./common/player.js";
var app = express();
expressW(app);
var game = new Game();
game.init();
app.use('/crypto.js', express.static('./common/crypto.js'));
app.use('/js', express.static('./common'));
app.use(express.static('./static'));
app.ws('/', function (ws, req) {
game.ws.push(ws);
let player = new Player(false, true, game);
let playerI = game.entities.length;
game.entities[playerI] = player;
ws.active = true;
ws.ent = player;
// This will only work under NGINX.
console.log(`Player ${player.you} joined under IP ${req.headers["x-real-ip"]}`)
ws.on('message', function message(msg) {
let data = {};
try {
data = JSON.parse(msg);
} catch (err) {
console.log(err);
data = [];
}
let newEnt = game.entities[playerI];
let { you } = newEnt;
let props = player.legalProps;
for (let i in props) {
let prop = data[i];
let typed = (typeof prop);
let keys = Object.keys(prop);
let isC = (typed === 'object' && keys[0] == 'x' && keys[1] == 'y' && keys.length == 2 && typeof prop.x == 'number' && typeof prop.y == 'number');
if (typed !== 'string' && typed !== 'number' && typed !== 'boolean' && typed !== 'undefined' && !isC) {
console.warn(`Player ${you} attempted to send an invalid packet ${props[i]}`)
continue;
}
newEnt[props[i]] = data[i];
}
let you2 = newEnt.you;
if (you != you2) {
console.log(`Player ${you} now identifies as ${you2}`);
}
if (newEnt.ref) {
console.log(`Player ${you2} discovered this game from ${newEnt.ref}`);
newEnt.ref = undefined;
}
})
ws.on('close', function () {
console.log(`Player ${game.entities[playerI].you} left`);
ws.active = false;
player.health = -1;
})
});
app.listen(process.env.PORT || 3069);