-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
2732 lines (2281 loc) · 100 KB
/
Copy pathgame.js
File metadata and controls
2732 lines (2281 loc) · 100 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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ABOUTME: This file contains the core game logic for the Threes card game web application
// ABOUTME: It includes card management, game state, player logic, and all interactive functionality
// Card data structures and constants
const CARD_RANKS = ['2', 'A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2'];
const CARD_SUITS = ['♠', '♥', '♦', '♣'];
// Game phase constants
const GAME_PHASES = {
SETUP: 'setup',
EXCHANGE: 'exchange',
PLAYING: 'playing',
GAME_OVER: 'game_over'
};
// Card Class
class Card {
constructor(rank, suit) {
this.rank = rank;
this.suit = suit;
this.id = `${rank}-${suit}`;
}
// Get card value for comparison (2=14, A=13, K=12, etc.)
getValue() {
const rankValues = {
'2': 14, 'A': 13, 'K': 12, 'Q': 11, 'J': 10,
'10': 10, '9': 9, '8': 8, '7': 7, '6': 6, '5': 5, '4': 4, '3': 3
};
return rankValues[this.rank] || 0;
}
// Get card display string
toString() {
return `${this.rank}${this.suit}`;
}
// Check if this is a red suit
isRed() {
return this.suit === '♥' || this.suit === '♦';
}
// Check if this is a black suit
isBlack() {
return this.suit === '♠' || this.suit === '♣';
}
}
// Player Class
class Player {
constructor(name) {
this.name = name;
this.handCards = [];
this.faceUpCards = [];
this.faceDownCards = [];
this.isActive = true;
this.hasFinished = false;
}
// Add a card to specified location
addCard(card, location = 'hand') {
switch(location) {
case 'hand':
this.handCards.push(card);
break;
case 'faceUp':
this.faceUpCards.push(card);
break;
case 'faceDown':
this.faceDownCards.push(card);
break;
default:
console.error('Invalid card location:', location);
}
}
// Remove a card from specified location
removeCard(cardId, location = 'hand') {
let cards;
switch(location) {
case 'hand':
cards = this.handCards;
break;
case 'faceUp':
cards = this.faceUpCards;
break;
case 'faceDown':
cards = this.faceDownCards;
break;
default:
console.error('Invalid card location:', location);
return null;
}
const cardIndex = cards.findIndex(card => card.id === cardId);
if (cardIndex !== -1) {
return cards.splice(cardIndex, 1)[0];
}
return null;
}
// Get total card count for player
getCardCount() {
return this.handCards.length + this.faceUpCards.length + this.faceDownCards.length;
}
// Get cards by location
getCards(location) {
switch(location) {
case 'hand': return [...this.handCards];
case 'faceUp': return [...this.faceUpCards];
case 'faceDown': return [...this.faceDownCards];
default: return [];
}
}
// Check if player has finished (no cards left)
checkFinished() {
this.hasFinished = this.getCardCount() === 0;
if (this.hasFinished) {
this.isActive = false;
}
return this.hasFinished;
}
}
// GameState Class
class GameState {
constructor() {
this.players = [];
this.currentPlayerIndex = 0;
this.gamePhase = GAME_PHASES.SETUP;
this.deck = [];
this.discardPile = [];
this.drawPile = [];
}
// Initialize the game with players
initializeGame(playerNames) {
this.players = playerNames.map(name => new Player(name));
this.deck = createDeck();
this.drawPile = shuffleDeck(this.deck);
this.discardPile = [];
this.currentPlayerIndex = 0;
this.gamePhase = GAME_PHASES.SETUP;
console.log(`Game initialized with ${this.players.length} players`);
}
// Get the current active player
getCurrentPlayer() {
if (this.players.length === 0) return null;
return this.players[this.currentPlayerIndex];
}
// Move to the next player
nextPlayer() {
if (this.players.length === 0) return;
// Find next active player
let nextIndex = (this.currentPlayerIndex + 1) % this.players.length;
let attempts = 0;
while (attempts < this.players.length && !this.players[nextIndex].isActive) {
nextIndex = (nextIndex + 1) % this.players.length;
attempts++;
}
if (attempts < this.players.length) {
this.currentPlayerIndex = nextIndex;
}
console.log(`Turn passed to: ${this.getCurrentPlayer().name}`);
}
// Check if game is over (only one player left)
checkGameOver() {
const activePlayers = this.players.filter(p => p.isActive);
if (activePlayers.length <= 1) {
this.gamePhase = GAME_PHASES.GAME_OVER;
return true;
}
return false;
}
// Get game state summary for debugging
getStateSummary() {
return {
phase: this.gamePhase,
currentPlayer: this.getCurrentPlayer()?.name,
playerCount: this.players.length,
activePlayerCount: this.players.filter(p => p.isActive).length,
drawPileSize: this.drawPile.length,
discardPileSize: this.discardPile.length
};
}
}
// Utility Functions
// Create a full 52-card deck
function createDeck() {
const deck = [];
for (const suit of CARD_SUITS) {
for (const rank of CARD_RANKS) {
deck.push(new Card(rank, suit));
}
}
return deck;
}
// Fisher-Yates shuffle implementation
function shuffleDeck(deck) {
const shuffled = [...deck]; // Create a copy
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;
}
// Create DOM element for a card
function renderCard(card, faceDown = false, isSelectable = false) {
const cardElement = document.createElement('div');
cardElement.className = 'card';
cardElement.dataset.cardId = card.id;
if (faceDown) {
cardElement.classList.add('face-down');
cardElement.innerHTML = '<div class="card-back">🂠</div>';
} else {
cardElement.classList.add('face-up');
if (card.isRed()) {
cardElement.classList.add('red-suit');
} else {
cardElement.classList.add('black-suit');
}
if (isSelectable) {
cardElement.classList.add('selectable');
}
cardElement.innerHTML = `
<div class="card-content">
<div class="card-rank">${card.rank}</div>
<div class="card-suit">${card.suit}</div>
</div>
`;
}
return cardElement;
}
// Render player area with all card types
function renderPlayerArea(player, isCurrentPlayer = false) {
const playerCards = {
faceDown: player.faceDownCards.map(card =>
renderCard(card, true, false).outerHTML
).join(''),
faceUp: player.faceUpCards.map(card =>
renderCard(card, false, isCurrentPlayer).outerHTML
).join(''),
hand: isCurrentPlayer ? player.handCards.map(card =>
renderCard(card, false, true).outerHTML
).join('') : ''
};
return playerCards;
}
// Render center area (draw and discard piles)
function renderCenterArea(gameState) {
const drawPileHTML = gameState.drawPile.length > 0 ?
renderCard(gameState.drawPile[gameState.drawPile.length - 1], true).outerHTML :
'<div class="empty-pile">Empty</div>';
const discardPileHTML = gameState.discardPile.length > 0 ?
gameState.discardPile.slice(-3).map(card => renderCard(card, false).outerHTML).join('') :
'<div class="empty-pile">Empty</div>';
return { drawPileHTML, discardPileHTML };
}
// Basic card creation function
function createCard(rank, suit) {
return new Card(rank, suit);
}
// Game Initialization Functions
// Setup players with default names if needed
function setupPlayers(playerCount, playerNames = []) {
const names = [];
for (let i = 0; i < playerCount; i++) {
names.push(playerNames[i] || `Player ${i + 1}`);
}
return names;
}
// Enhanced card dealing system
function dealInitialCards(gameState) {
if (!gameState || gameState.players.length === 0) {
console.error('Cannot deal cards without valid game state and players');
return false;
}
console.log('=== Starting Card Dealing ===');
// Ensure we have enough cards
const requiredCards = gameState.players.length * 9; // 9 cards per player
if (gameState.drawPile.length < requiredCards) {
console.error(`Not enough cards in draw pile. Need ${requiredCards}, have ${gameState.drawPile.length}`);
return false;
}
// Deal in proper order: face-down first, then face-up, then hand
console.log('Dealing face-down cards...');
gameState.players.forEach(player => {
for (let i = 0; i < 3; i++) {
const card = gameState.drawPile.pop();
player.addCard(card, 'faceDown');
}
});
console.log('Dealing face-up cards...');
gameState.players.forEach(player => {
for (let i = 0; i < 3; i++) {
const card = gameState.drawPile.pop();
player.addCard(card, 'faceUp');
}
});
console.log('Dealing hand cards...');
gameState.players.forEach(player => {
for (let i = 0; i < 3; i++) {
const card = gameState.drawPile.pop();
player.addCard(card, 'hand');
}
});
// Log dealing results
gameState.players.forEach((player, index) => {
console.log(`${player.name}: Face-down(${player.faceDownCards.length}), Face-up(${player.faceUpCards.length}), Hand(${player.handCards.length})`);
console.log(` Face-up cards: ${player.faceUpCards.map(c => c.toString()).join(', ')}`);
});
console.log(`Cards remaining in draw pile: ${gameState.drawPile.length}`);
console.log('=== Card Dealing Complete ===');
return true;
}
// Determine first player based on lowest face-up card
function determineFirstPlayer(gameState) {
let firstPlayerIndex = 0;
let lowestValue = Infinity;
let lowestCard = null;
gameState.players.forEach((player, playerIndex) => {
player.faceUpCards.forEach(card => {
// Special rule: 3s are lowest, then 4s, etc.
// We need to invert the getValue() for this check since 3 should be considered lowest
let checkValue = card.getValue();
if (card.rank === '3') checkValue = 1; // 3s are lowest
else if (card.rank === '4') checkValue = 2; // then 4s
else if (card.rank === '5') checkValue = 3; // then 5s, etc.
if (checkValue < lowestValue) {
lowestValue = checkValue;
lowestCard = card;
firstPlayerIndex = playerIndex;
}
});
});
console.log(`First player determined: ${gameState.players[firstPlayerIndex].name} (has ${lowestCard?.toString() || 'unknown card'})`);
return firstPlayerIndex;
}
// Initialize decks and deal initial cards (legacy function, now calls enhanced version)
function initializeDecks(gameState) {
const success = dealInitialCards(gameState);
if (success) {
// Determine who will go first in the actual game (but don't set it yet)
const firstPlayerIndex = determineFirstPlayer(gameState);
// Store the determined first player for later use
gameState.determinedFirstPlayerIndex = firstPlayerIndex;
// Exchange phase always starts with Player 1 (index 0)
gameState.currentPlayerIndex = 0;
gameState.gamePhase = GAME_PHASES.EXCHANGE;
console.log(`Exchange phase will start with ${gameState.players[0].name}`);
console.log(`Actual game will start with ${gameState.players[firstPlayerIndex].name}`);
}
return success;
}
// Global game state instance
let gameState = null;
// Setup Screen Module
const setupScreen = {
// Initialize the setup screen
init() {
console.log('Threes Card Game initialized!');
this.render();
this.attachEventListeners();
this.initializeDebouncedUpdates();
// Set up performance monitoring
setInterval(() => {
this.validateGamePerformance();
}, 30000); // Check every 30 seconds
console.log('GameManager initialized with performance optimizations');
},
// Render the setup screen HTML
render() {
const app = document.getElementById('app');
app.innerHTML = `
<div id="setup-screen" class="setup-container">
<div class="setup-header">
<h1 class="game-title">Threes</h1>
<p class="game-subtitle">The Classic Card Game</p>
</div>
<div class="setup-form">
<div class="player-count-section">
<h3>Number of Players</h3>
<div class="player-count-selector">
<input type="radio" id="players-2" name="playerCount" value="2">
<label for="players-2">2 Players</label>
<input type="radio" id="players-3" name="playerCount" value="3" checked>
<label for="players-3">3 Players</label>
<input type="radio" id="players-4" name="playerCount" value="4">
<label for="players-4">4 Players</label>
</div>
</div>
<div class="player-names-section">
<h3>Player Names</h3>
<div id="player-name-inputs" class="player-name-inputs">
<!-- Player name inputs will be generated here -->
</div>
</div>
<div class="setup-actions">
<button id="start-game-btn" class="start-game-btn">Start Game</button>
</div>
</div>
</div>
<div id="game-area" class="game-area hidden">
<!-- Game interface will be rendered here -->
</div>
`;
// Generate initial player name inputs for 3 players (default)
this.generatePlayerNameInputs(3);
},
// Generate player name input fields
generatePlayerNameInputs(count) {
const container = document.getElementById('player-name-inputs');
container.innerHTML = '';
for (let i = 1; i <= count; i++) {
const inputGroup = document.createElement('div');
inputGroup.className = 'input-group';
inputGroup.innerHTML = `
<label for="player-${i}-name">Player ${i}</label>
<input type="text" id="player-${i}-name" class="player-name-input"
placeholder="Player ${i}" value="Player ${i}">
`;
container.appendChild(inputGroup);
}
},
// Attach event listeners
attachEventListeners() {
// Player count change
document.querySelectorAll('input[name="playerCount"]').forEach(radio => {
radio.addEventListener('change', (e) => {
const count = parseInt(e.target.value);
this.generatePlayerNameInputs(count);
});
});
// Start game button
document.getElementById('start-game-btn').addEventListener('click', () => {
this.startGame();
});
},
// Validate setup form
validateSetup() {
const playerCount = parseInt(document.querySelector('input[name="playerCount"]:checked').value);
const names = [];
for (let i = 1; i <= playerCount; i++) {
const nameInput = document.getElementById(`player-${i}-name`);
const name = nameInput.value.trim();
if (!name) {
this.showError(`Player ${i} name cannot be empty`);
nameInput.focus();
return null;
}
if (names.includes(name)) {
this.showError(`Player names must be unique. "${name}" is already used.`);
nameInput.focus();
return null;
}
names.push(name);
}
return { playerCount, names };
},
// Show error message
showError(message) {
// Remove existing error
const existingError = document.querySelector('.setup-error');
if (existingError) {
existingError.remove();
}
// Create new error message
const errorDiv = document.createElement('div');
errorDiv.className = 'setup-error';
errorDiv.textContent = message;
const setupActions = document.querySelector('.setup-actions');
setupActions.insertBefore(errorDiv, setupActions.firstChild);
// Auto-remove after 5 seconds
setTimeout(() => {
if (errorDiv.parentNode) {
errorDiv.remove();
}
}, 5000);
},
// Start the game
startGame() {
const setupData = this.validateSetup();
if (!setupData) return;
const { playerCount, names } = setupData;
console.log(`Starting game with ${playerCount} players:`, names);
// Initialize game state
gameState = new GameState();
gameState.initializeGame(names);
initializeDecks(gameState);
console.log('Game initialized:', gameState.getStateSummary());
// Hide setup screen and show game area
this.hideSetup();
this.showGameArea();
},
// Hide setup screen
hideSetup() {
const setupScreen = document.getElementById('setup-screen');
setupScreen.classList.add('hidden');
},
// Show game area
showGameArea() {
const gameArea = document.getElementById('game-area');
gameArea.classList.remove('hidden');
// Check game phase and render appropriate interface
if (gameState.gamePhase === GAME_PHASES.EXCHANGE) {
this.renderExchangePhase();
} else {
this.renderGameBoard();
}
this.attachGameEventListeners();
},
// Render the complete game board layout
renderGameBoard() {
const gameArea = document.getElementById('game-area');
const playerCount = gameState.players.length;
const currentPlayerIndex = gameState.currentPlayerIndex;
gameArea.innerHTML = `
<div class="game-board" data-player-count="${playerCount}">
<!-- Current Player Name Display -->
<div class="current-player-display">
<h3 id="current-player-name">${gameState.getCurrentPlayer().name}'s Turn</h3>
</div>
<!-- Game Table Layout -->
<div class="game-table">
<!-- Other Players Areas -->
<div class="other-players-container">
${this.generateOtherPlayersHTML()}
</div>
<!-- Center Area (Draw Pile & Discard Pile) -->
<div class="center-area">
<div class="draw-pile-area">
<div class="pile-container">
<div id="draw-pile" class="card-pile">
${this.renderPileArea('draw')}
</div>
<div class="pile-info">
<span class="pile-count">${gameState.drawPile.length}</span>
<span class="pile-label">Draw</span>
</div>
</div>
</div>
<div class="discard-pile-area">
<div class="pile-container">
<div id="discard-pile" class="card-pile">
${this.renderPileArea('discard')}
</div>
<div class="pile-info">
<span class="pile-count">${gameState.discardPile.length}</span>
<span class="pile-label">Discard</span>
</div>
</div>
</div>
</div>
<!-- Current Player Area (Bottom) -->
<div class="current-player-area">
<div class="player-section" data-player-index="${currentPlayerIndex}">
<h4 class="player-name">${gameState.getCurrentPlayer().name} (You)</h4>
<!-- Player's Cards -->
<div class="player-cards">
<!-- Face-down table cards -->
<div class="card-row face-down-row">
<div class="card-row-label">Face Down</div>
<div class="card-container" id="current-player-face-down">
${this.generatePlayerCardsHTML(gameState.getCurrentPlayer(), 'faceDown', true)}
</div>
</div>
<!-- Face-up table cards -->
<div class="card-row face-up-row">
<div class="card-row-label">Face Up</div>
<div class="card-container" id="current-player-face-up">
${this.generatePlayerCardsHTML(gameState.getCurrentPlayer(), 'faceUp', true)}
</div>
</div>
<!-- Hand cards -->
<div class="card-row hand-row">
<div class="card-row-label">Hand</div>
<div class="card-container" id="current-player-hand">
${this.generatePlayerCardsHTML(gameState.getCurrentPlayer(), 'hand', true)}
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Selection Rules -->
<div class="selection-rules">
<h4>Card Selection Rules:</h4>
<ul>
<li>Select cards of the <strong>same rank</strong> to play together</li>
<li>Must play from <strong>hand cards first</strong> if available</li>
<li>Can play <strong>face-up cards</strong> when hand is empty</li>
<li>Face-down cards are only playable when no other cards remain</li>
</ul>
</div>
<!-- Control Buttons -->
<div class="game-controls">
<div id="selection-info" class="selection-info">No cards selected</div>
<div class="control-buttons">
<button id="play-selected-btn" class="control-btn primary" disabled>Play Selected Cards</button>
<button id="pick-up-pile-btn" class="control-btn secondary">Pick Up Pile</button>
<button id="pass-turn-btn" class="control-btn secondary">Pass to Next Player</button>
<button id="clear-selection-btn" class="control-btn tertiary">Clear Selection</button>
</div>
</div>
<!-- Debug Area (temporary) -->
<div class="debug-area">
<button id="toggle-debug" class="debug-toggle">Show Debug</button>
<div id="debug-panel" class="debug-panel hidden">
<h4>Game State Debug</h4>
<div id="game-state-debug"></div>
<button id="refresh-state-btn" class="debug-btn">Refresh</button>
</div>
</div>
</div>
`;
this.updateGameBoardDisplay();
},
// Generate HTML for other players (not current player)
generateOtherPlayersHTML() {
const currentPlayerIndex = gameState.currentPlayerIndex;
const otherPlayers = gameState.players.filter((_, index) => index !== currentPlayerIndex);
const playerCount = gameState.players.length;
return otherPlayers.map((player, relativeIndex) => {
const actualIndex = gameState.players.findIndex(p => p === player);
const position = this.getPlayerPosition(relativeIndex, playerCount - 1);
return `
<div class="other-player ${position}" data-player-index="${actualIndex}">
<h4 class="player-name">${player.name}</h4>
<div class="player-cards-summary">
<div class="card-summary">
<span class="card-count">${player.faceDownCards.length}</span>
<span class="card-type">Face Down</span>
</div>
<div class="card-summary">
<span class="card-count">${player.faceUpCards.length}</span>
<span class="card-type">Face Up</span>
</div>
<div class="card-summary">
<span class="card-count">${player.handCards.length}</span>
<span class="card-type">Hand</span>
</div>
</div>
<!-- Show actual face-up cards for other players -->
<div class="visible-cards">
${this.generatePlayerCardsHTML(player, 'faceUp', false)}
</div>
</div>
`;
}).join('');
},
// Get position class for other players based on player count
getPlayerPosition(relativeIndex, totalOthers) {
if (totalOthers === 1) {
return 'position-top';
} else if (totalOthers === 2) {
return relativeIndex === 0 ? 'position-top-left' : 'position-top-right';
} else if (totalOthers === 3) {
const positions = ['position-top', 'position-left', 'position-right'];
return positions[relativeIndex];
}
return 'position-top';
},
// Generate HTML for a player's cards
generatePlayerCardsHTML(player, cardType, isCurrentPlayer = false) {
let cards;
let faceDown = false;
let isSelectable = false;
switch(cardType) {
case 'hand':
cards = player.handCards;
isSelectable = isCurrentPlayer; // Only current player can select hand cards
break;
case 'faceUp':
cards = player.faceUpCards;
isSelectable = isCurrentPlayer; // Only current player can select their face-up cards
break;
case 'faceDown':
cards = player.faceDownCards;
faceDown = true;
isSelectable = false; // Face-down cards are never selectable during normal play
break;
default:
return '';
}
if (cards.length === 0) {
return '<div class="empty-card-slot">Empty</div>';
}
return cards.map(card => {
const cardElement = renderCard(card, faceDown, isSelectable);
return cardElement.outerHTML;
}).join('');
},
// Render pile area (draw or discard)
renderPileArea(pileType) {
if (pileType === 'draw') {
if (gameState.drawPile.length > 0) {
// Show face-down card for draw pile with count
const cardHTML = renderCard(gameState.drawPile[gameState.drawPile.length - 1], true).outerHTML;
return `${cardHTML}<div class="pile-count">${gameState.drawPile.length}</div>`;
} else {
return '<div class="empty-pile">Empty Draw Pile</div>';
}
} else if (pileType === 'discard') {
if (gameState.discardPile.length > 0) {
// Show top card prominently with pile info
const topCard = gameState.discardPile[gameState.discardPile.length - 1];
const cardHTML = renderCard(topCard, false).outerHTML;
const pileInfo = `
<div class="pile-info">
<div class="pile-count">${gameState.discardPile.length} cards</div>
<div class="top-card-info">Top: ${topCard.toString()}</div>
</div>
`;
return `${cardHTML}${pileInfo}`;
} else {
return '<div class="empty-pile">Empty Discard Pile<br><small>Any card can be played</small></div>';
}
}
return '<div class="empty-pile">Empty</div>';
},
// Update the game board display
updateGameBoardDisplay() {
// Update current player name
const currentPlayerNameEl = document.getElementById('current-player-name');
if (currentPlayerNameEl) {
currentPlayerNameEl.textContent = `${gameState.getCurrentPlayer().name}'s Turn`;
}
// Update pile counts
const drawPileCount = document.querySelector('.draw-pile-area .pile-count');
const discardPileCount = document.querySelector('.discard-pile-area .pile-count');
if (drawPileCount) drawPileCount.textContent = gameState.drawPile.length;
if (discardPileCount) discardPileCount.textContent = gameState.discardPile.length;
// Update pile visuals
const drawPileElement = document.getElementById('draw-pile');
const discardPileElement = document.getElementById('discard-pile');
if (drawPileElement) {
drawPileElement.innerHTML = this.renderPileArea('draw');
}
if (discardPileElement) {
discardPileElement.innerHTML = this.renderPileArea('discard');
// Add clickable class if pile has cards and we're in playing phase
if (gameState.gamePhase === GAME_PHASES.PLAYING && gameState.discardPile.length > 0) {
discardPileElement.classList.add('clickable');
} else {
discardPileElement.classList.remove('clickable');
}
}
// Update current player cards
this.updateCurrentPlayerCards();
// Update debug display if visible
this.updateGameStateDisplay();
},
// Update current player's card displays
updateCurrentPlayerCards() {
const currentPlayer = gameState.getCurrentPlayer();
const faceDownContainer = document.getElementById('current-player-face-down');
const faceUpContainer = document.getElementById('current-player-face-up');
const handContainer = document.getElementById('current-player-hand');
if (faceDownContainer) {
faceDownContainer.innerHTML = this.generatePlayerCardsHTML(currentPlayer, 'faceDown', true);
}
if (faceUpContainer) {
faceUpContainer.innerHTML = this.generatePlayerCardsHTML(currentPlayer, 'faceUp', true);
}
if (handContainer) {
handContainer.innerHTML = this.generatePlayerCardsHTML(currentPlayer, 'hand', true);
}
// Re-attach card selection listeners
this.attachCardSelectionListeners();
},
// Exchange Phase Management
renderExchangePhase() {
const gameArea = document.getElementById('game-area');
const currentPlayer = gameState.getCurrentPlayer();
const currentPlayerIndex = gameState.currentPlayerIndex;
const totalPlayers = gameState.players.length;
gameArea.innerHTML = `
<div class="exchange-phase">
<div class="exchange-header">
<h2>Card Exchange Phase</h2>
<p class="exchange-subtitle">Players can swap cards between hand and face-up positions</p>
<div class="exchange-progress">
<span>Player ${currentPlayerIndex + 1} of ${totalPlayers}: <strong>${currentPlayer.name}</strong></span>
</div>
</div>
<div class="exchange-instructions">
<div class="instructions-card">
<h3>Instructions for ${currentPlayer.name}</h3>
<ul>
<li>Click a <strong>Hand Card</strong>, then click a <strong>Face-Up Card</strong> to swap them</li>
<li>Face-up cards will be visible to all players during the game</li>
<li>Choose your face-up cards wisely - other players can see them!</li>
<li>Click "Confirm Exchanges" when you're satisfied with your arrangement</li>
</ul>
</div>
</div>
<div class="exchange-player-area">
<h3>${currentPlayer.name}'s Cards</h3>
<div class="exchange-cards">
<!-- Hand Cards -->
<div class="exchange-row">
<div class="card-section-header">
<h4>Hand Cards</h4>
<p>Click to select for swapping</p>
</div>
<div class="card-container exchange-hand" id="exchange-hand">
${this.generateExchangeCardsHTML(currentPlayer.handCards, 'hand')}
</div>
</div>
<!-- Face-Up Cards -->
<div class="exchange-row">
<div class="card-section-header">
<h4>Face-Up Cards</h4>
<p>Will be visible to all players</p>
</div>
<div class="card-container exchange-face-up" id="exchange-face-up">
${this.generateExchangeCardsHTML(currentPlayer.faceUpCards, 'faceUp')}
</div>
</div>
<!-- Face-Down Cards (non-interactive) -->
<div class="exchange-row">
<div class="card-section-header">
<h4>Face-Down Cards</h4>
<p>Hidden until later in the game</p>
</div>
<div class="card-container exchange-face-down">
${this.generateExchangeCardsHTML(currentPlayer.faceDownCards, 'faceDown')}
</div>
</div>
</div>
</div>
<div class="exchange-controls">
<button id="confirm-exchanges-btn" class="exchange-btn primary">Confirm Exchanges</button>
<button id="reset-exchanges-btn" class="exchange-btn secondary">Reset to Original</button>
</div>
<!-- Debug Area (temporary) -->
<div class="debug-area">
<button id="toggle-debug" class="debug-toggle">Show Debug</button>
<div id="debug-panel" class="debug-panel hidden">
<h4>Exchange Debug</h4>
<div id="game-state-debug"></div>
<button id="refresh-state-btn" class="debug-btn">Refresh</button>
</div>
</div>
</div>
`;
this.initializeExchangeState();
this.updateGameStateDisplay();
},
// Generate HTML for exchange cards
generateExchangeCardsHTML(cards, cardType) {
if (cards.length === 0) {
return '<div class="empty-card-slot">Empty</div>';
}
return cards.map(card => {
const isSelectable = cardType === 'hand' || cardType === 'faceUp';
const isFaceDown = cardType === 'faceDown';
const cardElement = renderCard(card, isFaceDown, isSelectable);
if (isSelectable) {
cardElement.classList.add('exchange-card');
cardElement.dataset.cardType = cardType;
cardElement.dataset.cardId = card.id;
}
return cardElement.outerHTML;
}).join('');
},
// Initialize exchange state tracking
initializeExchangeState() {
this.exchangeState = {