forked from carlssonk/Emote-Racer
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
630 lines (486 loc) · 19.5 KB
/
index.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
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
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server, { perMessageDeflate: false });
const PORT = process.env.PORT || 8080;
const { v4: uuidv4 } = require('uuid');
const {
// Battle Royale Private
brUserJoinPrivate,
brGetUserPrivate,
brUserLeavePrivate,
brGetRoomUsersPrivate,
// Battle Royale Public
brUserJoinPublic,
brGetUserPublic,
brUserLeavePublic,
brGetRoomUsersPublic,
// ---------------------------
// 1v1 Battle Private
oneUserJoinPrivate,
oneGetUserPrivate,
oneUserLeavePrivate,
oneGetRoomUsersPrivate,
// 1v1 Battle Public
oneUserJoinPublic,
oneGetUserPublic,
oneUserLeavePublic,
oneGetRoomUsersPublic,
// ###########################
// Admin
brGetClientsByNamePrivate,
brGetClientsByNamePublic,
oneGetClientsByNamePublic,
oneGetClientsByNamePrivate,
} = require('./utils/users'); // Import user methods
const emotesServer = require("./utils/emotes"); // Import emotes
app.use(express.static(`${__dirname}/public`));
// #################################################################################
// ############################### SOCKET IO #######################################
// #################################################################################
// Array that contains ALL rooms, the only reason we use this list is so we can loop over rooms and find one that a user joins when he is searching for a public br game,
// hence we dont need array of romms in private mode cuz we dont need to loop over rooms to find one.
let brRoomsList = [];
let oneRoomsList = [];
let lobbyCountdownTimers = [];
io.on("connection", (socket) => {
// ########################################
// #### BATTLE ROYALE PUBLIC HANDLING #####
// ########################################
socket.on("quickPlay", (username, nameColor, profileImg) => {
// Check if there are any available empty slots in rooms
if(brRoomsList.some(e => e.userLength < 12) && brRoomsList.some(e => e.isPlaying === false)) {
// Sort rooms from high to low
const roomsDescending = brRoomsList.sort((a, b) => b.userLength - a.userLength);
// Loop through the array until we find an empty spot
for(let room of roomsDescending) {
if(room.userLength < 12 && room.isPlaying === false) {
room.userLength++;
joinRoom(room.id, room.userLength);
// Set timer
// handleLobbyTimer(room.id, room.userLength, socket.id)
break;
}
}
} else {
createNewRoom();
}
function joinRoom(roomId, userLength) {
// Set room
const room = {id: roomId, isPrivate: false}
// Create new user
const user = brUserJoinPublic(socket.id, username, nameColor, profileImg, room)
// Join user to roomId
socket.join(user.room.id)
// Send all users currently in the room to client side
io.to(user.room.id).emit("joinPublicLobby", brGetRoomUsersPublic(user.room.id), room, socket.id); // True statement refers to that this is a public lobby
// Start Lobby Timer
if(userLength === 3) startLobbyTimer(roomId)
// Start game if FULL
if(userLength === 12) {
clearTimeoutLobby(roomId) // Clears timeout
requestStartGamePublic(roomId) // Starts game
}
}
function createNewRoom() {
// Create new room
const room = {id: uuidv4(), isPrivate: false}
// Create new user
const user = brUserJoinPublic(socket.id, username, nameColor, profileImg, room)
// Set Public Room
brRoomsList.push({id: room.id, isPrivate: false, isPlaying: false, userLength: 1})
// Join user to roomId
socket.join(user.room.id);
// Send room to client so it can generate a link for other people to join
socket.emit('initPublicLobby', room);
}
})
// Starts a 20 seconds timer, so if lobby is not full, game will start automatically
function startLobbyTimer(roomId) {
this.clearTimeoutLobby = function(roomId) {
for(let i = 0; i < lobbyCountdownTimers.length; i++) {
if(lobbyCountdownTimers[i]._timerArgs[0] === roomId) {
clearTimeout(lobbyCountdownTimers[i])
lobbyCountdownTimers.splice(i, 1)
}
}
}
// Clear possible duplicates
clearTimeoutLobby(roomId);
lobbyCountdownTimers.push(setTimeout(() => requestStartGamePublic(roomId), 20000, roomId))
}
// ########################################
// #### BATTLE ROYALE PRIVATE HANDLING ####
// ########################################
socket.on("createPrivateLobby", (username, nameColor, profileImg) => {
// Create new room
const room = {id: uuidv4(), isPrivate: true, isPlaying: false}
// Create new user
const user = brUserJoinPrivate(socket.id, username, nameColor, profileImg, room)
// Join user to roomId
socket.join(user.room.id);
// Create a route for that room so people can join it by link
app.get(`/battle-royale/?${room.id}`, (req, res) => {
res.sendFile(`${__dirname}/public/index.html`);
});
// Send room to client so it can generate a link for other people to join
socket.emit('initPrivateLobby', room);
})
socket.on("requestJoin", (roomId, username, nameColor, profileImg) => {
const theRoom = brGetRoomUsersPrivate(roomId);
if(theRoom.length > 0) {
if(theRoom.length >= 12 || theRoom[0].room.isPlaying === true) {
socket.emit("roomIsFull")
// Room is full
return
}
}
// Set room
const room = {id: roomId, isPrivate: true, isPlaying: false}
// Create new user
const user = brUserJoinPrivate(socket.id, username, nameColor, profileImg, room)
// Join user to roomId
socket.join(user.room.id)
// Send all users currently in the room to client side
io.to(user.room.id).emit("joinPrivateLobby", brGetRoomUsersPrivate(roomId), room, socket.id);
})
socket.on("gameEndPrivate", (roomId) => {
const theRoom = brGetRoomUsersPrivate(roomId)
for(let i = 0; i < theRoom.length; i++) {
theRoom[i].room.isPlaying = false;
}
})
// ###########################
// #### GAME LOGIC WIRING ####
// ###########################
// Send signal to all users
socket.on("requestStartGamePrivate", (roomId) => {
const theRoom = brGetRoomUsersPrivate(roomId)
for(let i = 0; i < theRoom.length; i++) {
theRoom[i].room.isPlaying = true;
}
const randomEmoteIndex = Math.floor(Math.random() * emotesServer.length);
io.to(roomId).emit("startGame", emotesServer, randomEmoteIndex, theRoom);
})
function requestStartGamePublic(roomId) {
clearTimeoutLobby(roomId); // Clear lobby timer since we are now gonna start game
const theRoom = brGetRoomUsersPublic(roomId)
if(theRoom.length === 1) return;
const room = brRoomsList.findIndex(room => room.id === roomId)
brRoomsList[room].isPlaying = true;
const randomEmoteIndex = Math.floor(Math.random() * emotesServer.length);
io.to(roomId).emit("startGame", emotesServer, randomEmoteIndex, theRoom);
}
socket.on("handleEndRound", (roomId) => {
io.to(roomId).emit("handleEndRound");
});
socket.on("requestNextRound", (roomId, localEmotes) => {
const randomEmoteIndex = Math.floor(Math.random() * localEmotes.length);
io.to(roomId).emit("nextRound", randomEmoteIndex);
});
socket.on("userCorrect", (roomId, socketId, profileImg) => {
io.to(roomId).emit("userCorrect", socketId, profileImg);
})
socket.on("userWrong", (roomId, socketId) => {
io.to(roomId).emit("userWrong", socketId);
})
socket.on("userEliminated", (roomId, socketId, profileImg) => {
io.to(roomId).emit("userEliminated", socketId, profileImg);
})
// ########################################
// ####### 1 VS 1 PUBLIC HANDLING #########
// ########################################
socket.on("quickPlay1v1", (username, nameColor, profileImg) => {
// Check if there are any available empty slots in rooms
if(oneRoomsList.some(e => e.userLength < 2) && oneRoomsList.some(e => e.isPlaying === false)) {
// Find a room that the user can join
for(let room of oneRoomsList) {
if(room.userLength < 2 && room.isPlaying === false) {
room.userLength++;
joinRoom(room.id);
break;
}
}
} else {
createNewRoom();
}
function joinRoom(roomId) {
// Set room
const room = {id: roomId, isPrivate: false}
// Create new user
const user = oneUserJoinPublic(socket.id, username, nameColor, profileImg, room)
// Join user to roomId
socket.join(user.room.id)
// Send all users currently in the room to client side
io.to(user.room.id).emit("joinPublicLobby1v1", oneGetRoomUsersPublic(user.room.id), room, socket.id); // True statement refers to that this is a public lobby
}
function createNewRoom() {
// Create new room
const room = {id: uuidv4(), isPrivate: false}
// Create new user
const user = oneUserJoinPublic(socket.id, username, nameColor, profileImg, room)
// Set Public Room
oneRoomsList.push({id: room.id, isPrivate: false, isPlaying: false, userLength: 1})
// Join user to roomId
socket.join(user.room.id);
// Send room to client so it can generate a link for other people to join
socket.emit('initPublicLobby1v1', room);
}
})
// ########################################
// ####### 1 VS 1 PRIVATE HANDLING ########
// ########################################
socket.on("createPrivateLobby1v1", (username, nameColor, profileImg) => {
// Create new room
const room = {id: uuidv4(), isPrivate: true, isPlaying: false}
// Create new user
const user = oneUserJoinPrivate(socket.id, username, nameColor, profileImg, room)
// Join user to roomId
socket.join(user.room.id);
// Create a route for that room so people can join it by link
app.get(`/1v1/?${room.id}`, (req, res) => {
res.sendFile(`${__dirname}/public/index.html`);
});
// Send room to client so it can generate a link for other people to join
socket.emit('initPrivateLobby1v1', room);
})
socket.on("requestJoin1v1", (roomId, username, nameColor, profileImg) => {
const theRoom = oneGetRoomUsersPrivate(roomId)
if(theRoom.length > 0) {
if(theRoom.length >= 2 || theRoom[0].room.isPlaying === true) {
socket.emit("roomIsFull")
// Room is full
return
}
}
// Set room
const room = {id: roomId, isPrivate: true, isPlaying: false}
// Create new user
const user = oneUserJoinPrivate(socket.id, username, nameColor, profileImg, room)
// Join user to roomId
socket.join(user.room.id)
// Send all users currently in the room to client side
io.to(user.room.id).emit("joinPrivateLobby1v1", oneGetRoomUsersPrivate(roomId), room, socket.id);
})
// ###########################
// #### GAME LOGIC WIRING ####
// ###########################
socket.on("toggleReady1v1", (roomId) => {
io.to(roomId).emit("toggleReady1v1", socket.id);
});
// Send signal to all users
socket.on("requestStartGamePrivate1v1", (roomId) => {
let randomEmoteIndexArr = [];
for(let i = 0; i < emotesServer.length; i++) {
randomEmoteIndexArr.push(i)
}
shuffleArray(randomEmoteIndexArr)
io.to(roomId).emit("startGame1v1", emotesServer, randomEmoteIndexArr);
})
// Send signal to all users
socket.on("requestStartGamePublic1v1", (roomId) => {
const theRoom = oneGetRoomUsersPublic(roomId)
if(theRoom.length === 1) return;
const room = oneRoomsList.findIndex(room => room.id === roomId)
oneRoomsList[room].isPlaying = true;
let randomEmoteIndexArr = [];
for(let i = 0; i < emotesServer.length; i++) {
randomEmoteIndexArr.push(i)
}
shuffleArray(randomEmoteIndexArr)
io.to(roomId).emit("startGame1v1", emotesServer, randomEmoteIndexArr);
})
socket.on("userCorrect1v1", (roomId, socketId) => {
io.to(roomId).emit("userCorrect1v1", socketId);
})
// ###########################
// ### CLIENT DISCONNECTS ####
// ###########################
// If clicks on "NavLogo" or "Main Menu" whilst being in a multiplayer room
socket.on('disconnect', () => {
// Find what room the user is in, We have 4 possibilities, 1. BATTLE-ROYALE (PUBLIC), 2. BATTLE-ROYALE (PRIVATE), 3. 1VS1 (PUBLIC), 4. 1VS1 (PRIVATE)
let user = null;
let roomName = "";
for(let i = 0; i < 1; i++) {
user = brGetUserPublic(socket.id)
roomName = "battleRoyalePublic"
if(user !== undefined) break; // If user is in Battle Royale (Public) Break loop
user = oneGetUserPublic(socket.id)
roomName = "1v1Public"
if(user !== undefined) break; // If user is in 1vs1 (Public) Break loop
user = oneGetUserPrivate(socket.id)
roomName = "1v1Private"
if(user !== undefined) break; // If user is in 1vs1 (Private) Break loop, else we know the user is in Battle Royale (Private)
user = brGetUserPrivate(socket.id)
roomName = "battleRoyalePrivate"
}
if(user === undefined) return;
if(user !== null) {
socket.leave(user.room.id)
if(roomName === "battleRoyalePublic") {
spliceBrPublic(user.room.id, socket.id);
} else if(roomName === "1v1Public") {
splice1v1Public(user.room.id, socket.id);
} else if(roomName === "1v1Private") {
splice1v1Private(user.room.id, socket.id);
} else if(roomName === "battleRoyalePrivate") {
spliceBrPrivate(user.room.id, socket.id);
}
}
});
// If user click Play Again whilst being in a multiplayer room, leave the user from the room, dont remove the socket connection like we do above
socket.on("leaveUser", (roomName, roomId) => {
socket.leave(roomId)
if(roomName === "battleRoyalePublic") {
spliceBrPublic(roomId, socket.id);
} else if(roomName === "1v1Public") {
splice1v1Public(roomId, socket.id);
} else if(roomName === "1v1Private") {
splice1v1Private(roomId, socket.id);
} else if(roomName === "battleRoyalePrivate") {
spliceBrPrivate(roomId, socket.id);
}
});
// Send to client first before removing him in servers array list.
function spliceBrPublic(roomId, socketId) {
// TO CLIENT
io.to(roomId).emit("userLeave", socketId, brGetRoomUsersPublic(roomId))
// SERVER
decrementUserLength("br", roomId) // This room is public & have a public roomsListArray. So Remove length for that room
brUserLeavePublic(socketId)
// socket.leave(roomId)
}
function spliceBrPrivate(roomId, socketId) {
const theRoom = brGetRoomUsersPrivate(roomId);
// TO CLIENT
io.to(roomId).emit("userLeave", socketId, theRoom)
// SERVER
brUserLeavePrivate(socketId)
// the room is declared before we remove the user, so 1 means that there is no one in the room
if(theRoom.length === 1) spliceRoute("/battle-royale/?", roomId)
// socket.leave(roomId)
}
function splice1v1Public(roomId, socketId) {
// TO CLIENT
io.to(roomId).emit("userLeave1v1", socketId, oneGetRoomUsersPublic(roomId), "public")
// SERVER
decrementUserLength("1v1", roomId) // This room is public & have a public roomsListArray. So Remove length for that room
oneUserLeavePublic(socketId)
// socket.leave(roomId)
}
function splice1v1Private(roomId, socketId) {
const theRoom = oneGetRoomUsersPrivate(roomId);
// TO CLIENT
io.to(roomId).emit("userLeave1v1", socketId, theRoom, "private")
// SERVER
oneUserLeavePrivate(socketId)
// the room is declared before we remove the user, so 1 means that there is no one in the room
if(theRoom.length === 1) spliceRoute("/1v1/?", roomId)
// socket.leave(roomId)
}
function decrementUserLength(message, roomId) {
// Decrement userLength for thath room
// If userLength is 0, splice the room
if(message === "br") {
for(let i = 0; i < brRoomsList.length; i++) {
if(brRoomsList[i].id === roomId) {
brRoomsList[i].userLength--;
if(brRoomsList[i].userLength < 3) {
if(typeof clearTimeoutLobby === "function") clearTimeoutLobby(roomId) // Clear possible lobby timers
}
if(brRoomsList[i].userLength === 0) brRoomsList.splice(i, 1) // Lastly, if userLength === 0, splice room
}
}
}
// Decrement userLength for thath room
// If userLength is 0, splice the room
if(message === "1v1") {
for(let i = 0; i < oneRoomsList.length; i++) {
if(oneRoomsList[i].id === roomId) {
oneRoomsList[i].userLength--;
if(oneRoomsList[i].userLength === 0) oneRoomsList.splice(i, 1)
}
}
}
}
// Remove route when a private room is empty
function spliceRoute(pathname, roomId) {
const routes = [...app._router.stack].reverse();
for(let i = 0; i < routes.length; i++) {
if(typeof routes[i].route === "undefined") continue;
if(routes[i].route.path === `${pathname}${roomId}`) {
routes.splice(i, 1);
break;
}
}
}
// ##########################
// ##### ADMIN COMMANDS #####
// ##########################
socket.on("getClientsByName", (username, mode, passcode) => {
if(passcode === "6c6e4bf90683" && mode === "brPublic") io.to(socket.id).emit("getClientsByName", brGetClientsByNamePublic(username))
if(passcode === "6c6e4bf90683" && mode === "brPrivate") io.to(socket.id).emit("getClientsByName", brGetClientsByNamePrivate(username))
if(passcode === "6c6e4bf90683" && mode === "onePublic") io.to(socket.id).emit("getClientsByName", oneGetClientsByNamePublic(username))
if(passcode === "6c6e4bf90683" && mode === "onePrivate") io.to(socket.id).emit("getClientsByName", oneGetClientsByNamePrivate(username))
})
socket.on("emoteFlyby", (socketId, emote) => {
io.to(socketId).emit("emoteFlyby", emote)
})
socket.on("sendCoins", (socketId, amount, passcode) => {
if(passcode === "6c6e4bf90683" && typeof amount === "number") {
io.to(socketId).emit("sendCoins", amount)
}
})
socket.on("clearCoins", (socketId, passcode) => {
if(passcode === "6c6e4bf90683") {
io.to(socketId).emit("clearCoins")
}
})
})
// ##################
// ##### EXTRAS #####
// ##################
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
// Garbage collector
function garbageCollector() {
if(global.gc) {
global.gc()
} else {
process.exit();
}
}
setInterval(() => garbageCollector(), 1000 * 60)
// Performance BOOSTED START SCRIPT
// `node --nouse-idle-notification --expose-gc --max-old-space-size=8192 index.js`
// #################################################################################
// ################################## ROUTES #######################################
// #################################################################################
app.get('/battle-royale', function (req, res) {
res.sendFile(`${__dirname}/public/index.html`)
})
app.get("/battle-royale/:id", (req, res) => {
res.sendFile(`${__dirname}/public/index.html`);
});
app.get('/solo', function (req, res) {
res.sendFile(`${__dirname}/public/index.html`);
});
app.get('/1v1', function (req, res) {
res.sendFile(`${__dirname}/public/index.html`);
});
app.get('/1v1:id', function (req, res) {
res.sendFile(`${__dirname}/public/index.html`);
});
app.get('/profile', function (req, res) {
res.sendFile(`${__dirname}/public/index.html`);
});
app.get("*", function (req, res) {
res.redirect("/");
});
server.listen(PORT, () => {
console.log(`Listening on ${PORT}...`)
});