-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
815 lines (684 loc) · 35.4 KB
/
script.js
File metadata and controls
815 lines (684 loc) · 35.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
class HalfCircleMultiplayerGame {
constructor() {
this.socket = null;
this.isConnected = false;
this.roomId = null;
this.playerInfo = null;
this.gameState = {
currentPlayer: 1,
round: 1,
maxRounds: 10,
scores: { player1: 0, player2: 0 },
gamePhase: 'waiting',
targetAngle: 0,
targetRange: 20,
needleAngle: 90,
isGameStarted: false
};
this.players = [];
this.initializeElements();
this.initializeSocket();
this.bindConnectionEvents();
this.generateStars();
}
initializeElements() {
this.elements = {
// Connection screen elements
connectionScreen: document.getElementById('connection-screen'),
connectionForm: document.getElementById('connection-form'),
gameContainer: document.getElementById('game-container'),
playerNameInput: document.getElementById('player-name'),
roomIdInput: document.getElementById('room-id'),
maxRoundsInput: document.getElementById('max-rounds'),
joinRoomBtn: document.getElementById('join-room-btn'),
createRoomBtn: document.getElementById('create-room-btn'),
leaveRoomBtn: document.getElementById('leave-room-btn'),
waitingRoom: document.getElementById('waiting-room'),
currentRoomId: document.getElementById('current-room-id'),
playerCount: document.getElementById('player-count'),
copyFeedback: document.getElementById('copy-feedback'),
// End game elements
endGameScreen: document.getElementById('end-game-screen'),
endGameTitle: document.getElementById('end-game-title'),
endGameMessage: document.getElementById('end-game-message'),
finalPlayer1Name: document.getElementById('final-player1-name'),
finalPlayer1Score: document.getElementById('final-player1-score'),
finalPlayer2Name: document.getElementById('final-player2-name'),
finalPlayer2Score: document.getElementById('final-player2-score'),
finalPlayer1Card: document.getElementById('final-player1'),
finalPlayer2Card: document.getElementById('final-player2'),
newGameEndBtn: document.getElementById('new-game-end'),
leaveGameEndBtn: document.getElementById('leave-game-end'),
// Game elements
player1Score: document.getElementById('player1-score'),
player2Score: document.getElementById('player2-score'),
player1Name: document.getElementById('player1-name'),
player2Name: document.getElementById('player2-name'),
currentPlayer: document.getElementById('current-player'),
roundInfo: document.getElementById('round-info'),
instructionText: document.getElementById('instruction-text'),
startRound: document.getElementById('start-round'),
showTarget: document.getElementById('show-target'),
placeNeedle: document.getElementById('place-needle'),
confirmGuess: document.getElementById('confirm-guess'),
nextTurn: document.getElementById('next-turn'),
newGame: document.getElementById('new-game'),
gameSvg: document.getElementById('game-svg'),
semicircle: document.getElementById('semicircle'),
clickArea: document.getElementById('click-area'),
needle: document.getElementById('needle'),
targetRange: document.getElementById('target-range'),
scorePopup: document.getElementById('score-popup'),
scoreTitle: document.getElementById('score-title'),
scoreValue: document.getElementById('score-value'),
closePopup: document.getElementById('close-popup')
};
}
initializeSocket() {
this.socket = io();
this.socket.on('connect', () => {
console.log('Connected to server');
this.isConnected = true;
});
this.socket.on('disconnect', () => {
console.log('Disconnected from server');
this.isConnected = false;
this.showConnectionScreen();
});
this.socket.on('joined-room', (data) => {
console.log('Joined room:', data);
this.roomId = data.roomId;
this.playerInfo = data.player;
this.gameState = data.gameState;
this.elements.currentRoomId.textContent = this.roomId;
this.showWaitingRoom();
});
this.socket.on('room-full', () => {
alert('Cette salle est pleine! Essayez un autre code.');
});
this.socket.on('player-joined', (data) => {
console.log('Player joined:', data);
this.elements.playerCount.textContent = data.playerCount;
this.gameState = data.gameState;
});
this.socket.on('player-left', (data) => {
console.log('Player left:', data);
this.elements.playerCount.textContent = data.playerCount;
this.gameState = data.gameState;
if (data.playerCount === 1) {
// Return to waiting room
this.elements.gameContainer.style.display = 'none';
this.elements.endGameScreen.style.display = 'none';
this.elements.connectionScreen.style.display = 'flex';
this.showWaitingRoom();
this.elements.instructionText.textContent = `${data.player.name} a quitté la partie. En attente d'un nouvel adversaire...`;
}
});
this.socket.on('game-ready', (data) => {
console.log('Game ready:', data);
this.players = data.players;
this.gameState = data.gameState;
this.showGameScreen();
this.bindGameEvents();
this.initializeGameState();
this.updateDisplay();
// Auto-start first round after 2 seconds
const isMyTurn = this.playerInfo && this.playerInfo.playerNumber === this.gameState.currentPlayer;
if (isMyTurn) {
this.elements.instructionText.textContent = 'La partie commence...';
setTimeout(() => {
this.socket.emit('start-round');
}, 2000);
}
});
this.socket.on('round-started', (data) => {
console.log('Round started event received:', data);
this.gameState = data.gameState;
this.targetAngle = data.targetAngle;
this.targetRange = data.targetRange;
console.log('Stored target data:', { targetAngle: this.targetAngle, targetRange: this.targetRange });
this.updateDisplay();
// Show target to guide player, hide from shooter player
const isMyTurn = this.playerInfo && this.playerInfo.playerNumber === this.gameState.currentPlayer;
const otherPlayerName = this.players.find(p => p.playerNumber !== this.playerInfo.playerNumber)?.name || 'Adversaire';
console.log('Round started - Is my turn:', isMyTurn, 'Player number:', this.playerInfo?.playerNumber, 'Current player:', this.gameState.currentPlayer);
if (isMyTurn) {
// Guide player: sees target and must communicate to other player
this.displayTargetRange(this.targetAngle, this.targetRange);
this.hideNeedle(); // Hide needle for guide player
this.elements.instructionText.textContent = `Vous voyez les zones cibles! Guidez ${otherPlayerName} verbalement pour qu'il place l'aiguille.`;
this.showButtons([]); // No buttons for guide - hide start-round button
} else {
// Shooter player: doesn't see target, can immediately place needle
this.hideTarget();
this.showNeedle(); // Show needle for shooter player
this.elements.instructionText.textContent = `Écoutez les instructions de ${otherPlayerName} et cliquez sur le demi-cercle pour placer l'aiguille.`;
this.enableNeedlePlacement(); // Enable needle placement immediately
this.showButtons([]); // Hide start-round button for shooter too
}
});
this.socket.on('target-shown', (data) => {
console.log('Target shown event received:', data);
this.gameState = data.gameState;
// Only show target to the current player (the one who should see it)
const isMyTurn = this.playerInfo && this.playerInfo.playerNumber === this.gameState.currentPlayer;
console.log('Is my turn to see target:', isMyTurn, 'Player number:', this.playerInfo?.playerNumber, 'Current player:', this.gameState.currentPlayer);
if (isMyTurn) {
const targetAngle = this.targetAngle || data.targetAngle;
const targetRange = this.targetRange || data.targetRange;
console.log('Showing target with angle:', targetAngle, 'range:', targetRange);
this.displayTargetRange(targetAngle, targetRange);
this.elements.instructionText.textContent = 'Mémorisez la position de la zone verte!';
} else {
this.elements.instructionText.textContent = 'Votre adversaire mémorise la zone cible...';
}
this.updateDisplay();
this.showButtons([]);
});
this.socket.on('needle-placed', (data) => {
this.gameState = data.gameState;
this.rotateNeedle(data.needleAngle);
// Make sure needle is visible for both players during scoring
this.showNeedle();
// Show target with results to both players
this.displayTargetRange(data.targetAngle, data.targetRange, data.angleDifference);
this.showScorePopup(data.points, data.message);
this.updateDisplay();
});
this.socket.on('turn-changed', (data) => {
this.gameState = data.gameState;
this.resetNeedle();
this.showNeedle(); // Make sure needle is visible for new round
this.hideTarget();
this.updateDisplay();
// Auto-start the round after a brief delay
const isMyTurn = this.playerInfo && this.playerInfo.playerNumber === this.gameState.currentPlayer;
if (isMyTurn) {
this.elements.instructionText.textContent = 'Votre tour commence...';
setTimeout(() => {
this.socket.emit('start-round');
}, 1500); // 1.5 second delay before auto-starting
} else {
this.updateInstructions();
}
this.showButtons([]); // No buttons needed
});
this.socket.on('game-ended', (data) => {
this.gameState = data.gameState;
this.updateDisplay();
this.showButtons(['new-game']);
this.showEndGameMessage(data.winner, data.scores);
});
this.socket.on('game-reset', (data) => {
this.gameState = data.gameState;
this.resetNeedle();
this.hideTarget();
this.updateDisplay();
this.showButtons([]);
this.elements.endGameScreen.style.display = 'none'; // Hide end game screen
// Auto-start new game after 2 seconds
const isMyTurn = this.playerInfo && this.playerInfo.playerNumber === this.gameState.currentPlayer;
if (isMyTurn) {
this.elements.instructionText.textContent = 'Nouvelle partie! Elle commence dans un instant...';
setTimeout(() => {
this.socket.emit('start-round');
}, 2000);
} else {
this.elements.instructionText.textContent = 'Nouvelle partie! En attente du début...';
}
});
}
bindConnectionEvents() {
this.elements.joinRoomBtn.addEventListener('click', () => this.joinRoom());
this.elements.createRoomBtn.addEventListener('click', () => this.createRoom());
this.elements.leaveRoomBtn.addEventListener('click', () => this.leaveRoom());
// Room code click to copy invite link
this.elements.currentRoomId.addEventListener('click', () => this.copyInviteLink());
// End game buttons
this.elements.newGameEndBtn.addEventListener('click', () => {
this.elements.endGameScreen.style.display = 'none';
this.socket.emit('new-game');
});
this.elements.leaveGameEndBtn.addEventListener('click', () => {
this.leaveRoom();
this.elements.endGameScreen.style.display = 'none';
});
// Enter key support for inputs
this.elements.playerNameInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.joinRoom();
});
this.elements.roomIdInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') this.joinRoom();
});
// Check for room code in URL parameters
this.checkUrlParameters();
}
generateStars() {
const starsContainer = document.getElementById('stars');
const starPositions = [
{ x: 120, y: 120 }, { x: 180, y: 90 }, { x: 220, y: 100 },
{ x: 280, y: 130 }, { x: 150, y: 140 }, { x: 250, y: 160 },
{ x: 130, y: 170 }, { x: 270, y: 110 }, { x: 200, y: 130 }
];
starPositions.forEach((pos, index) => {
const star = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
star.setAttribute('points', '0,-3 0.8,-0.9 2.6,-0.9 1.4,0.3 1.8,2.1 0,1.2 -1.8,2.1 -1.4,0.3 -2.6,-0.9 -0.8,-0.9');
star.setAttribute('transform', `translate(${pos.x}, ${pos.y}) scale(0.8)`);
star.setAttribute('class', 'star');
star.style.animationDelay = `${index * 0.3}s`;
starsContainer.appendChild(star);
});
}
bindGameEvents() {
this.elements.startRound.addEventListener('click', () => this.socket.emit('start-round'));
this.elements.nextTurn.addEventListener('click', () => this.socket.emit('next-turn'));
this.elements.newGame.addEventListener('click', () => this.socket.emit('new-game'));
this.elements.closePopup.addEventListener('click', () => this.closeScorePopup());
this.elements.confirmGuess.addEventListener('click', () => {
console.log('Confirm button clicked! Pending angle:', this.pendingNeedleAngle);
if (this.pendingNeedleAngle !== undefined) {
console.log('Sending needle placement to server:', this.pendingNeedleAngle);
// Send needle placement to server
this.socket.emit('place-needle', { needleAngle: this.pendingNeedleAngle });
this.pendingNeedleAngle = undefined;
this.showButtons([]);
this.elements.instructionText.textContent = 'Placement confirmé! En attente du résultat...';
} else {
console.log('No pending angle to confirm!');
}
});
this.elements.clickArea.addEventListener('click', (e) => this.placeNeedleAtPosition(e));
}
// Connection methods
checkUrlParameters() {
const urlParams = new URLSearchParams(window.location.search);
const roomCode = urlParams.get('room');
if (roomCode) {
// Pre-fill the room code input
this.elements.roomIdInput.value = roomCode;
// Focus on the player name input
this.elements.playerNameInput.focus();
}
}
async copyInviteLink() {
if (!this.roomId) return;
// Create invite link with room code as URL parameter
const inviteUrl = `${window.location.origin}${window.location.pathname}?room=${this.roomId}`;
try {
await navigator.clipboard.writeText(inviteUrl);
// Show feedback
this.elements.copyFeedback.style.display = 'block';
setTimeout(() => {
this.elements.copyFeedback.style.display = 'none';
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
// Fallback: show the link in an alert
alert(`Lien d'invitation: ${inviteUrl}`);
}
}
joinRoom() {
const playerName = this.elements.playerNameInput.value.trim();
const roomId = this.elements.roomIdInput.value.trim();
if (!playerName) {
alert('Veuillez entrer votre nom!');
return;
}
if (!roomId) {
alert('Veuillez entrer un code de salle!');
return;
}
this.socket.emit('join-room', { roomId, playerName });
}
createRoom() {
const playerName = this.elements.playerNameInput.value.trim();
if (!playerName) {
alert('Veuillez entrer votre nom!');
return;
}
// Use custom room ID if provided, otherwise generate random one
let roomId = this.elements.roomIdInput.value.trim();
if (!roomId) {
roomId = Math.random().toString(36).substring(2, 8).toUpperCase();
}
// Get max rounds from selector
const maxRounds = parseInt(this.elements.maxRoundsInput.value);
this.socket.emit('join-room', { roomId, playerName, maxRounds });
}
leaveRoom() {
this.socket.disconnect();
this.socket.connect();
this.showConnectionScreen();
}
showConnectionScreen() {
this.elements.connectionScreen.style.display = 'flex';
this.elements.connectionForm.style.display = 'flex'; // Show the form
this.elements.gameContainer.style.display = 'none';
this.elements.waitingRoom.style.display = 'none';
this.elements.endGameScreen.style.display = 'none'; // Hide end game screen
// Reset form inputs
this.elements.roomIdInput.value = '';
this.roomId = null;
this.playerInfo = null;
this.players = [];
}
showWaitingRoom() {
this.elements.connectionForm.style.display = 'none'; // Hide the form
this.elements.waitingRoom.style.display = 'block'; // Show waiting room
this.elements.playerCount.textContent = '1';
}
showGameScreen() {
this.elements.connectionScreen.style.display = 'none';
this.elements.gameContainer.style.display = 'block';
// Update player names
if (this.players.length >= 2) {
this.elements.player1Name.textContent = this.players[0].name + ':';
this.elements.player2Name.textContent = this.players[1].name + ':';
}
}
initializeGameState() {
// Initialize needle and click area state
this.showNeedle();
this.elements.clickArea.style.cursor = 'not-allowed';
this.elements.clickArea.classList.add('disabled');
this.elements.clickArea.style.pointerEvents = 'none';
}
displayTargetRange(targetAngle, targetRange, angleDifference = null) {
console.log('Displaying target range:', { targetAngle, targetRange, angleDifference });
if (!this.elements.targetRange) {
console.error('Target range element not found!');
return;
}
const centerX = 200;
const centerY = 200;
const radius = 155; // Match the semicircle radius from the SVG path
// Clear any existing target range displays
this.clearTargetZones();
// Create subdivided zones for different point values
this.createPointZones(centerX, centerY, radius, targetAngle, targetRange, angleDifference);
this.elements.targetRange.setAttribute('opacity', '1');
}
createPointZones(centerX, centerY, radius, targetAngle, targetRange, angleDifference = null) {
// Create different zones for different point values
// Draw from largest to smallest so smaller zones appear on top
const zones = [
{ points: 1, range: 25, color: 'rgba(249, 115, 22, 0.4)', label: '1pt' }, // OK zone (largest, drawn first)
{ points: 3, range: 15, color: 'rgba(251, 191, 36, 0.6)', label: '3pts' }, // Good zone (medium)
{ points: 5, range: 5, color: 'rgba(34, 197, 94, 0.8)', label: '5pts' } // Perfect zone (smallest, drawn last = on top)
];
// Clear existing zones
const svg = this.elements.gameSvg;
const existingZones = svg.querySelectorAll('.target-zone');
existingZones.forEach(zone => zone.remove());
zones.forEach((zone, index) => {
const halfRange = zone.range / 2;
// Convert angle to radians and calculate positions
// Our coordinate system: 0° = right, 90° = up, 180° = left
const startAngle = (targetAngle - halfRange) * Math.PI / 180;
const endAngle = (targetAngle + halfRange) * Math.PI / 180;
// Use standard circle coordinates (no mirroring needed)
const startX = centerX + Math.cos(startAngle) * radius;
const startY = centerY - Math.sin(startAngle) * radius; // Subtract because SVG Y goes down
const endX = centerX + Math.cos(endAngle) * radius;
const endY = centerY - Math.sin(endAngle) * radius;
// Create path for this zone
// Arc goes counter-clockwise (sweep-flag = 0) from higher angle to lower angle
const largeArcFlag = zone.range > 180 ? 1 : 0;
const pathData = `M ${centerX} ${centerY} L ${startX} ${startY} A ${radius} ${radius} 0 ${largeArcFlag} 0 ${endX} ${endY} Z`;
// Create the zone element
const zoneElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');
zoneElement.setAttribute('d', pathData);
zoneElement.setAttribute('fill', zone.color);
zoneElement.setAttribute('stroke', zone.color.replace(/[\d.]+\)/, '1)'));
zoneElement.setAttribute('stroke-width', '0.5');
zoneElement.setAttribute('class', 'target-zone');
zoneElement.setAttribute('data-points', zone.points);
// Add the zone to the SVG (before the needle)
const needle = this.elements.needle;
svg.insertBefore(zoneElement, needle);
});
// Add point labels
this.addPointLabels(centerX, centerY, radius, targetAngle);
}
addPointLabels(centerX, centerY, radius, targetAngle) {
const svg = this.elements.gameSvg;
// Remove existing labels
const existingLabels = svg.querySelectorAll('.point-label');
existingLabels.forEach(label => label.remove());
// Add labels for each zone - positioned inside their zones
// Zones: 5pt (±2.5°), 3pt (±7.5°), 1pt (±12.5°)
const labels = [
{ points: '5', angle: targetAngle, distance: radius * 0.80, color: '#ffffff', fontSize: '14' }, // Center of green zone (0°)
{ points: '3', angle: targetAngle - 5, distance: radius * 0.80, color: '#ffffff', fontSize: '13' }, // Left yellow zone (-5°, between 2.5° and 7.5°)
{ points: '3', angle: targetAngle + 5, distance: radius * 0.80, color: '#ffffff', fontSize: '13' }, // Right yellow zone (+5°)
{ points: '1', angle: targetAngle - 10, distance: radius * 0.80, color: '#ffffff', fontSize: '13' }, // Left orange zone (-10°, between 7.5° and 12.5°)
{ points: '1', angle: targetAngle + 10, distance: radius * 0.80, color: '#ffffff', fontSize: '13' } // Right orange zone (+10°)
];
labels.forEach(label => {
const angleRad = (label.angle) * Math.PI / 180;
// Use standard circle coordinates matching the zone drawing
const x = centerX + Math.cos(angleRad) * label.distance;
const y = centerY - Math.sin(angleRad) * label.distance;
const textElement = document.createElementNS('http://www.w3.org/2000/svg', 'text');
textElement.setAttribute('x', x);
textElement.setAttribute('y', y);
textElement.setAttribute('text-anchor', 'middle');
textElement.setAttribute('dominant-baseline', 'middle');
textElement.setAttribute('fill', label.color);
textElement.setAttribute('font-size', label.fontSize);
textElement.setAttribute('font-weight', 'bold');
textElement.setAttribute('class', 'point-label');
textElement.textContent = label.points;
svg.appendChild(textElement);
});
}
clearTargetZones() {
const svg = this.elements.gameSvg;
const existingZones = svg.querySelectorAll('.target-zone, .point-label');
existingZones.forEach(zone => zone.remove());
}
hideTarget() {
console.log('Hiding target range');
this.elements.targetRange.setAttribute('opacity', '0');
this.elements.targetRange.setAttribute('stroke-width', '0');
this.elements.targetRange.setAttribute('class', '');
this.clearTargetZones();
}
enableNeedlePlacement() {
console.log('Enabling needle placement');
this.elements.clickArea.style.cursor = 'crosshair';
this.elements.clickArea.classList.remove('disabled');
this.elements.clickArea.style.pointerEvents = 'auto';
this.showButtons([]);
// Don't change instruction text here, it's handled by the calling function
}
placeNeedleAtPosition(event) {
console.log('Attempting to place needle. Game phase:', this.gameState.gamePhase);
console.log('Click area classes:', this.elements.clickArea.className);
// Allow needle placement in both target-shown and placing-needle phases
if (this.gameState.gamePhase !== 'placing-needle' && this.gameState.gamePhase !== 'target-shown') {
console.log('Cannot place needle - wrong game phase');
return;
}
// Check if click area is enabled
if (this.elements.clickArea.classList.contains('disabled')) {
console.log('Click area is disabled');
return;
}
// Check if this player should be placing the needle
// The SHOOTER (non-current player) should place the needle, not the guide
const isMyTurn = this.playerInfo && this.playerInfo.playerNumber === this.gameState.currentPlayer;
if (isMyTurn) {
console.log('Guide player cannot place needle - you are the guide!');
return; // Guide player shouldn't be able to place needle
}
console.log('Shooter is placing needle...');
// Get SVG element and its client rectangle
const svg = this.elements.gameSvg;
const rect = svg.getBoundingClientRect();
// SVG viewBox coordinates
const viewBox = svg.viewBox.baseVal;
console.log('ViewBox:', { width: viewBox.width, height: viewBox.height });
console.log('Rect (client):', { width: rect.width, height: rect.height });
const centerX = 200;
const centerY = 200;
// Calculate click position in SVG coordinates (accounting for viewBox)
const clickX = ((event.clientX - rect.left) / rect.width) * viewBox.width;
const clickY = ((event.clientY - rect.top) / rect.height) * viewBox.height;
console.log('Click position in SVG coords:', { clickX, clickY });
// Calculate angle from center
const deltaX = clickX - centerX;
const deltaY = centerY - clickY; // Invert Y because SVG Y increases downward
console.log('Delta from center:', { deltaX, deltaY });
// Calculate angle using atan2 - returns angle in radians from -PI to PI
let angleRad = Math.atan2(deltaY, deltaX);
// Convert to degrees
// In our system: 0° is right, 90° is up, 180° is left
let angle = angleRad * 180 / Math.PI;
// Ensure angle is between 0 and 180 (top half of circle)
if (angle < 0) angle = 0;
if (angle > 180) angle = 180;
console.log('Calculated angle:', angle, '(angleRad:', angleRad, ')');
// Immediately rotate needle for visual feedback
this.rotateNeedle(angle);
// Show confirm button for shooter
this.showButtons(['confirm-guess']);
this.elements.instructionText.textContent = 'Cliquez sur "Confirmer le placement" pour valider votre choix. Vous pouvez ajuster la position avant de confirmer.';
// Store the angle for confirmation
this.pendingNeedleAngle = angle;
// Allow repositioning - don't disable click area
// Player can click again to adjust before confirming
}
rotateNeedle(angle) {
// Rotate needle to the specified angle
this.elements.needle.style.transform = `rotate(${-(angle - 90)}deg)`;
}
showScorePopup(points, message) {
this.elements.scoreTitle.textContent = message;
this.elements.scoreValue.textContent = points > 0 ? `+${points} points` : 'Aucun point';
this.elements.scoreValue.style.color = points > 0 ? '#22c55e' : '#ef4444';
this.elements.scorePopup.style.display = 'flex';
// Auto-close popup after 3 seconds and advance to next turn
setTimeout(() => {
this.closeScorePopup();
// Auto-advance to next turn
if (this.gameState.round <= this.gameState.maxRounds) {
this.socket.emit('next-turn');
}
}, 3000);
}
closeScorePopup() {
this.elements.scorePopup.style.display = 'none';
if (this.gameState.round > this.gameState.maxRounds) {
this.showButtons(['new-game']);
} else {
this.showButtons([]); // No manual button needed, auto-advances
}
}
resetNeedle() {
this.elements.needle.style.transform = 'rotate(0deg)';
}
hideNeedle() {
this.elements.needle.style.opacity = '0';
}
showNeedle() {
this.elements.needle.style.opacity = '1';
}
showEndGameMessage(winner, scores) {
// Update player names
this.elements.finalPlayer1Name.textContent = this.players[0]?.name || 'Joueur 1';
this.elements.finalPlayer2Name.textContent = this.players[1]?.name || 'Joueur 2';
// Update scores
this.elements.finalPlayer1Score.textContent = `${scores.player1} pts`;
this.elements.finalPlayer2Score.textContent = `${scores.player2} pts`;
// Highlight winner
this.elements.finalPlayer1Card.classList.remove('winner');
this.elements.finalPlayer2Card.classList.remove('winner');
let message = '';
if (winner === 0) {
message = '🤝 Match nul! Bien joué à tous les deux!';
this.elements.endGameTitle.textContent = '🏆 Égalité parfaite!';
} else {
const winnerName = this.players[winner - 1]?.name || `Joueur ${winner}`;
message = `🎉 ${winnerName} remporte la victoire!`;
this.elements.endGameTitle.textContent = '🏆 Victoire!';
// Highlight winner card
if (winner === 1) {
this.elements.finalPlayer1Card.classList.add('winner');
} else {
this.elements.finalPlayer2Card.classList.add('winner');
}
}
this.elements.endGameMessage.textContent = message;
this.elements.endGameScreen.style.display = 'flex';
}
updateInstructions() {
if (!this.playerInfo || !this.gameState) return;
const isMyTurn = this.playerInfo.playerNumber === this.gameState.currentPlayer;
const otherPlayerName = this.players.find(p => p.playerNumber !== this.playerInfo.playerNumber)?.name || 'Adversaire';
const myName = this.playerInfo.name;
switch (this.gameState.gamePhase) {
case 'waiting':
if (isMyTurn) {
this.elements.instructionText.textContent = 'Cliquez sur "Commencer la manche" pour débuter!';
} else {
this.elements.instructionText.textContent = `Attendez que ${otherPlayerName} commence la manche...`;
}
break;
case 'target-shown':
if (isMyTurn) {
this.elements.instructionText.textContent = `Vous voyez les zones cibles! Guidez ${otherPlayerName} verbalement puis activez le placement.`;
} else {
this.elements.instructionText.textContent = `Écoutez les instructions de ${otherPlayerName} pour savoir où placer l'aiguille.`;
}
break;
case 'placing-needle':
if (isMyTurn) {
this.elements.instructionText.textContent = `Continuez à guider ${otherPlayerName} pendant qu'il place l'aiguille!`;
} else {
this.elements.instructionText.textContent = 'Cliquez sur le demi-cercle pour placer l\'aiguille selon les instructions!';
}
break;
case 'scored':
this.elements.instructionText.textContent = 'Points calculés! Voyez le résultat.';
break;
}
}
showButtons(buttonIds) {
const allButtons = ['start-round', 'confirm-guess', 'next-turn', 'new-game'];
allButtons.forEach(id => {
const elementKey = this.convertToCamelCase(id);
if (this.elements[elementKey]) {
this.elements[elementKey].style.display = 'none';
}
});
// Show the specified buttons
buttonIds.forEach(id => {
const elementKey = this.convertToCamelCase(id);
if (this.elements[elementKey]) {
this.elements[elementKey].style.display = 'inline-block';
}
});
}
convertToCamelCase(str) {
// Convert kebab-case to camelCase (e.g., 'confirm-guess' -> 'confirmGuess')
return str.replace(/-([a-z])/g, (match, letter) => letter.toUpperCase());
}
updateDisplay() {
if (!this.gameState) return;
// Update scores
this.elements.player1Score.textContent = `${this.gameState.scores.player1} pts`;
this.elements.player2Score.textContent = `${this.gameState.scores.player2} pts`;
// Update current player highlighting
this.elements.player1Name.classList.toggle('active', this.gameState.currentPlayer === 1);
this.elements.player2Name.classList.toggle('active', this.gameState.currentPlayer === 2);
// Update game info
const currentPlayerName = this.players.find(p => p.playerNumber === this.gameState.currentPlayer)?.name || `Joueur ${this.gameState.currentPlayer}`;
this.elements.currentPlayer.textContent = `Tour de ${currentPlayerName}`;
this.elements.roundInfo.textContent = `Manche ${this.gameState.round} sur ${this.gameState.maxRounds}`;
}
}
// Initialize the game when the page loads
document.addEventListener('DOMContentLoaded', () => {
new HalfCircleMultiplayerGame();
});