-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
492 lines (434 loc) · 13.9 KB
/
Copy pathserver.js
File metadata and controls
492 lines (434 loc) · 13.9 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
/** @module server */
const express = require('express');
const app = express();
const http = require('http');
const { Server } = require('socket.io');
const path = require('path')
const { randomInt } = require('crypto');
const stringSimilarity = require('string-similarity');
const POINTS = [20, 14, 9, 6, 4, 2, 1];
let lobbies = [];
const PORT = process.env.PORT || 5000;
const server = http.createServer(app);
app.use(express.static(path.join(__dirname, 'client', 'build')));
app.use(express.static(path.join(__dirname, 'docs', 'build')));
app.get('/', function(_req, res)
{
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
app.get('/docs', function(_req, res)
{
res.sendFile(path.join(__dirname, 'docs', 'build', 'index.html'));
});
const io = new Server(server);
io.on('connection', (socket) =>
{
/**
* Emits to everyone in the lobby except the origin.
* @function otherEmit
* @param {string} event - Event name.
* @param {*} args - Event arguments.
*/
function otherEmit(event, args)
{
if(args === undefined)
io.to(getLobbyRoom()).except(socket.id).emit(event);
else
io.to(getLobbyRoom()).except(socket.id).emit(event, args);
}
/**
* Emits to everyone in the lobby.
* @function roomEmit
* @param {string} event - Event name.
* @param {*} args - Event arguments.
*/
function roomEmit(event, args)
{
if(args === undefined)
io.to(getLobbyRoom()).emit(event);
else
io.to(getLobbyRoom()).emit(event, args);
}
/**
* Gets the id of this socket's lobby.
* @function getLobbyRoom
* @returns {string} Id of this socket's lobby.
*/
function getLobbyRoom()
{
return Array.from(socket.rooms)[1];
}
/**
* Gets this socket's lobby.
* @function getLobbyRoom
* @returns {Object} This socket's lobby.
*/
function getLobby()
{
return lobbies.find(l => l.players.some(p => p.id === socket.id));
}
/**
* Returns whether this socket is an admin.
* @function isAdmin
* @returns {boolean} Whether this socket is an admin.
*/
function isAdmin()
{
return getLobby() && getLobby().players[0].id === socket.id;
}
/**
* Returns whether this socket is on turn.
* @function isOnTurn
* @returns {boolean} Whether this socket is on turn.
*/
function isOnTurn()
{
return getLobby().players.find(p => socket.id === p.id).onTurn;
}
/**
* Transmits the newly set number of rounds by admin to others in the lobby.
* @function roundsChanged
* @param {number} rounds Number of rounds in a game.
*/
function roundsChanged(rounds)
{
if(isAdmin())
{
getLobby().rounds = rounds;
otherEmit('roundsChanged', rounds);
}
}
/**
* Transmits the newly set amount of times by admin to others in the lobby.
* @function timeChanged
* @param {number} time Amount of time for one turn.
*/
function timeChanged(time)
{
if(isAdmin())
{
getLobby().time = time;
otherEmit('timeChanged', time);
}
}
/**
* Transmits the newly set words by admin to others in the lobby.
* @function wordsChanged
* @param {string[]} words Array of words to choose from in the game.
*/
function wordsChanged(words)
{
if(isAdmin())
{
getLobby().words = words;
otherEmit('wordsChanged', words);
}
}
/**
* Tells all other sockets to join the game, if this socket is an admin.
* @function joinGame
*/
function joinGame()
{
if(isAdmin())
{
let lobby = getLobby();
lobby.inGame = true;
let index = randomInt(lobby.words.length);
lobby.currentWord = lobby.words[index];
otherEmit('joinGame');
}
}
/**
* Transmits the position where this socket started drawing to others in the lobby.
* @function startDrawing
* @param {Object} pos Position object containing x, y position where this socket started drawing.
*/
function startDrawing(pos)
{
if(isOnTurn())
{
roomEmit('startDrawing', pos);
}
}
/**
* Transmits the position where this socket is drawing to others in the lobby.
* @function draw
* @param {Object} pos Position object containing x, y position where this socket is drawing.
*/
function draw(pos)
{
if(isOnTurn())
{
roomEmit('draw', pos);
}
}
/**
* Transmits the newly set drawing color by the player on turn to others in the lobby.
* @function colorChanged
* @param {string} color Hex value of the new drawing color.
*/
function colorChanged(color)
{
if(isOnTurn())
{
otherEmit('colorChanged', color);
}
}
/**
* Transmits the newly set line width by the player on turn to others in the lobby.
* @function widthChanged
* @param {number} width The width of the brush.
*/
function widthChanged(width)
{
if(isOnTurn())
{
otherEmit('widthChanged', width);
}
}
/**
* Transmits the action of clearing the canvas by the player on turn to others in the lobby.
* @function clearCanvas
*/
function clearCanvas()
{
if(isOnTurn())
{
otherEmit('clearCanvas');
}
}
/**
* Sends a request to the admin for sending the data to the corresponding socket.
* @function turnDataRequested
* @param {string} socketId Id of the socket, that requested the data.
*/
function turnDataRequested(socketId)
{
io.to(getLobby().players[0].id).emit('turnDataRequested', socketId);
}
/**
* Sends the data recieved from the admin to the socket, that requested it.
* @function turnDataSent
* @param {*} data Object containing current turn time and picture data.
*/
function turnDataSent(data)
{
if(isAdmin())
{
let lobby = getLobby();
io.to(data.socketId).emit('turnDataSent', {timeCounter: data.timeCounter, word: lobby.currentWord.replace(/[^\s]/g, '_'), round: lobby.currentRound, pictureData: data.pictureData});
}
}
/**
* Checks whether the sender guessed the word, gives the points,
* calculates if the word is similar
* and transmits it to others in the lobby.
* @function messageSent
* @param {Object} message Object containing the message's raw contents.
*/
function messageSent(message)
{
let lobby = getLobby();
let player = lobby.players.find(p => p.id === socket.id);
let messageRaw = message.raw.trim().toUpperCase().normalize();
if(messageRaw.length > 40)
messageRaw = messageRaw.substring(0, 40);
let wordRaw = lobby.currentWord.trim().toUpperCase().normalize();
if(player.guessed)
{
for(let p of lobby.players)
{
if(p.guessed && p.id != socket.id)
{
io.to(p.id).emit('messageSent', message);
}
}
return;
}
else if(messageRaw === wordRaw)
{
player.guessed = true;
let points = POINTS[lobby.playersGuessed.length] || POINTS[POINTS.length - 1]
player.points += points;
player.pointsThisTurn = points;
lobby.playersGuessed.push(player.id);
roomEmit('playerGuessed', [socket.id, points]);
if(!lobby.players.some(p => !p.guessed))
{
endTurn();
}
return;
}
otherEmit('messageSent', message);
let similarity = stringSimilarity.compareTwoStrings(messageRaw, wordRaw);
if(similarity > .35)
{
roomEmit('playerNearGuess', message.raw)
}
}
/**
* Connects the socket to the desired lobby and transmit it to others in the lobby.
* If the lobby doesn't exist, create a new one.
* @function join
* @param {Object} data Object containing the newly joined player's nickname and lobby id.
*/
function join(data)
{
let lobby = lobbies.find(l => l.id === data.lobbyId)
if(!lobby)
{
lobby = {id: socket.id.substring(0, 16), inGame: false, players: [], currentPlayer: -1, rounds: 5, currentRound: 0, time: '90', words: ['Rukavice','Šnek','Měsíc','Žárovka','Kalendář','Zub','Jazyk','Voda'], currentWord: '', playersGuessed: []};
lobbies.push(lobby);
}
let nickname = data.nickname;
if(nickname.length > 16)
nickname = nickname.substring(0, 16);
let player = {id: socket.id, nickname: data.nickname, onTurn: false, ready: false, guessed: false, points: 0, pointsThisTurn: 0};
lobby.players.push(player);
let newLobby = {id: lobby.id, inGame: lobby.inGame, players: lobby.players, currentPlayer: lobby.currentPlayer, rounds: lobby.rounds, currentRound: lobby.currentRound, time: lobby.time, words: lobby.words, currentWord: lobby.currentWord};
io.to(lobby.id).emit('playerJoined', player);
io.to(socket.id).socketsJoin(lobby.id);
io.to(socket.id).emit('join', JSON.stringify(newLobby));
}
/**
* Marks this socket as ready.
* If all the sockets in a lobby are ready, the game starts.
* @function ready
*/
function ready()
{
let lobby = getLobby();
let index = lobby.players.findIndex(p => p.id === socket.id);
lobby.players[index].ready = true;
if(lobby.players.every(p => p.ready))
{
endTurn();
nextTurn();
}
}
/**
* Prepares all lobby variables for the next turn.
* Transmits the data about the next turn to others in the lobby.
*
* @function nextTurn
*/
function nextTurn()
{
let lobby = getLobby();
lobby.playersGuessed = [];
lobby.players.forEach(player =>
{
player.onTurn = false;
player.guessed = false;
player.pointsThisTurn = 0;
});
clearTimeout(lobby.timeout);
lobby.currentPlayer++;
if(lobby.currentPlayer >= lobby.players.length)
lobby.currentPlayer = 0;
if(lobby.currentPlayer == 0)
lobby.currentRound++;
if(lobby.currentRound > lobby.rounds)
{
endGame();
return;
}
let playerIndex = lobby.currentPlayer;
let wordIndex = randomInt(0, lobby.words.length);
let player = lobby.players[playerIndex];
player.onTurn = true;
player.guessed = true;
lobby.currentWord = lobby.words[wordIndex];
io.to(player.id).emit('newPlayerOnTurn', [playerIndex, lobby.currentWord]);
io.to(getLobbyRoom()).except(player.id).emit('newPlayerOnTurn', [playerIndex, lobby.currentWord.replace(/[^\s]/g, '_')]);
let preTurnTimeout = 5000;
lobby.timeout = setTimeout(() =>
{
roomEmit('startTurn');
lobby.timeout = setTimeout(() =>
{
endTurn();
}, lobby.time * 1000);
}, preTurnTimeout);
}
/**
* Transmits the end of the turn to the others in the lobby.
* Then starts a new turn.
* @function endTurn
*/
function endTurn()
{
let lobby = getLobby();
clearTimeout(lobby.timeout);
roomEmit('endTurn', lobby.currentWord);
let endTurnTimeout = 6000;
lobby.timeout = setTimeout(() =>
{
nextTurn();
}, endTurnTimeout);
}
/**
* Transmits the end of the game to the others in the lobby.
* Then sends everyone back to the lobby.
* @function endGame
*/
function endGame()
{
let lobby = getLobby();
roomEmit('endGame');
let leaderboardTime = 8000;
lobby.timeout = setTimeout(() =>
{
lobby.inGame = false;
lobby.currentPlayer = -1;
lobby.currentRound = 0;
lobby.playersGuessed = [];
lobby.players.forEach(player =>
{
player.ready = false;
player.points = 0;
});
roomEmit('restartGame');
}, leaderboardTime);
}
/**
* Removes a player from the lobby and transmits it to the others in the lobby.
* @function disconnecting
*/
function disconnecting()
{
let lobby = getLobby();
if(!lobby)
return;
let playerIndex = lobby.players.findIndex(p => p.id === socket.id);
lobby.players.splice(playerIndex, 1);
if(lobby.players.length == 0)
{
clearTimeout(lobby.timeout);
let lobbyIndex = lobbies.indexOf(lobby);
lobbies.splice(lobbyIndex, 1);
}
otherEmit('playerDisconnected', socket.id);
}
socket.on('roundsChanged', roundsChanged);
socket.on('timeChanged', timeChanged);
socket.on('wordsChanged', wordsChanged);
socket.on('joinGame', joinGame);
socket.on('draw', draw);
socket.on('startDrawing', startDrawing);
socket.on('colorChanged', colorChanged);
socket.on('clearCanvas', clearCanvas);
socket.on('widthChanged', widthChanged);
socket.on('turnDataRequested', turnDataRequested);
socket.on('turnDataSent', turnDataSent);
socket.on('messageSent', messageSent);
socket.on('join', join);
socket.on('ready', ready);
socket.on('nextTurn', nextTurn);
socket.on('disconnecting', disconnecting);
});
server.listen(PORT, () =>
{
console.log('Listening on port ' + PORT);
});