papercats/server.js

65 lines
2.0 KiB
JavaScript
Raw Normal View History

2019-03-27 09:53:43 -04:00
//https://github.com/socketio/socket.io/blob/master/examples/chat/index.js
const express = require("express");
const app = express();
const path = require("path");
2020-02-03 22:10:32 -05:00
const os = require("os");
const chalk = require("chalk");
2019-03-27 09:53:43 -04:00
const server = require("http").createServer(app);
const io = require("socket.io")(server);
2020-07-22 08:56:04 -04:00
const { exec, fork } = require("child_process");
2019-02-21 11:19:33 -05:00
2020-07-24 03:11:35 -04:00
const config = require("./config.json");
2020-03-04 22:54:21 -05:00
config.dev ? exec("npm run build-dev") : exec("npm run build");
2019-02-21 11:19:33 -05:00
if (!(config.port >= 0 && config.port < 65536 && config.port % 1 === 0)) {
console.error("[ERROR] `port` argument must be an integer >= 0 and < 65536. Default value will be used.");
2019-03-27 09:53:43 -04:00
config.port = 8080;
2019-02-21 11:19:33 -05:00
}
2020-07-24 03:11:35 -04:00
const port = process.env.PORT || config.port;
2019-02-21 11:19:33 -05:00
server.listen(port, () => {
2020-02-03 22:10:32 -05:00
console.log(chalk.yellow("Server available on:"));
const ifaces = os.networkInterfaces();
Object.keys(ifaces).forEach(dev => {
ifaces[dev].forEach(details => {
if (details.family === 'IPv4') {
console.log((` http://${details.address}:${chalk.green(port.toString())}`));
}
});
});
console.log("Hit CTRL-C to stop the server");
});
//Routing
app.use(express.static(path.join(__dirname, "public")));
2020-04-16 06:44:34 -04:00
app.use("/font", express.static(path.join(__dirname, "node_modules/@fortawesome/fontawesome-free")));
2017-02-28 02:20:32 -05:00
2020-07-24 03:11:35 -04:00
const Game = require("./src/game-server");
const game = new Game();
io.set("transports", ["websocket"]);
2020-02-03 22:10:32 -05:00
io.on("connection", socket => {
socket.on("hello", (data, fn) => {
2019-01-15 10:42:15 -05:00
//TODO: error checking.
2019-02-22 00:22:21 -05:00
if (data.god && game.addGod(socket)) {
fn(true);
return;
}
2019-01-15 10:42:15 -05:00
if (data.name && data.name.length > 32) fn(false, "Your name is too long!");
2019-02-21 20:36:35 -05:00
else if (!game.addPlayer(socket, data.name)) fn(false, "There're too many platers!");
2019-01-15 10:42:15 -05:00
else fn(true);
});
socket.on("pings", (fn) => {
2019-01-15 10:42:15 -05:00
socket.emit("pongs");
socket.disconnect();
});
});
setInterval(() => {
2019-02-21 11:19:33 -05:00
game.tickFrame();
}, 1000 / 60);
2019-02-22 04:35:16 -05:00
2020-07-24 03:11:35 -04:00
for (let i = 0; i < parseInt(config.bots); i++) {
2020-07-22 08:56:04 -04:00
fork(path.join(__dirname, "paper-io-bot.js"), [`ws://localhost:${port}`], {
stdio: 'inherit'
2019-02-22 04:35:16 -05:00
});
}