-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
368 lines (279 loc) · 10.5 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
const fs = require("fs");
const cmd = require('node-cmd');
const crypto = require('crypto');
const bodyParser = require('body-parser');
const deepcopy = require("deepcopy");
const Game = require("./game/game.js");
const powers = require("./game/player.js");
var globals = require("./game/globals.js");
const express = require('express');
const app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.use(express.static("public"));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
});
const onWebhook = (req, res) => {
let hmac = crypto.createHmac('sha1', process.env.SECRET);
let sig = `sha1=${hmac.update(JSON.stringify(req.body)).digest('hex')}`;
if (req.headers['x-github-event'] === 'push' && sig === req.headers['x-hub-signature']) {
cmd.run('chmod 777 ./git.sh');
cmd.run('./git.sh', (err, data) => {
if (data) {
console.log(data);
}
if (err) {
console.log(err);
}
})
cmd.run('refresh');
}
return res.sendStatus(200);
}
app.post('/git', onWebhook);
// Health check
app.head('/health', function (req, res) {
res.sendStatus(200);
});
var string = fs.readFileSync('data/save.json');
var data = JSON.parse(string);
// console.log(data);
var games = {};
function saveData(obj) {
var string = JSON.stringify(obj);
fs.writeFile('data/save.json', string, finished);
function finished(err) { if (err != null) console.log(err) };
console.log("Data Saved");
};
function choose(choices) {
console.log(choices);
var index = Math.floor(Math.random() * choices.length);
return choices[index];
}
function randomID(length) {
// Declare all characters
let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
// Pick characers randomly
let str = '';
for (let i = 0; i < length; i++) {
str += chars.charAt(Math.floor(Math.random() * chars.length));
}
return str;
}
function compressMap(map) {
var rows = [];
var empty = 0;
for (var row of map) {
var r = "";
for (var tile of row) {
if (tile === -1) {
empty += 1;
} else {
if (empty) r += String(empty);
empty = 0;
r += (tile === -2 ? "W" : String.fromCharCode(tile + 65));
}
}
if (empty) r += String(empty);
empty = 0;
rows.push(r);
}
return rows.join("/");
}
io.on('connection', (socket) => {
var game;
var prePlay;
console.log('a user connected');
socket.emit("message", "Succesfully connected as user " + socket.id);
socket.emit("public games", Object.values(globals.games).filter(e => !e.isPrivate).length);
function generateSettingsValidity() {
if (!game) return;
return Object.keys(game.settings).reduce(function(result, key) {
result[key] = game.settingsConditions[key](game.settings[key] ? game.settings[key] : game.defaults[key]) && !isNaN(game.settings[key]);
return result;
}, {});
}
async function testForGameStart() {
if (!game.order.map(e => game.players[e]).filter(e => !e.ready).length && game.order.length > 1) {
await game.startGame();
io.in(game.id).emit("message", "Game has started with players " + game.order.map(e => game.players[e].username).join(", "));
if (game.withPowers) {
game.waitingForChoice = game.order.map(e => true);
io.in(game.id).emit("message", "Waiting for everyone to choose their power...");
var sockets = await io.in(game.id).fetchSockets();
for (var s of sockets) if (game.order.includes(s.id)) s.emit("select power");
} else {
game.initialMap = compressMap(game.map);
}
return true;
}
return false;
}
socket.on('join', (username, room) => {
if (game) return;
if (typeof(room) === "string") {
if (!room.length) { room = choose(Object.keys(globals.games).filter(e => !globals.games[e].isPrivate)) }
if (!globals.games[room]) { console.log("Unknown game ID " + room); return; }
socket.join(room);
game = globals.games[room];
} else {
var ID = randomID(5);
socket.join(ID);
game = globals.games[ID] = new Game(io, ID, socket.id, data);
console.log("New game at ID " + ID);
}
game.players[socket.id] = new powers.Player(game, username, socket.id);
if (game.turn == -1 && game.order.length < 6) {
game.order.push(socket.id);
} else {
socket.emit("spectate", true);
}
socket.emit("login");
socket.emit("message", "Joined as " + username + " to room " + game.id);
io.in(game.id).emit("message", username + " connected 👋");
});
socket.on("login", () => {
game.sendPlayerList();
socket.emit("update gamestate", {map: game.map, layer: game.layer, turn: game.turm, round: game.round, settings: game.settings, defaults: game.defaults, valid: generateSettingsValidity(), moveList: game.moveList, powers: Object.values(powers).map(e => { var temp = new e(); return {key: e.name, emoji: temp.emoji, name: temp.name, description: temp.description} })});
socket.emit("private", game.isPrivate);
socket.emit("powers state", game.withPowers);
socket.emit("timer", game.timerType);
});
socket.on('message', (message) => {
if (!game) return;
var msg = "[" + game.players[socket.id].username + "] " + message;
socket.emit("message", msg);
var send = true;
if (message.substring(0, 1) == "!") send = false;
if (send) socket.in(game.id).emit("message", msg);
});
socket.on('ready', async (state) => {
if (!game) return;
if (game.turn != -1) return;
if (!game.order.includes(socket.id)) return;
game.players[socket.id].ready = state;
io.in(game.id).emit("message", game.players[socket.id].username + " is " + (!state ? "not ready ❌" : "ready ✅"));
if (!await testForGameStart()) {
socket.emit("ready", state);
}
game.sendPlayerList();
});
socket.on('power selected', async (key) => {
if (!game) return;
if (!game.order.includes(socket.id)) return;
if (!game.waitingForChoice.length) return;
if (!game.waitingForChoice[game.order.indexOf(socket.id)]) return;
if (!powers[key]) return;
var replacement = new powers[key](game, game.players[socket.id].username, socket.id);
replacement.index = game.players[socket.id].index;
replacement.score = game.players[socket.id].score;
game.players[socket.id] = replacement;
game.waitingForChoice[game.order.indexOf(socket.id)] = false;
if (!game.waitingForChoice.filter(e => e).length) {
io.in(game.id).emit("message", "All powers have been chosen");
game.waitingForChoice = [];
for (var [i, [x, y]] of game.spawns.entries()) game.players[game.order[i]].spawn(game.map, x, y);
io.in(game.id).emit("update gamestate", {map: game.map});
game.initialMap = compressMap(game.map)
game.sendPlayerList();
}
socket.emit("power selected");
})
socket.on('spectate', async (state) => {
if (!game) return;
if (game.order.includes(socket.id) !== state) { socket.emit("spectate", state); return; } // Only go to spectator if in the players, and vice versa. Also correct if client desynced
if (!state && (game.order.length === 6 || game.turn !== -1)) return; // Only allow joining if there are less than 6 players and before the game starts
var state_string = "";
if (state) {
if (game.turn == -1) {
game.order.splice(game.order.indexOf(socket.id), 1);
state_string = " is now spectating 👻";
}
if (game.turn != -1 && game.players[socket.id].score) {
game.players[socket.id].forfeit();
state_string = " forfeited 💀";
}
} else {
game.order.push(socket.id);
state_string = " is now playing 🎮";
}
if (state_string.length) io.in(game.id).emit("message", game.players[socket.id].username + state_string);
socket.emit("spectate", !game.order.includes(socket.id));
if (game.turn === -1) await testForGameStart();
game.sendPlayerList();
});
socket.on('private', (state) => {
if (!game) return;
if (socket.id !== game.admin) return;
game.isPrivate = state;
io.in(game.id).emit("private", state);
io.emit("public games", Object.values(globals.games).filter(e => !e.isPrivate).length);
});
socket.on('powers', (state) => {
if (!game) return;
if (socket.id !== game.admin) return;
game.withPowers = state;
io.in(game.id).emit("powers state", state);
});
socket.on('timer', (state) => {
if (!game) return;
if (socket.id !== game.admin) return;
if (state < 0 || state > 2) return;
game.timerType = state;
io.in(game.id).emit("timer", state);
});
socket.on('settings', (settings) => {
if (!game) return;
if (socket.id !== game.admin) return;
if (game.turn !== -1) return;
for (var [key, value] of Object.entries(settings)) {
var name = key.slice(0, -5);
if (game.settings[name] !== undefined) { game.settings[name] = value.length ? Number(value) : null; }
}
console.log(game.settings);
io.in(game.id).emit("update gamestate", {settings: game.settings, valid: generateSettingsValidity()});
})
socket.on('input', (index, canPrePlay) => {
if (!game) return;
if (game.waitingForChoice.length) return;
if (game.turn === -1) return;
if (!game.order.includes(socket.id)) return;
if (index < 0) return;
if (game.order[game.turn] === socket.id && game.players[socket.id].prePlay === null) {
if (index < 4) {
game.players[socket.id].play(index);
} else if (index == 4 && game.players[socket.id].powerActive) {
io.in(game.id).emit("message", game.players[socket.id].activePower());
}
} else if (index < 4 && game.players[socket.id].prePlay !== index && canPrePlay) {
game.players[socket.id].prePlay = index;
socket.emit("message", "PRE PLAY: " + ["⬅️", "⬆️", "⬇️", "➡️", "🦸♂️"][index]);
}
});
socket.on('reconnecting', (attemptNumber) => {
socket.emit("message", "Reconnection attempt number " + attemptNumber + "...");
});
socket.on('disconnect', (reason) => {
console.log('user disconnected');
if (!game) return;
io.in(game.id).emit("message", game.players[socket.id].username + " disconnected (" + reason + ")");
if (game.turn !== -1) game.players[socket.id].forfeit();
if (game.order.includes(socket.id)) {
game.order.splice(game.order.indexOf(socket.id), 1);
if (game.waitingForChoice.length && game.waitingForChoice[game.order.indexOf(socket.id)]) game.waitingForChoice[game.order.indexOf(socket.id)] = false;
}
delete game.players[socket.id];
if (game.admin === socket.id) {
game.admin = Object.keys(game.players)[0];
if (game.admin) io.in(game.id).emit("message", game.players[game.admin].username + " is now the game admin");
}
game.sendPlayerList();
if (!game.admin) delete globals.games[game.id];
io.in(game.id).emit("update gamestate", {map: game.map, layer: game.layer});
});
});
http.listen(process.env.PORT || 3000, () => {
console.log('listening on *:' + (process.env.PORT || 3000));
});