-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
318 lines (277 loc) · 9.27 KB
/
server.js
File metadata and controls
318 lines (277 loc) · 9.27 KB
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
import { createServer } from "http";
import express from "express";
import next from "next";
import { Server } from "socket.io";
import {
START,
PLAYERS,
START_REQUEST,
SCORE_INFO,
ROUND_DELAY,
ROUND_INFO,
ROUND_START,
ROUND_END,
GUESS,
PLAYERS_UPDATE,
ROUND_INTERLUDE,
GUESS_MADE,
GUESS_UPDATE,
GAME_END,
} from "./socket-messages.js";
import { CronJob } from "cron";
const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handler = app.getRequestHandler();
// See socket-types.ts
let multiplayerData = {};
let multiplayerBookkeeping = {};
let timeoutBookkeeping = {};
function utcSecondsSinceEpoch() {
const now = new Date();
const utcMilllisecondsSinceEpoch =
now.getTime() + now.getTimezoneOffset() * 60 * 1000;
const utcSecondsSinceEpoch = Math.round(utcMilllisecondsSinceEpoch / 1000);
return utcSecondsSinceEpoch;
}
function cleanupGames() {
for (var k of Object.keys(timeoutBookkeeping)) {
// If it has been more than 5 minutes since the game was last restarted clear its data.
if (timeoutBookkeeping[k] + 60 * 5 < utcSecondsSinceEpoch()) {
delete timeoutBookkeeping[k];
delete multiplayerBookkeeping[k];
delete multiplayerData[k];
}
}
}
// Runs every 3 minnutes
const cleanupJob = CronJob.from({
cronTime: "*/3 * * * *",
onTick: () => {
cleanupGames();
},
start: true,
});
// Runs daily
const dailySelectionJob = CronJob.from({
cronTime: "0 0 * * *",
onTick: async () => {
fetch(`http://${process.env.NEXT_PUBLIC_SITE_URL}/api/cron`).then(res => console.log("Job selection cron job ran:" + res)).catch(err => console.err("Job selection cron job ran: " + err))
},
start: true,
});
function generateGameCode(length = 8) {
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let result = "";
do {
result = "";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
} while (multiplayerData.hasOwnProperty(result));
return result;
}
const MAX_ROUNDS = 6; // Number of rounds in the game.
app.prepare().then(() => {
const server = express();
const httpServer = createServer(server);
const io = new Server(httpServer, {
cors: {
origin: `http://${process.env.NEXT_PUBLIC_SITE_URL}`,
},
});
async function roundStartSequence(code) {
let roundInfoBody = await fetch(
`http://${process.env.NEXT_PUBLIC_SITE_URL}/api/data/multiplayer`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(multiplayerBookkeeping[code].previouslySelected),
}
);
let roundInfo = await roundInfoBody.json();
// Update list of previously selected countries.
multiplayerBookkeeping[code].previouslySelected.push(roundInfo.country);
multiplayerBookkeeping[code].population = roundInfo.population;
// console.log("Selected round info for game", roundInfo);
io.to(code).emit(ROUND_INFO, roundInfo);
setTimeout(() => {
io.to(code).emit(ROUND_START, "");
// console.log("Sent start round request");
}, ROUND_DELAY);
}
const socketServer = io.on("connection", (socket) => {
const code = socket.handshake.query.code;
// Join the game room socket
socket.join(code);
socket.on("disconnect", () => {
// console.log("Client disconnected");
});
socket.on(START_REQUEST, async (code) => {
if (multiplayerBookkeeping[code].started) {
return;
}
multiplayerBookkeeping[code].started = true;
timeoutBookkeeping[code] = utcSecondsSinceEpoch();
io.to(code).emit(START, ""); // Tell the other nodes that game has started
roundStartSequence(code); // Fetch ROUND_INFO and call ROUND_START
});
socket.on(ROUND_END, () => {
if (multiplayerBookkeeping[code].roundEnded) {
return;
}
// Round number update to next round.
multiplayerBookkeeping[code].roundNumber++;
multiplayerBookkeeping[code].roundEnded = true;
// Scoring
const answer = multiplayerBookkeeping[code].population;
let game = multiplayerData[code];
let roundResults = [];
Object.keys(game).forEach((user) => {
if (game[user].guessInfo === null) {
roundResults.push([user, Number.MAX_VALUE]);
} else {
roundResults.push([user, Math.abs(game[user].guessInfo[0] - answer)]);
}
});
roundResults.sort((a, b) => a[1] - b[1]); // Sort in increasing order by absolute value distance from answer.
let bestDifferential = Number.MIN_VALUE;
let rank = 0;
let maxPoints = roundResults.length; // Number of users in the game.
let tieBuildup = 0;
// Push scores to the sorted array.
for (let index = 0; index < roundResults.length; index++) {
let i = roundResults[index];
let differential = i[1];
if (differential > bestDifferential) {
bestDifferential = differential;
i.pop();
i.push(maxPoints - rank);
tieBuildup = 0;
} else if (differential == bestDifferential) {
tieBuildup++;
i.pop();
i.push(maxPoints - rank + tieBuildup);
} else {
console.error(
"Algorithm for score calculation found unsorted scores"
);
}
rank++;
}
// Calculate information about total points accumulation of each user.
for (const i of roundResults) {
let userName = i[0];
let score = i[1];
multiplayerData[code][userName].points += score;
}
// Next round initiation sequence.
const SCORE_MODAL_TIME_MS = 5000;
setTimeout(() => {
multiplayerBookkeeping[code].roundEnded = false;
if (multiplayerBookkeeping[code].roundNumber > MAX_ROUNDS) {
// Game over
io.to(code).emit(GAME_END, "");
multiplayerBookkeeping[code] = {
previouslySelected: [],
roundNumber: 1,
started: false,
population: 0,
roundEnded: false,
};
multiplayerData[code] = {};
} else {
Object.keys(game).forEach((user) => {
game[user].guessInfo = null;
});
io.to(code).emit(
ROUND_INTERLUDE,
multiplayerBookkeeping[code].roundNumber
);
roundStartSequence(code); // Fetch ROUND_INFO and call ROUND_START
}
}, SCORE_MODAL_TIME_MS);
io.to(code).emit(PLAYERS_UPDATE, multiplayerData[code]); // Send updated point tallies and guessInfo.
io.to(code).emit(SCORE_INFO, roundResults); // Send sorted names/scores.
});
socket.on(GUESS, ([name, guessInfo]) => {
multiplayerData[code][name].guessInfo = guessInfo;
// console.log(
// "recorded best guess for code: " +
// code +
// ", name: " +
// name +
// ", guess: " +
// guessInfo
// );
});
socket.on(GUESS_MADE, (guess) => {
io.to(code).except(socket.id).emit(GUESS_UPDATE, guess); // Don't need to tell a user their own guess so we use except().
});
});
server.post(`/api/multiplayer/create`, (req, res) => {
const code = generateGameCode();
multiplayerData[code] = {};
multiplayerBookkeeping[code] = {
previouslySelected: [],
roundNumber: 1,
started: false,
population: 0,
roundEnded: false,
};
timeoutBookkeeping[code] = utcSecondsSinceEpoch();
res.status(201).json({ code }).end();
});
// Custom JSON parser because can't use express json parser middleware as this leads to Next.JS double parsing
server.post("/api/multiplayer/join", async (req, res) => {
let rawData = "";
req.on("data", (chunk) => {
rawData += chunk;
});
req.on("end", () => {
try {
let body = JSON.parse(rawData);
const code = body.code;
const name = body.name;
if (!multiplayerData.hasOwnProperty(code)) {
res.status(401).send(`Invalid game code provided: ${code}`);
return;
} else if (multiplayerBookkeeping[code].started) {
res
.status(401)
.send(
"Game has already started, please wait for it to end and then join."
);
return;
}
if (multiplayerData[code].hasOwnProperty(name)) {
res
.status(401)
.send(
`User with this username (${name}) already exists in game: ${code}`
);
return;
}
// Update data store
multiplayerData[code][name] = { guessInfo: null, points: 0 };
// Send list of users currently in game, including themselves
io.to(code).emit(PLAYERS, multiplayerData[code]);
res.status(200).end();
} catch (error) {
res.status(400).json({ error: "Invalid JSON" }).end();
}
});
});
server.all("*", (req, res) => handler(req, res));
httpServer
.once("error", (err) => {
console.error(err);
process.exit(1);
})
.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});