unibutton/index.js

95 lines
No EOL
2.5 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";
import initDb from "./db.js";
let db = await initDb();
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.get('/leaderboard', async function (ws, req) {
let scores = game.scores || [];
req.send(scores.map((x,i) => `#${i+1}: ${x[0]} [${x[1]}: ${x[2]}]`).join('\n'));
})
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;
ws.ip = req.headers["x-real-ip"];
// This will only work under NGINX.
console.log(`Player ${player.you} joined under IP ${ws.ip}`)
ws.on('message', function message(msg) {
let data = {};
try {
data = JSON.parse(msg);
} catch (err) {
console.log(err);
data = [];
}
let type = data[0];
if (type == 'AUTH') {
game.authUser(ws,data[1]);
return;
}
data.splice(0, 1);
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);