-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
645 lines (592 loc) · 19.2 KB
/
Copy pathserver.js
File metadata and controls
645 lines (592 loc) · 19.2 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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server, {
transports: ['websocket'],
});
const next = require('next');
const cookie = require('cookie');
const wordSheet = require('./consts/wordSheet.js');
const fakeRooms = require('./consts/fakeRooms.js');
const fakeActiveGrids = require('./consts/fakeActiveGrids');
const fakeChatRooms = require('./consts/fakeChatRooms');
// const cluster = require('cluster');
// const numCPUs = require('os').cpus().length;
// for scaling if we need more CPU cores
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({ dev });
const nextHandler = nextApp.getRequestHandler();
// fake DB - probably don't need a db
// ======
// globals
// ======
const MAX_PLAYERS = 12;
const RECONNECTION_TIME = dev ? 5000 : 300000; // in ms
const CHAT_LENGTH = 150;
// an array of all users
const users = [];
const usersConnected = [];
// active rooms
const rooms = dev ? fakeRooms : {};
// roomId: {
// id: string,
// host: username,
// players: {
// [userName]: points (number)
// },
// inProgress: boolean
// full: boolean
// privateRoom?: boolean
// chameleonSeeClues?: boolean
// pointsForGuessing?: boolean
// anonymousVoting: boolean
// clueTimer: boolean
// }
// grid by room
const active_grids = dev ? fakeActiveGrids : {};
// roomId: {
// grid: string[],
// gridTitle: string,
// keyWord: string,
// chameleon: username,
// gridSelect: string | 'random'
// boardIsClickable: boolean
// playerShowsClue: username
// players: {
// [username]: {
// clue: string,
// clueReady: boolean,
// vote: string,
// },
// },
// };
const chat_rooms = dev ? fakeChatRooms : { Lobby: [] };
// roomId: [
// {
// username: string,
// message: string,
// timestamp: timestamp,
// },
// ];
// array of grid titles
const gridTitles = Object.keys(wordSheet) || [];
const gridTitlesLength = gridTitles.length;
// ======================
// socket.io
// ======================
io.on('connection', function (socket) {
const cookies = socket.handshake.headers.cookie ? cookie.parse(socket.handshake.headers.cookie) : {};
// locals
let username = cookies.playerName || undefined;
let roomId = cookies.roomId || undefined;
if (username && !userNameExists(username)) {
users.push(username);
}
if (username && usersConnected.indexOf(username) === -1) {
usersConnected.push(username);
}
if (roomId && active_grids[roomId]) {
socket.join(roomId);
}
socket.emit('connected', { playersOnline: users, connected: true, username });
// exit room
function exitRoom() {
socket.to(roomId).emit('updateRoom', { roomState: rooms[roomId] });
socket.leave(roomId);
if (rooms[roomId] && Object.keys(rooms[roomId].players).length < 1) {
delete rooms[roomId];
delete active_grids[roomId];
if (chat_rooms[roomId]) {
delete chat_rooms[roomId];
}
io.emit('moreRooms', rooms);
}
roomId = undefined;
}
function removePlayer() {
if (roomId !== undefined) {
removeUserFromRoom(username, roomId, socket);
}
if (username !== undefined) {
removeUserFromArr(username, users);
username = undefined;
}
if (roomId !== undefined) {
exitRoom();
}
}
// disconnect
socket.on('removePlayer', removePlayer);
socket.on('disconnect', function () {
// remove from usersConnected array immediately
removeUserFromArr(username, usersConnected);
// give a timeout
setTimeout(() => {
// if they didn't reconnect in that time... axe 'em
if (usersConnected.indexOf(username) < 0) {
removePlayer();
}
}, RECONNECTION_TIME);
});
// leaveroom event
socket.on('leaveRoom', function () {
removeUserFromRoom(username, roomId, socket);
exitRoom();
});
socket.on('requestuser', function (requestedUsername) {
// console.log('A user requested sign up: ' + requestedUsername);
if (userNameExists(requestedUsername)) {
socket.emit('signUpError', 'The name you selected is already taken');
return;
}
username = requestedUsername;
users.push(username);
socket.emit('acceptuser', { username, playersOnline: users, rooms });
});
socket.on('requestRoom', function (preferences) {
const { requestedRoom } = preferences;
// host new room
if (rooms[requestedRoom] === undefined) {
// console.log(username + ' is requesting a new room: ' + requestedRoom);
const { gridSelect, privateRoom, chameleonSeeClues, pointsForGuessing, anonymousVoting, clueTimer } = preferences;
const newGrid = gridSelect === 'random' ? randomGrid() : { gridTitle: gridSelect, grid: wordSheet[gridSelect] };
rooms[requestedRoom] = {
id: requestedRoom,
host: username,
players: {
[username]: 0,
},
privateRoom,
chameleonSeeClues,
pointsForGuessing,
anonymousVoting,
clueTimer,
};
active_grids[requestedRoom] = {
gridSelect,
grid: newGrid.grid,
gridTitle: newGrid.gridTitle,
keyWord: '',
chameleon: '',
playerShowsClue: '',
boardIsClickable: false,
players: {
[username]: {
clue: '',
clueReady: false,
vote: '',
},
},
};
chat_rooms[requestedRoom] = [];
roomId = requestedRoom;
socket.join(roomId);
io.in(roomId).emit('updateRoom', { roomState: rooms[roomId], gameState: active_grids[roomId] });
socket.emit('acceptJoinGame', requestedRoom);
io.emit('moreRooms', rooms);
} else if (rooms[requestedRoom] && Object.keys(rooms[requestedRoom].players).length >= MAX_PLAYERS) {
// rooms are full
socket.emit(
'toaster',
{ title: 'Error', message: 'The room you requested is full', type: 'error' },
{ key: 'moreRooms', rooms }
);
return;
} else if (rooms[requestedRoom] && active_grids[requestedRoom]) {
// join a rom
roomId = requestedRoom;
rooms[roomId].players[username] = 0;
active_grids[roomId].players[username] = {
clue: '',
clueReady: false,
vote: '',
};
if (Object.keys(rooms[requestedRoom].players).length === MAX_PLAYERS) {
rooms[roomId].full = true;
}
socket.join(roomId);
io.in(roomId).emit('updateRoom', { roomState: rooms[roomId], gameState: active_grids[roomId] });
socket.emit('acceptJoinGame', requestedRoom);
}
});
// host starts the game
socket.on('startGame', function () {
const currentGrid = active_grids[roomId];
const currentRoom = rooms[roomId];
if (!currentRoom || !currentGrid) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
const newGrid =
currentGrid.gridSelect === 'random' ? randomGrid() : { gridTitle: currentGrid.gridTitle, grid: currentGrid.grid };
const players = Object.keys(currentGrid.players);
const chameleon = getRandomValue(players);
const restOfPlayers = players.filter((player) => player !== chameleon);
rooms[roomId].inProgress = true;
active_grids[roomId].grid = newGrid.grid;
active_grids[roomId].gridTitle = newGrid.gridTitle;
active_grids[roomId].boardIsClickable = false;
active_grids[roomId].playerShowsClue = currentRoom.chameleonSeeClues ? getRandomValue(restOfPlayers) : '';
active_grids[roomId].keyWord = getRandomValue(currentGrid.grid);
active_grids[roomId].chameleon = chameleon;
active_grids[roomId].players = players.reduce(
(prev, cur) => ({
...prev,
[cur]: {
clue: '',
clueReady: false,
vote: '',
},
}),
{}
);
io.in(roomId).emit('updateRoom', { roomState: rooms[roomId], gameState: active_grids[roomId] });
});
// Game ends. Add the points
// PLAYER OPTIONS
socket.on('updatePlayerOption', function (options) {
if (!active_grids[roomId] || !username || !active_grids[roomId].players[username]) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
options.forEach(({ optionName, value }) => {
active_grids[roomId].players[username][optionName] = value;
});
io.in(roomId).emit('updateRoom', { gameState: active_grids[roomId] });
});
// vote for which player you think the chameleon is
socket.on('updateVote', function (playerVote) {
const currentGrid = active_grids[roomId];
if (!currentGrid || !username || !active_grids[roomId].players[username]) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
active_grids[roomId].players[username].vote = playerVote;
const allVotesCast = Object.keys(active_grids[roomId].players).every(
(player) => !!active_grids[roomId].players[player].vote
);
// update vote
if (!allVotesCast) {
io.in(roomId).emit('updateRoom', { gameState: active_grids[roomId] });
return;
}
const chameleonEscapes = didChameleonEscape(active_grids[roomId]);
// if he doesn't escape, the chameleon has a chance at 1 point
if (!chameleonEscapes) {
io.in(roomId).emit(
'toaster',
{
title: 'Found!',
message: `The chameleon was found! ${currentGrid.chameleon} now gets a chance to pick the correct clue.`,
type: 'success',
},
{ key: 'chameleonFound' }
);
active_grids[roomId].boardIsClickable = true;
io.in(roomId).emit('updateRoom', { gameState: active_grids[roomId] });
return;
}
// end game and add scores
rooms[roomId].inProgress = false;
Object.keys(rooms[roomId].players).forEach((player) => {
if (currentGrid.chameleon === player) {
// chameleon gets 2 points
rooms[roomId].players[player] = rooms[roomId].players[player] + 2;
return;
}
// if you voted for the chameleon, even though he escaped, you get a point
if (rooms[roomId].pointsForGuessing && active_grids[roomId].players[player].vote === currentGrid.chameleon) {
rooms[roomId].players[player] = rooms[roomId].players[player] + 1;
}
});
io.in(roomId).emit('updateRoom', { roomState: rooms[roomId], gameState: active_grids[roomId] });
io.in(roomId).emit(
'toaster',
{
title: 'Escaped',
message: `The chameleon has escaped! Congrats to ${currentGrid.chameleon} and better luck next time for everyone else.`,
type: 'info',
},
{ key: 'chameleonEscaped' }
);
});
socket.on('chameleonGuesses', function (word) {
const currentGrid = active_grids[roomId];
const currentRoom = rooms[roomId];
if (!currentGrid || !username) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
const { chameleon } = currentGrid;
if (word === currentGrid.keyWord) {
io.in(roomId).emit(
'toaster',
{
title: 'Correct',
message: `The chameleon guessed the CORRECT word. Congrats to ${chameleon} and better luck next time for everyone else.`,
type: 'success',
},
{ key: 'correctWord' }
);
rooms[roomId].players[chameleon] = currentRoom.players[chameleon] + 1;
} else {
io.in(roomId).emit(
'toaster',
{
title: 'Wrong',
message: `The chameleon guessed the WRONG word. ${chameleon} guessed ${word}. +1 for everyone else.`,
type: 'error',
},
{ key: 'wrongWord' }
);
Object.keys(currentRoom.players).forEach((player) => {
if (chameleon !== player) {
// everyone but the chameleon gets a point
rooms[roomId].players[player] = currentRoom.players[player] + 1;
return;
}
});
}
active_grids[roomId].boardIsClickable = false;
rooms[roomId].inProgress = false;
io.in(roomId).emit('updateRoom', { roomState: rooms[roomId], gameState: active_grids[roomId] });
});
// HOST OPTIONS
socket.on('kickPlayer', function (playerName) {
if (!rooms[roomId]) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
io.in(roomId).emit(
'toaster',
{ title: 'Kicked Player', message: `Player ${playerName} was kicked from the room`, type: 'moreInfo' },
{ key: 'kickPlayer', playerName }
);
});
socket.on('changeGrid', function (gridSelect) {
if (!active_grids[roomId]) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
if (gridSelect !== 'random') {
active_grids[roomId].grid = wordSheet[gridSelect];
active_grids[roomId].gridTitle = gridSelect;
}
active_grids[roomId].gridSelect = gridSelect;
active_grids[roomId].keyWord = '';
active_grids[roomId].chameleon = '';
io.in(roomId).emit('updateRoom', { gameState: active_grids[roomId] });
});
socket.on('changeRoomOptions', function ({ name, value }) {
if (!rooms[roomId]) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
rooms[roomId][name] = value;
io.in(roomId).emit('updateRoom', { roomState: rooms[roomId] });
});
socket.on('resetScores', function () {
const currentGrid = active_grids[roomId];
const currentRoom = rooms[roomId];
if (!currentRoom || !currentGrid) {
io.in(roomId).emit('toaster', { title: 'Room Closed', message: '', type: 'moreInfo' }, { key: 'roomClosed' });
return;
}
const players = Object.keys(currentRoom.players);
active_grids[roomId].boardIsClickable = false;
rooms[roomId].inProgress = false;
rooms[roomId].players = players.reduce(
(prev, cur) => ({
...prev,
[cur]: 0,
}),
{}
);
active_grids[roomId].players = players.reduce(
(prev, cur) => ({
...prev,
[cur]: {
clue: '',
clueReady: false,
vote: '',
},
}),
{}
);
io.in(roomId).emit('updateRoom', { roomState: rooms[roomId], gameState: active_grids[roomId] });
});
socket.on('chatMessage', function ({ message, type, headerName }) {
const chatRoom = chat_rooms[headerName];
if (!chatRoom) {
chat_rooms[headerName] = [];
}
if (chat_rooms[headerName].length >= CHAT_LENGTH) {
chat_rooms[headerName].shift();
}
const chatRoomLength = chat_rooms[headerName].length;
const recentChat = chat_rooms[headerName][chatRoomLength - 1] || {};
const same = recentChat.username === username || recentChat.prevUser === username;
const chatMessage = {
message,
timestamp: Date.now(),
};
if (same) {
chatMessage.prevUser = username;
} else {
chatMessage.username = username;
}
if (type) {
chatMessage.type = type;
}
chat_rooms[headerName].push(chatMessage);
if (roomId === headerName) {
io.in(headerName).emit('updateChat', chat_rooms[headerName]);
} else {
io.emit('updateLobbyChat', chat_rooms[headerName]);
}
});
});
nextApp.prepare().then(() => {
app.get('/rooms', (req, res) => {
// res.json(rooms);
res.redirect(301, 'https://www.find-the-fox.com/');
});
app.get('/getRoom/:roomId', (req, res) => {
// const room = rooms[req.params.roomId];
// if (room) {
// res.json(room);
// } else {
// res.json(null);
// }
res.redirect(301, 'https://www.find-the-fox.com/');
});
app.get('/getActiveGrid/:roomId', (req, res) => {
// const grid = active_grids[req.params.roomId];
// if (grid) {
// res.json(grid);
// } else {
// res.json(null);
// }
res.redirect(301, 'https://www.find-the-fox.com/');
});
app.get('/getChatRoom/:roomId', (req, res) => {
// const chatRoom = chat_rooms[req.params.roomId];
// if (chatRoom) {
// res.json(chatRoom);
// } else {
// res.json(null);
// }
res.redirect(301, 'https://www.find-the-fox.com/');
});
app.get('*', (req, res) => {
// return nextHandler(req, res);
res.redirect(301, 'https://www.find-the-fox.com/');
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
// =========
// functions
// =========
// random integer choice from 0:N-1
function getRandomChoice(N) {
return Math.floor(Math.random() * N);
}
function getRandomValue(arry) {
let arr = arry || [];
return arr[getRandomChoice(arr.length)];
}
// remove a user from an array
function removeUserFromArr(username, array) {
const index = array.indexOf(username);
// if we found a use remove them
if (index > -1) {
array.splice(index, 1);
}
}
// removes users from objects
function removeUserFromRoom(username, roomId, socket) {
if (rooms[roomId]) {
delete rooms[roomId].players[username];
const players = Object.keys(rooms[roomId].players);
if (rooms[roomId].host === username && players.length > 0) {
// assign new host
const newHost = getRandomValue(players);
rooms[roomId].host = newHost;
io.in(roomId).emit(
'toaster',
{
title: 'Host Left',
message: `A new host has been assigned: ${newHost}`,
type: 'moreInfo',
},
{ key: 'hostLeft' }
);
}
}
if (active_grids[roomId]) {
delete active_grids[roomId].players[username];
const players = Object.keys(active_grids[roomId].players);
if (active_grids[roomId].chameleon === username && players.length > 0) {
// restart game if chameleon leaves
rooms[roomId].inProgress = false;
io.in(roomId).emit(
'toaster',
{
title: 'Chameleon Left',
message: 'Host needs to start a new game to get a new chameleon.',
type: 'moreInfo',
},
{ key: 'chameleonLeft' }
);
}
}
}
// is a username available?
function userNameExists(username) {
return users.indexOf(username) > -1;
}
// get a random grid
function randomGrid() {
const gridTitle = gridTitles[getRandomChoice(gridTitlesLength)];
return {
gridTitle: gridTitle,
grid: wordSheet[gridTitle],
};
}
// did the chameleon escape
function didChameleonEscape(currentGrid) {
// if all votes are cast count up the points
let chameleonEscapes = false;
// count up votes
const votes = {};
const players = Object.keys(currentGrid.players);
players.forEach((player) => {
const vote = currentGrid.players[player].vote;
if (votes[vote]) {
votes[vote]++;
} else {
votes[vote] = 1;
}
});
// find the highest vote
let highestNum = 0;
const highestVote = Object.keys(votes).reduce((prev, cur) => {
if (votes[prev] === votes[cur]) {
highestNum = 'tie';
return prev;
}
if (votes[prev] > votes[cur]) {
highestNum = votes[prev];
return prev;
}
highestNum = votes[cur];
return cur;
}, highestNum);
if (highestVote !== currentGrid.chameleon || highestNum === 'tie') {
chameleonEscapes = true;
}
return chameleonEscapes;
}