-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
839 lines (712 loc) · 31.4 KB
/
server.js
File metadata and controls
839 lines (712 loc) · 31.4 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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const { Server } = require('socket.io');
const dev = process.env.NODE_ENV !== 'production';
// Always bind to 0.0.0.0 for container/cloud deployments
const hostname = '0.0.0.0';
const port = parseInt(process.env.PORT || '3000', 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
// In-memory game sessions storage
const gameSessions = new Map();
const playerSockets = new Map();
// Face-off questions by theme
const faceOffQuestions = {
'seven-wonders': [
{ id: 'sw-fo-1', question: 'Is the Great Pyramid of Giza the oldest of the Seven Wonders?', answer: true, category: 'seven-wonders' },
{ id: 'sw-fo-2', question: 'Was the Colossus of Rhodes made of gold?', answer: false, category: 'seven-wonders' },
{ id: 'sw-fo-3', question: 'Is the Great Wall of China visible from space with the naked eye?', answer: false, category: 'seven-wonders' },
{ id: 'sw-fo-4', question: 'Was the Lighthouse of Alexandria over 100 meters tall?', answer: true, category: 'seven-wonders' },
{ id: 'sw-fo-5', question: 'Is Machu Picchu located in Peru?', answer: true, category: 'seven-wonders' },
{ id: 'sw-fo-6', question: 'Was the Hanging Gardens of Babylon built by King Solomon?', answer: false, category: 'seven-wonders' },
{ id: 'sw-fo-7', question: 'Is the Taj Mahal a tomb?', answer: true, category: 'seven-wonders' },
{ id: 'sw-fo-8', question: 'Was the Statue of Zeus at Olympia made by Phidias?', answer: true, category: 'seven-wonders' },
{ id: 'sw-fo-9', question: 'Is Christ the Redeemer located in Argentina?', answer: false, category: 'seven-wonders' },
{ id: 'sw-fo-10', question: 'Was the Temple of Artemis destroyed by fire?', answer: true, category: 'seven-wonders' },
{ id: 'sw-fo-11', question: 'Is Petra located in Jordan?', answer: true, category: 'seven-wonders' },
{ id: 'sw-fo-12', question: 'Was the Mausoleum at Halicarnassus built for a Roman emperor?', answer: false, category: 'seven-wonders' },
],
'world-cup': [
{ id: 'wc-fo-1', question: 'Has Brazil won the most FIFA World Cups?', answer: true, category: 'world-cup' },
{ id: 'wc-fo-2', question: 'Was the first World Cup held in Brazil?', answer: false, category: 'world-cup' },
{ id: 'wc-fo-3', question: 'Did Pelé win 3 World Cups?', answer: true, category: 'world-cup' },
{ id: 'wc-fo-4', question: 'Has England won the World Cup more than once?', answer: false, category: 'world-cup' },
{ id: 'wc-fo-5', question: 'Was the 2022 World Cup held in Qatar?', answer: true, category: 'world-cup' },
{ id: 'wc-fo-6', question: 'Did Maradona score the "Hand of God" goal against England?', answer: true, category: 'world-cup' },
{ id: 'wc-fo-7', question: 'Has the World Cup always had 32 teams?', answer: false, category: 'world-cup' },
{ id: 'wc-fo-8', question: 'Did Germany win the 2014 World Cup?', answer: true, category: 'world-cup' },
{ id: 'wc-fo-9', question: 'Is the World Cup held every 2 years?', answer: false, category: 'world-cup' },
{ id: 'wc-fo-10', question: 'Has an African nation ever won the World Cup?', answer: false, category: 'world-cup' },
{ id: 'wc-fo-11', question: 'Did France win the 2018 World Cup?', answer: true, category: 'world-cup' },
{ id: 'wc-fo-12', question: 'Was Zinedine Zidane sent off in the 2006 World Cup final?', answer: true, category: 'world-cup' },
],
'space-travel': [
{ id: 'st-fo-1', question: 'Was Yuri Gagarin the first human in space?', answer: true, category: 'space-travel' },
{ id: 'st-fo-2', question: 'Has a human walked on Mars?', answer: false, category: 'space-travel' },
{ id: 'st-fo-3', question: 'Is the International Space Station visible from Earth?', answer: true, category: 'space-travel' },
{ id: 'st-fo-4', question: 'Did Apollo 13 land on the Moon?', answer: false, category: 'space-travel' },
{ id: 'st-fo-5', question: 'Is Pluto still classified as a planet?', answer: false, category: 'space-travel' },
{ id: 'st-fo-6', question: 'Was Neil Armstrong the first person to walk on the Moon?', answer: true, category: 'space-travel' },
{ id: 'st-fo-7', question: 'Is Venus hotter than Mercury?', answer: true, category: 'space-travel' },
{ id: 'st-fo-8', question: 'Did SpaceX send humans to space?', answer: true, category: 'space-travel' },
{ id: 'st-fo-9', question: 'Is Jupiter the largest planet in our solar system?', answer: true, category: 'space-travel' },
{ id: 'st-fo-10', question: 'Was Laika the dog the first animal in space?', answer: false, category: 'space-travel' },
{ id: 'st-fo-11', question: 'Does Saturn have more moons than Jupiter?', answer: true, category: 'space-travel' },
{ id: 'st-fo-12', question: 'Is the Sun a planet?', answer: false, category: 'space-travel' },
],
'maths-logic': [
{ id: 'ml-fo-1', question: 'Is Pi a rational number?', answer: false, category: 'maths-logic' },
{ id: 'ml-fo-2', question: 'Is 1 a prime number?', answer: false, category: 'maths-logic' },
{ id: 'ml-fo-3', question: 'Does 2 + 2 equal 4?', answer: true, category: 'maths-logic' },
{ id: 'ml-fo-4', question: 'Is the square root of 2 a rational number?', answer: false, category: 'maths-logic' },
{ id: 'ml-fo-5', question: 'Is zero an even number?', answer: true, category: 'maths-logic' },
{ id: 'ml-fo-6', question: 'Is infinity a number?', answer: false, category: 'maths-logic' },
{ id: 'ml-fo-7', question: 'Does every triangle have 180 degrees?', answer: true, category: 'maths-logic' },
{ id: 'ml-fo-8', question: 'Is 7 a prime number?', answer: true, category: 'maths-logic' },
{ id: 'ml-fo-9', question: 'Can you divide by zero?', answer: false, category: 'maths-logic' },
{ id: 'ml-fo-10', question: 'Is the Pythagorean theorem about circles?', answer: false, category: 'maths-logic' },
{ id: 'ml-fo-11', question: 'Is a googol larger than a billion?', answer: true, category: 'maths-logic' },
{ id: 'ml-fo-12', question: 'Does hexadecimal use base 16?', answer: true, category: 'maths-logic' },
],
'science-physics': [
{ id: 'sp-fo-1', question: 'Is water made of hydrogen and oxygen?', answer: true, category: 'science-physics' },
{ id: 'sp-fo-2', question: 'Does light travel faster than sound?', answer: true, category: 'science-physics' },
{ id: 'sp-fo-3', question: 'Is glass a liquid?', answer: false, category: 'science-physics' },
{ id: 'sp-fo-4', question: 'Did Einstein discover gravity?', answer: false, category: 'science-physics' },
{ id: 'sp-fo-5', question: 'Is absolute zero the coldest possible temperature?', answer: true, category: 'science-physics' },
{ id: 'sp-fo-6', question: 'Do electrons have a negative charge?', answer: true, category: 'science-physics' },
{ id: 'sp-fo-7', question: 'Is DNA found in all living cells?', answer: true, category: 'science-physics' },
{ id: 'sp-fo-8', question: 'Is gold heavier than silver?', answer: true, category: 'science-physics' },
{ id: 'sp-fo-9', question: 'Can sound travel through a vacuum?', answer: false, category: 'science-physics' },
{ id: 'sp-fo-10', question: 'Is the speed of light constant?', answer: true, category: 'science-physics' },
{ id: 'sp-fo-11', question: 'Did Marie Curie discover radioactivity?', answer: false, category: 'science-physics' },
{ id: 'sp-fo-12', question: 'Is helium lighter than air?', answer: true, category: 'science-physics' },
],
};
// Generate a random 6-character game code
function generateGameCode() {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code = '';
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
// Shuffle array
function shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
// Total available rooms (20 rooms now)
const TOTAL_ROOMS = 20;
const ROOMS_PER_GAME = 5;
// Get random room indices for a game (5 random rooms from 20)
function getRandomRoomIndices() {
const allIndices = Array.from({ length: TOTAL_ROOMS }, (_, i) => i);
const shuffled = shuffleArray(allIndices);
return shuffled.slice(0, ROOMS_PER_GAME);
}
// Get random face-off questions for a theme
function getRandomFaceOffQuestions(theme) {
const questions = faceOffQuestions[theme] || faceOffQuestions['science-physics'];
return shuffleArray(questions).slice(0, 10);
}
// Room order for each player (randomized)
const roomIds = ['seven-wonders', 'world-cup', 'space-travel', 'maths-logic', 'science-physics'];
// Get the actual room index from player's randomized order
function getActualRoomIndex(player) {
return player.roomOrder[player.currentRoomIndex] ?? player.currentRoomIndex;
}
// Find other players in the same actual room
function getPlayersInSameRoom(session, player) {
const playerActualRoom = getActualRoomIndex(player);
return session.players.filter(p =>
p.id !== player.id &&
p.isAlive &&
getActualRoomIndex(p) === playerActualRoom
);
}
app.prepare().then(() => {
const httpServer = createServer((req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
});
const io = new Server(httpServer, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
// Create a new game session
socket.on('create-game', ({ playerName, playerColor }) => {
const gameCode = generateGameCode();
const playerId = socket.id;
const session = {
code: gameCode,
hostId: playerId,
players: [{
id: playerId,
socketId: socket.id,
name: playerName,
color: playerColor,
position: { x: 15, y: 70 },
currentRoomIndex: 0,
roomOrder: getRandomRoomIndices(), // 5 random rooms from 20 total
score: 0,
wrongAnswers: 0,
isAlive: true,
completedItems: [],
isReady: true,
hasCompletedCurrentRoom: false,
}],
status: 'waiting', // waiting, playing, finished
createdAt: Date.now(),
maxPlayers: 4,
minPlayers: 1,
activeFaceOff: null,
};
gameSessions.set(gameCode, session);
playerSockets.set(socket.id, gameCode);
socket.join(gameCode);
socket.emit('game-created', {
gameCode,
session,
playerId,
});
console.log(`Game created: ${gameCode} by ${playerName}`);
});
// Start single player game (creates and auto-starts)
socket.on('start-single-player', ({ playerName, playerColor }) => {
const gameCode = generateGameCode();
const playerId = socket.id;
const session = {
code: gameCode,
hostId: playerId,
players: [{
id: playerId,
socketId: socket.id,
name: playerName,
color: playerColor,
position: { x: 15, y: 70 },
currentRoomIndex: 0,
roomOrder: getRandomRoomIndices(), // 5 random rooms from 20 total
score: 0,
wrongAnswers: 0,
isAlive: true,
completedItems: [],
isReady: true,
hasCompletedCurrentRoom: false,
}],
status: 'playing', // Start immediately in playing status
createdAt: Date.now(),
maxPlayers: 1,
minPlayers: 1,
activeFaceOff: null,
isSinglePlayer: true,
};
gameSessions.set(gameCode, session);
playerSockets.set(socket.id, gameCode);
socket.join(gameCode);
// Emit both game-created and game-started to start immediately
socket.emit('game-created', {
gameCode,
session,
playerId,
});
socket.emit('game-started', { session });
console.log(`Single player game started: ${gameCode} by ${playerName}`);
});
// Join an existing game
socket.on('join-game', ({ gameCode, playerName, playerColor }) => {
const session = gameSessions.get(gameCode.toUpperCase());
if (!session) {
socket.emit('join-error', { message: 'Game not found. Check the code and try again.' });
return;
}
if (session.status !== 'waiting') {
socket.emit('join-error', { message: 'Game has already started.' });
return;
}
if (session.players.length >= session.maxPlayers) {
socket.emit('join-error', { message: 'Game is full (max 4 players).' });
return;
}
// Check if color is taken
const colorTaken = session.players.some(p => p.color === playerColor);
if (colorTaken) {
socket.emit('join-error', { message: 'Color already taken. Choose a different color.' });
return;
}
const playerId = socket.id;
const newPlayer = {
id: playerId,
socketId: socket.id,
name: playerName,
color: playerColor,
position: { x: 15 + session.players.length * 10, y: 70 },
currentRoomIndex: 0,
roomOrder: getRandomRoomIndices(), // 5 random rooms from 20 total
score: 0,
wrongAnswers: 0,
isAlive: true,
completedItems: [],
isReady: false,
hasCompletedCurrentRoom: false,
};
session.players.push(newPlayer);
playerSockets.set(socket.id, gameCode);
socket.join(gameCode);
socket.emit('game-joined', {
gameCode,
session,
playerId,
});
// Notify all players in the session
io.to(gameCode).emit('player-joined', {
player: newPlayer,
session,
});
console.log(`${playerName} joined game: ${gameCode}`);
});
// Player ready toggle
socket.on('player-ready', ({ gameCode }) => {
const session = gameSessions.get(gameCode);
if (!session) return;
const player = session.players.find(p => p.socketId === socket.id);
if (player) {
player.isReady = !player.isReady;
io.to(gameCode).emit('session-updated', { session });
}
});
// Start the game (host only)
socket.on('start-game', ({ gameCode }) => {
const session = gameSessions.get(gameCode);
if (!session) return;
if (session.hostId !== socket.id) {
socket.emit('error', { message: 'Only the host can start the game.' });
return;
}
if (session.players.length < session.minPlayers) {
socket.emit('error', { message: `Need at least ${session.minPlayers} player(s) to start.` });
return;
}
const allReady = session.players.every(p => p.isReady);
if (!allReady) {
socket.emit('error', { message: 'All players must be ready to start.' });
return;
}
session.status = 'playing';
session.startedAt = Date.now();
io.to(gameCode).emit('game-started', { session });
console.log(`Game started: ${gameCode}`);
});
// Player movement
socket.on('player-move', ({ gameCode, position, direction }) => {
const session = gameSessions.get(gameCode);
if (!session || session.status !== 'playing') return;
const player = session.players.find(p => p.socketId === socket.id);
if (player && player.isAlive) {
player.position = position;
player.direction = direction;
// Broadcast to other players in the same room
socket.to(gameCode).emit('player-moved', {
playerId: player.id,
position,
direction,
});
}
});
// Player completed an item
socket.on('item-completed', ({ gameCode, itemId, score }) => {
const session = gameSessions.get(gameCode);
if (!session) return;
const player = session.players.find(p => p.socketId === socket.id);
if (player) {
if (!player.completedItems.includes(itemId)) {
player.completedItems.push(itemId);
}
player.score = score;
io.to(gameCode).emit('session-updated', { session });
}
});
// Player answered wrong
socket.on('wrong-answer', ({ gameCode, wrongAnswers }) => {
const session = gameSessions.get(gameCode);
if (!session) return;
const player = session.players.find(p => p.socketId === socket.id);
if (player) {
player.wrongAnswers = wrongAnswers;
if (wrongAnswers >= 3) {
player.isAlive = false;
io.to(gameCode).emit('player-ejected', {
playerId: player.id,
playerName: player.name,
reason: 'wrong_answers',
message: `${player.name} was ejected! Too many wrong answers.`,
});
}
io.to(gameCode).emit('session-updated', { session });
}
});
// Player completed a room - COMPETITIVE MECHANIC
socket.on('room-completed', ({ gameCode, nextRoomIndex }) => {
const session = gameSessions.get(gameCode);
if (!session) return;
const player = session.players.find(p => p.socketId === socket.id);
if (!player || !player.isAlive) return;
// Get other players in the same actual room
const playersInSameRoom = getPlayersInSameRoom(session, player);
// If there are other players in the same room, they get ejected!
if (playersInSameRoom.length > 0) {
console.log(`${player.name} completed room first! Ejecting ${playersInSameRoom.length} other player(s)`);
playersInSameRoom.forEach(otherPlayer => {
otherPlayer.isAlive = false;
// Notify the ejected player specifically
io.to(otherPlayer.socketId).emit('room-competition-lost', {
winnerId: player.id,
winnerName: player.name,
message: `${player.name} completed the room first! You've been ejected!`,
});
// Notify everyone about the ejection
io.to(gameCode).emit('player-ejected', {
playerId: otherPlayer.id,
playerName: otherPlayer.name,
reason: 'room_competition',
winnerId: player.id,
winnerName: player.name,
message: `${otherPlayer.name} was ejected! ${player.name} completed the room first!`,
});
});
}
// Update the winning player
player.currentRoomIndex = nextRoomIndex;
player.completedItems = [];
player.position = { x: 15, y: 70 };
player.hasCompletedCurrentRoom = false;
// Check if player finished all rooms
if (nextRoomIndex >= 5) {
io.to(gameCode).emit('player-finished', {
playerId: player.id,
playerName: player.name,
score: player.score,
});
// Check if game is over (all players either finished or ejected)
const activePlayers = session.players.filter(p => p.isAlive);
if (activePlayers.every(p => p.currentRoomIndex >= 5)) {
session.status = 'finished';
io.to(gameCode).emit('game-finished', {
session,
winners: activePlayers.map(p => ({ id: p.id, name: p.name, score: p.score })),
});
}
}
// Notify the winner
socket.emit('room-completion-confirmed', {
nextRoomIndex,
ejectedCount: playersInSameRoom.length,
ejectedPlayers: playersInSameRoom.map(p => ({ id: p.id, name: p.name })),
});
io.to(gameCode).emit('session-updated', { session });
});
// ========== FACE-OFF CHALLENGE SYSTEM ==========
// Player initiates a face-off challenge
socket.on('faceoff-challenge', ({ gameCode, targetPlayerId, roomTheme }) => {
const session = gameSessions.get(gameCode);
if (!session || session.status !== 'playing') return;
// Check if there's already an active face-off
if (session.activeFaceOff) {
socket.emit('error', { message: 'A face-off is already in progress!' });
return;
}
const challenger = session.players.find(p => p.socketId === socket.id);
const target = session.players.find(p => p.id === targetPlayerId);
if (!challenger || !target) {
socket.emit('error', { message: 'Invalid players for face-off.' });
return;
}
if (!challenger.isAlive || !target.isAlive) {
socket.emit('error', { message: 'Both players must be alive for a face-off.' });
return;
}
// Check if they're in the same room
const challengerRoom = getActualRoomIndex(challenger);
const targetRoom = getActualRoomIndex(target);
if (challengerRoom !== targetRoom) {
socket.emit('error', { message: 'You can only challenge players in the same room.' });
return;
}
console.log(`Face-off challenge: ${challenger.name} -> ${target.name} in room ${roomIds[challengerRoom]}`);
// Get 10 random questions for the challenger to choose from
const theme = roomIds[challengerRoom];
const availableQuestions = getRandomFaceOffQuestions(theme);
// Create pending face-off
session.activeFaceOff = {
id: `faceoff-${Date.now()}`,
challengerId: challenger.id,
challengerName: challenger.name,
challengedId: target.id,
challengedName: target.name,
availableQuestions: availableQuestions, // Store for selection phase
questions: [], // Will be filled after challenger selects
currentQuestionIndex: 0,
correctAnswers: 0,
status: 'selecting',
startedAt: Date.now(),
};
// Send to challenger to select questions
socket.emit('faceoff-select-questions', {
faceOff: session.activeFaceOff,
availableQuestions: availableQuestions,
targetName: target.name,
});
// Notify the target they've been challenged
io.to(target.socketId).emit('faceoff-challenge-received', {
challenge: {
challengerId: challenger.id,
challengerName: challenger.name,
challengerColor: challenger.color,
},
message: `${challenger.name} is selecting questions for your face-off!`,
});
// Notify all other players
io.to(gameCode).emit('faceoff-initiated', {
challengerId: challenger.id,
challengerName: challenger.name,
challengedId: target.id,
challengedName: target.name,
});
io.to(gameCode).emit('session-updated', { session });
});
// Challenger selects 3 questions
socket.on('faceoff-select-questions', ({ gameCode, questionIds }) => {
const session = gameSessions.get(gameCode);
if (!session || !session.activeFaceOff) return;
const faceOff = session.activeFaceOff;
// Verify the challenger is selecting
const challenger = session.players.find(p => p.socketId === socket.id);
if (!challenger || challenger.id !== faceOff.challengerId) {
socket.emit('error', { message: 'Only the challenger can select questions.' });
return;
}
if (questionIds.length !== 3) {
socket.emit('error', { message: 'You must select exactly 3 questions.' });
return;
}
// Get the selected questions
const selectedQuestions = faceOff.availableQuestions.filter(q => questionIds.includes(q.id));
if (selectedQuestions.length !== 3) {
socket.emit('error', { message: 'Invalid question selection.' });
return;
}
// Update face-off with selected questions
faceOff.questions = selectedQuestions;
faceOff.status = 'answering';
faceOff.currentQuestionIndex = 0;
faceOff.correctAnswers = 0;
console.log(`Face-off questions selected by ${challenger.name}:`, selectedQuestions.map(q => q.id));
// Notify both players face-off is starting
io.to(gameCode).emit('faceoff-started', { faceOff });
// Send the first question to the challenged player
const challenged = session.players.find(p => p.id === faceOff.challengedId);
if (challenged) {
io.to(challenged.socketId).emit('faceoff-question', {
question: {
id: selectedQuestions[0].id,
question: selectedQuestions[0].question,
category: selectedQuestions[0].category,
},
questionNumber: 1,
totalQuestions: 3,
correctSoFar: 0,
});
}
io.to(gameCode).emit('session-updated', { session });
});
// Challenged player answers a face-off question
socket.on('faceoff-answer', ({ gameCode, answer }) => {
const session = gameSessions.get(gameCode);
if (!session || !session.activeFaceOff) return;
const faceOff = session.activeFaceOff;
// Verify the challenged player is answering
const player = session.players.find(p => p.socketId === socket.id);
if (!player || player.id !== faceOff.challengedId) {
socket.emit('error', { message: 'Only the challenged player can answer.' });
return;
}
if (faceOff.status !== 'answering') {
socket.emit('error', { message: 'Face-off is not in answering phase.' });
return;
}
const currentQuestion = faceOff.questions[faceOff.currentQuestionIndex];
const isCorrect = answer === currentQuestion.answer;
if (isCorrect) {
faceOff.correctAnswers++;
}
console.log(`Face-off answer: ${player.name} answered ${answer ? 'YES' : 'NO'} - ${isCorrect ? 'CORRECT' : 'WRONG'}`);
// Send result to both players
const challenger = session.players.find(p => p.id === faceOff.challengerId);
io.to(player.socketId).emit('faceoff-answer-result', {
correct: isCorrect,
correctAnswer: currentQuestion.answer,
correctSoFar: faceOff.correctAnswers,
questionNumber: faceOff.currentQuestionIndex + 1,
});
if (challenger) {
io.to(challenger.socketId).emit('faceoff-answer-result', {
correct: isCorrect,
correctAnswer: currentQuestion.answer,
correctSoFar: faceOff.correctAnswers,
questionNumber: faceOff.currentQuestionIndex + 1,
});
}
// Check if face-off is over
if (!isCorrect) {
// Challenged player got it wrong - they're ejected!
faceOff.status = 'completed';
faceOff.result = 'challenged_ejected';
player.isAlive = false;
io.to(gameCode).emit('faceoff-completed', {
faceOff,
ejectedId: player.id,
ejectedName: player.name,
survivorId: faceOff.challengerId,
survivorName: faceOff.challengerName,
reason: 'wrong_answer',
message: `${player.name} answered wrong and was ejected! ${faceOff.challengerName} wins the face-off!`,
});
io.to(gameCode).emit('player-ejected', {
playerId: player.id,
playerName: player.name,
reason: 'faceoff_lost',
message: `${player.name} lost the face-off and was ejected!`,
});
session.activeFaceOff = null;
} else if (faceOff.currentQuestionIndex >= 2) {
// All 3 questions answered correctly - challenger is ejected!
faceOff.status = 'completed';
faceOff.result = 'challenger_ejected';
if (challenger) {
challenger.isAlive = false;
}
io.to(gameCode).emit('faceoff-completed', {
faceOff,
ejectedId: faceOff.challengerId,
ejectedName: faceOff.challengerName,
survivorId: player.id,
survivorName: player.name,
reason: 'all_correct',
message: `${player.name} answered all 3 questions correctly! ${faceOff.challengerName} is ejected!`,
});
io.to(gameCode).emit('player-ejected', {
playerId: faceOff.challengerId,
playerName: faceOff.challengerName,
reason: 'faceoff_backfire',
message: `${faceOff.challengerName}'s challenge backfired and they were ejected!`,
});
session.activeFaceOff = null;
} else {
// Move to next question
faceOff.currentQuestionIndex++;
const nextQuestion = faceOff.questions[faceOff.currentQuestionIndex];
setTimeout(() => {
io.to(player.socketId).emit('faceoff-question', {
question: {
id: nextQuestion.id,
question: nextQuestion.question,
category: nextQuestion.category,
},
questionNumber: faceOff.currentQuestionIndex + 1,
totalQuestions: 3,
correctSoFar: faceOff.correctAnswers,
});
}, 1500); // Brief delay between questions
}
io.to(gameCode).emit('session-updated', { session });
});
// Decline face-off (optional - could be used if we add declining)
socket.on('faceoff-decline', ({ gameCode }) => {
const session = gameSessions.get(gameCode);
if (!session || !session.activeFaceOff) return;
// Cancel the face-off
session.activeFaceOff = null;
io.to(gameCode).emit('faceoff-cancelled', {
reason: 'Face-off was declined.',
});
io.to(gameCode).emit('session-updated', { session });
});
// ========== END FACE-OFF SYSTEM ==========
// Get current session state
socket.on('get-session', ({ gameCode }) => {
const session = gameSessions.get(gameCode);
if (session) {
socket.emit('session-updated', { session });
}
});
// Chat message
socket.on('chat-message', ({ gameCode, message }) => {
const session = gameSessions.get(gameCode);
if (!session) return;
const player = session.players.find(p => p.socketId === socket.id);
if (player) {
io.to(gameCode).emit('chat-message', {
playerId: player.id,
playerName: player.name,
playerColor: player.color,
message,
timestamp: Date.now(),
});
}
});
// Disconnect handling
socket.on('disconnect', () => {
const gameCode = playerSockets.get(socket.id);
if (gameCode) {
const session = gameSessions.get(gameCode);
if (session) {
// Cancel any active face-off involving this player
if (session.activeFaceOff) {
const fo = session.activeFaceOff;
const player = session.players.find(p => p.socketId === socket.id);
if (player && (fo.challengerId === player.id || fo.challengedId === player.id)) {
session.activeFaceOff = null;
io.to(gameCode).emit('faceoff-cancelled', {
reason: 'A player disconnected during the face-off.',
});
}
}
const playerIndex = session.players.findIndex(p => p.socketId === socket.id);
if (playerIndex !== -1) {
const player = session.players[playerIndex];
session.players.splice(playerIndex, 1);
// If host left, assign new host
if (session.hostId === socket.id && session.players.length > 0) {
session.hostId = session.players[0].id;
}
io.to(gameCode).emit('player-left', {
playerId: player.id,
playerName: player.name,
session,
});
// Clean up empty sessions
if (session.players.length === 0) {
gameSessions.delete(gameCode);
console.log(`Game session deleted: ${gameCode}`);
}
}
}
playerSockets.delete(socket.id);
}
console.log('Client disconnected:', socket.id);
});
});
httpServer.listen(port, () => {
console.log(`> Ready on http://${hostname}:${port}`);
});
});