-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtableManager.js
More file actions
1676 lines (1408 loc) · 56.9 KB
/
tableManager.js
File metadata and controls
1676 lines (1408 loc) · 56.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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
(() => {
const tableContainer = document.getElementById('table-container');
const playersContainer = document.getElementById('playersContainer');
const contractsContainer = document.getElementById('contractsContainer');
const drawPileDiv = document.getElementById('drawPile');
const discardPileDiv = document.getElementById('discardPile');
const suitOrder = ['♦', '♥', '♣', '♠', '★'];
const rankOrder = ['A','2','3','4','5','6','7','8','9','10','J','Q','K','A','W'];
const roundHistory = [];
const OVERLAP_PCT = 0.35; // 35% overlap
let players = [];
let contracts = [];
let hands = {};
let subcontractCards = {}; // flat arrays of cards per player including subArea property
let drawPile = [];
let discardPile = [];
let hasDrawn = false;
window.hasDrawn = hasDrawn;
let RoundStarter = 0;
let roundFinished = false;
// Customization defaults & variables
let suitColors = {};
let backColors = { center: "#000000", edge1: "#333333", edge2: "#666666", edge3: "#999999", outline: "#ffffff", edgeWidth: 6 };
let suitSize = 90;
let rankSize = 65;
// Round index variable
let roundIndex = 0;
let Softwindow = false;
let Hardwindow = false;
// Contracts text by round
const roundContracts = [
"2 Sets",
"1 Set + 1 Run",
"2 Runs",
"3 Sets",
"2 Sets + 1 Run",
"1 Set + 2 Runs",
"3 Runs"
];
const CONTRACT_SUB_AREAS = {
1: ['Set 1', 'Set 2'],
2: ['Set 1', 'Run 1'],
3: ['Run 1', 'Run 2'],
4: ['Set 1', 'Set 2', 'Set 3'],
5: ['Set 1', 'Set 2', 'Run 1'],
6: ['Set 1', 'Run 1', 'Run 2'],
7: ['Run 1', 'Run 2', 'Run 3']
};
function getMyTurnPlayerIndex() {
return players.findIndex((_, i) => {
const el = document.getElementById(`player-${i}`);
return el?.classList.contains('MyTurn');
});
}
function isWild(card) {
const rules = window.gameRules || {};
if (!rules.wildsEnabled) return false;
const type = (rules.wildType || 'classic').toLowerCase();
if (type === 'classic')
return card.rank === '3' && (card.suit === '♦' || card.suit === '♥');
if (type === 'extra')
return (
card.rank === '3' &&
(card.suit === '♦' || card.suit === '♥' || card.suit === '★')
);
if (type === 'joker')
return card.rank === 'W';
return false;
}
function isValidSet(cards) {
const wildCnt = cards.filter(isWild).length;
const nonWild = cards.filter(c => !isWild(c));
// If there are no non‑wild cards, we need at least 3 wilds.
if (nonWild.length === 0) return wildCnt >= 3;
// Gather the distinct ranks among the non‑wild cards.
const distinctRanks = [...new Set(nonWild.map(c => c.rank))];
// More than one rank → cannot be a single set.
if (distinctRanks.length > 1) return false;
// All non‑wild cards share the same rank.
const needed = Math.max(0, 3 - nonWild.length); // how many wilds we need
return wildCnt >= needed;
}
function isValidRun(cards) {
// --------------------------------------------------------------
// 1️⃣ Split wilds from the rest.
// --------------------------------------------------------------
const wildCnt = cards.filter(isWild).length;
const nonWild = cards.filter(c => !isWild(c));
const totalLen = nonWild.length + wildCnt; // exact length of the run
if (totalLen < 4) return false; // need ≥4 cards
// If there are no non‑wild cards, any 4+ wilds are a valid run.
if (nonWild.length === 0) return wildCnt >= 4;
// --------------------------------------------------------------
// 2️⃣ All non‑wild cards must share one suit.
// --------------------------------------------------------------
const distinctSuits = [...new Set(nonWild.map(c => c.suit))];
if (distinctSuits.length > 1) return false;
const runSuit = distinctSuits[0];
// Choose rank order with possible wrapAround
const wrapAround = window.gameRules?.wrapAround ?? false;
let extendedRankOrder = rankOrder;
if (wrapAround) {
// For wrapAround, extend rankOrder to allow Q-K-A-2 sequences
// rankOrder is ['A','2','3',...,'K','A','W']
// We create a cycle by appending '2','3','4' at the end so Q-K-A-2 is valid
extendedRankOrder = ['A','2','3','4','5','6','7','8','9','10','J','Q','K','A','2','3','4','5','6','7','8','9','10','J','Q','K','A'];
const maxStart = extendedRankOrder.length - totalLen;
const matchesSequence = (seq) => {
let usedWilds = 0;
for (let i = 0; i < cards.length; ++i) {
const card = cards[i];
if (isWild(card)) {
usedWilds++;
continue;
}
if (card.rank !== seq[i] || card.suit !== runSuit) return false;
}
return usedWilds <= wildCnt;
};
for (let start = 0; start <= maxStart; ++start) {
// Ascending e.g. 5-6-7-8 or wrap e.g. Q-K-A-2
const ascSeq = extendedRankOrder.slice(start, start + totalLen);
if (matchesSequence(ascSeq)) return true;
// Descending sequence (reverse)
const descSeq = [...ascSeq].reverse();
if (matchesSequence(descSeq)) return true;
}
return false;
}
// --------------------------------------------------------------
// 3️⃣ Build every possible *ordered* rank sequence that could
// represent a run of length `totalLen`. We generate both
// forward (ascending) and backward (descending) sequences.
// --------------------------------------------------------------
const maxStart = rankOrder.length - totalLen; // inclusive upper bound
// Helper: does the container match the supplied rank sequence?
const matchesSequence = (seq) => {
let usedWilds = 0;
for (let i = 0; i < cards.length; ++i) {
const card = cards[i];
if (isWild(card)) {
// Wild can always fill the current slot.
usedWilds++;
continue;
}
// Concrete card must match the expected rank *and* the run suit.
if (card.rank !== seq[i] || card.suit !== runSuit) return false;
}
// We must not have used more wilds than we actually have.
return usedWilds <= wildCnt;
};
// --------------------------------------------------------------
// 4️⃣ Try every start position in both directions.
// --------------------------------------------------------------
for (let start = 0; start <= maxStart; ++start) {
// ----- Ascending (e.g. 5‑6‑7‑8) -----
const ascSeq = rankOrder.slice(start, start + totalLen);
if (matchesSequence(ascSeq)) return true;
// ----- Descending (e.g. 8‑7‑6‑5) -----
const descSeq = [...ascSeq].reverse(); // reverse of the same slice
if (matchesSequence(descSeq)) return true;
}
// No possible ordered sequence fits → not a valid run.
return false;
}
window.isValidSet = isValidSet;
window.isValidRun = isValidRun;
function validateLayDown(playerIdx) {
const player = players[playerIdx];
const subAreas = getSubcontractSubAreas(playerIdx); // <-- now uses the API wrapper
const roundNum = roundIndex; // current round (global)
const expectedLabelst = CONTRACT_SUB_AREAS[roundNum] || [];
// Reset all sub‑area colours first
subAreas.forEach(sa => (sa.style.backgroundColor = '#fff'));
// Validate each sub‑area individually
subAreas.forEach((sub, areaIdx) => {
const label = sub.dataset.label || '';
const cardsInArea = (subcontractCards[player] || []).filter(
c => c.subArea === areaIdx
);
let ok = false;
if (label.toLowerCase().includes('set')) ok = isValidSet(cardsInArea);
else if (label.toLowerCase().includes('run')) ok = isValidRun(cardsInArea);
sub.style.backgroundColor = ok ? '#c8e6c9' : '#fff';
});
}
function populateContractSubAreas(roundNum) {
const labels = CONTRACT_SUB_AREAS[roundNum] || [];
contracts.forEach((contractDiv, i) => {
if (!contractDiv) return;
// Clear previous sub-areas before populating (prevent duplicates on new rounds)
contractDiv.innerHTML = '';
// Build a non-wrapping flex container for the sub-areas
const wrapper = document.createElement('div');
wrapper.style.display = 'flex';
wrapper.style.flexDirection = 'row';
wrapper.style.flexWrap = 'nowrap'; // prevent vertical wrap
wrapper.style.gap = '8px'; // visible separation between sub-areas
wrapper.style.padding = '4px';
wrapper.style.border = `1px dashed ${backColors.outline}`;
wrapper.style.borderRadius = '6px';
wrapper.style.minWidth = '0'; // allow the wrapper to shrink if needed
contractDiv.appendChild(wrapper);
labels.forEach(label => {
const sub = document.createElement('div');
sub.className = 'contract-subarea';
sub.dataset.label = label;
sub.dataset.playerIndex = i;
sub.dataset.myTurn = (players[i] &&
document.getElementById(`player-${i}`).classList.contains('MyTurn'))
? 'true' : 'false';
sub.style.flex = '0 0 auto'; // fixed width to content
sub.style.flexShrink = '0';
sub.style.maxWidth = 'none';
sub.style.minWidth = '0';
sub.style.padding = '2px';
sub.style.borderRadius = '4px';
sub.style.border = '1px solid #000';
sub.style.backgroundColor = '#fff';
sub.style.display = 'flex';
sub.style.alignItems = 'center';
sub.style.justifyContent = 'space-between';
sub.style.fontSize = '0.85rem';
sub.style.fontWeight = '500';
sub.style.boxSizing = 'border-box';
sub.style.minHeight = '75px';
sub.style.userSelect = 'none';
const lbl = document.createElement('span');
lbl.textContent = label;
sub.appendChild(lbl);
const placeholder = document.createElement('span');
placeholder.textContent = '';
sub.appendChild(placeholder);
wrapper.appendChild(sub);
});
});
}
function getCookie(name) {
if (!document.cookie) return null;
const cookies = document.cookie.split('; ');
for (let pair of cookies) {
const i = pair.indexOf('=');
if (i === -1) continue;
const k = pair.substring(0, i);
if (k === name) {
try {
return decodeURIComponent(pair.substring(i + 1));
} catch {
return pair.substring(i + 1);
}
}
}
return null;
}
function suitToKey(suit) {
switch (suit) {
case '♦': return 'diamonds';
case '♥': return 'hearts';
case '♣': return 'clubs';
case '♠': return 'spades';
case '★': return 'stars';
default: return 'hearts';
}
}
function isRedSuit(suit) { return suit === '♦' || suit === '♥'; }
function safeNumber(val, fallback) {
if (val === undefined || val === null) return fallback;
const n = Number(val);
return Number.isNaN(n) ? fallback : n;
}
function setDefaultSuitColors() {
suitColors = {
diamonds: { symbol: '#ffff5c', background: '#bbb', outline: '#444' },
clubs: { symbol: '#00e9f1', background: '#bbb', outline: '#444' },
hearts: { symbol: '#e97311', background: '#bbb', outline: '#444' },
spades: { symbol: '#01ff05', background: '#bbb', outline: '#444' },
stars: { symbol: 'white', background: '#bbb', outline: '#444' }
};
}
function setDefaultBackColors() {
backColors = {
center: '#f9d71c',
edge1: '#e39e13',
edge2: '#cf7518',
edge3: '#a05108',
outline: '#3a2e01',
edgeWidth: 6
};
}
function loadCustomization() {
try {
const ccStr = getCookie('cardCustom');
if (!ccStr) {
setDefaultSuitColors();
setDefaultBackColors();
return;
}
const cc = JSON.parse(ccStr);
if (cc.suitColors) {
suitColors = {};
for (let key in cc.suitColors) {
if (!Object.prototype.hasOwnProperty.call(cc.suitColors, key)) continue;
const entry = cc.suitColors[key];
suitColors[key] = {
symbol: entry.symbol || 'white',
background: entry.background || '#bbb',
outline: entry.outline || 'green'
};
}
} else {
setDefaultSuitColors();
}
if (cc.backColors) {
backColors = Object.assign({}, backColors, cc.backColors);
backColors.edgeWidth = safeNumber(backColors.edgeWidth, backColors.edgeWidth);
} else {
setDefaultBackColors();
}
suitSize = safeNumber(cc.suitSize, 90);
rankSize = safeNumber(cc.rankSize, 65);
} catch (e) {
console.warn("Failed to parse cardCustom cookie", e);
setDefaultSuitColors();
setDefaultBackColors();
}
}
function loadRules() {
try {
const crStr = getCookie('customRules');
if (!crStr) return {};
return JSON.parse(crStr);
} catch {
return {};
}
}
function createPlayers(playerNames) {
players = playerNames;
contracts = new Array(playerNames.length).fill(null);
subcontractCards = {};
playerNames.forEach(p => subcontractCards[p] = []);
for (let i = 0; i < players.length; i++) {
const playerDiv = document.createElement('div');
playerDiv.className = 'player';
playerDiv.id = `player-${i}`;
playerDiv.style.position = 'absolute';
const nameplate = document.createElement('div');
nameplate.className = 'nameplate';
nameplate.textContent = players[i];
const layBtn = document.createElement('button');
layBtn.className = 'lay-down-btn';
layBtn.type = 'button';
layBtn.textContent = 'Lay Down';
// Initial state – will be refreshed later by `refreshLayButtons()`
layBtn.disabled = true;
layBtn.addEventListener('click', LayDownClick);
const stats = document.createElement('div');
stats.className = 'stats';
const topRow = document.createElement('div');
topRow.style.display = 'flex';
topRow.style.justifyContent = 'space-between';
topRow.style.width = '100%';
const buysDiv = document.createElement('div');
buysDiv.className = 'stat-buys';
buysDiv.textContent = 'Buys: 3';
const heldPointsDiv = document.createElement('div');
heldPointsDiv.className = 'stat-held';
heldPointsDiv.textContent = 'Held: 0';
topRow.appendChild(buysDiv);
topRow.appendChild(heldPointsDiv);
const bottomRow = document.createElement('div');
bottomRow.style.display = 'flex';
bottomRow.style.justifyContent = 'space-between';
bottomRow.style.width = '100%';
const cardsDiv = document.createElement('div');
cardsDiv.className = 'stat-cards';
cardsDiv.textContent = 'Cards: 0';
const scoreDiv = document.createElement('div');
scoreDiv.className = 'stat-score';
scoreDiv.textContent = 'Score: 0';
bottomRow.appendChild(cardsDiv);
bottomRow.appendChild(scoreDiv);
stats.appendChild(topRow);
stats.appendChild(bottomRow);
const handArea = document.createElement('div');
handArea.className = 'hand-area';
handArea.id = `hand-${i}`;
handArea.style.position = 'relative';
handArea.style.display = 'flex';
handArea.style.alignItems = 'center';
handArea.style.marginTop = '8px';
const _handStyle = document.createElement('style');
_handStyle.textContent = `.hand-area{min-width:40px;}`;
document.head.appendChild(_handStyle);
playerDiv.appendChild(nameplate);
playerDiv.appendChild(layBtn);
playerDiv.appendChild(stats);
playerDiv.appendChild(handArea);
if (playersContainer) playersContainer.appendChild(playerDiv);
// contract area
const contractDiv = document.createElement('div');
contractDiv.className = 'contract-area';
contractDiv.id = `contract-${i}`;
contractDiv.style.display = 'inline-block';
contractDiv.style.whiteSpace = 'nowrap';
if (contractsContainer) contractsContainer.appendChild(contractDiv);
contracts[i] = contractDiv;
}
}
function layoutPiles() {
if (!tableContainer || !drawPileDiv || !discardPileDiv) return;
const centerX = tableContainer.clientWidth / 2;
const centerY = tableContainer.clientHeight / 2;
const spacing = 160;
const pileWidth = drawPileDiv.offsetWidth || 120;
const pileHeight = drawPileDiv.offsetHeight || 160;
drawPileDiv.style.left = (centerX - spacing / 2 - pileWidth / 2) + "px";
drawPileDiv.style.top = (centerY - pileHeight / 2) + "px";
discardPileDiv.style.left = (centerX + spacing / 2 - pileWidth / 2) + "px";
discardPileDiv.style.top = (centerY - pileHeight / 2) + "px";
const c = backColors;
const grad = `radial-gradient(circle at center,
${c.center} 0%,
${c.edge1} 25%,
${c.edge2} 50%,
${c.edge3} 75%,
${c.edge3} 80%
)`;
[drawPileDiv].forEach(pile => {
if (!pile) return;
pile.style.background = grad;
pile.style.border = `${c.edgeWidth}px solid ${c.outline}`;
pile.style.borderRadius = '10px';
pile.style.boxSizing = 'border-box';
pile.style.lineHeight = `${pileHeight}px`;
pile.style.userSelect = 'none';
pile.style.cursor = 'default';
});
}
function drawCardFrom(source, playerIdx) {
if (playerIdx === undefined) {
playerIdx = getMyTurnPlayerIndex();
}
if (playerIdx < 0) return; // no player to draw for
// Block draw if player already drew on their turn
if (hasDrawn && playerIdx === getMyTurnPlayerIndex()) return;
let card = null;
if (source === 'draw') {
// If there is only one card left, try reshuffle discard pile into draw pile
if (drawPile && drawPile.length === 1) {
if (window.initDeckInstance && typeof window.initDeckInstance.reshuffle === 'function') {
const result = window.initDeckInstance.reshuffle(drawPile, discardPile);
drawPile = result.drawPile;
discardPile = result.discardPile;
} else {
console.warn("Fallback shuffle");
// fallback shuffle logic omitted for brevity
}
}
if (drawPile.length === 0) return; // no card to draw
card = drawPile.pop();
} else if (source === 'discard') {
if (discardPile.length === 0) return;
card = discardPile.pop();
}
if (!card) return;
hands[players[playerIdx]].push(card);
// Mark drawn only for the current turn player
if (playerIdx === getMyTurnPlayerIndex()) {
hasDrawn = true;
window.hasDrawn = true;
const playerDiv = document.getElementById(`player-${playerIdx}`);
if (playerDiv) playerDiv.classList.add('HasDrawn');
}
cardManager.setupDragDrop();
renderHands(hands);
if (source === 'discard') {
cardManager.renderDiscardPile();
}
}
window.drawCardFrom = drawCardFrom;
function calculateCardPoints(card, wildCardsEnabled, wildType) {
const rank = card.rank;
const suit = card.suit;
function isWildCard() {
if (!wildCardsEnabled) return false;
if (wildType === 'classic') return (rank === '3' && (suit === '♦' || suit === '♥'));
if (wildType === 'extra') return (rank === '3' && (suit === '♦' || suit === '♥' || suit === '★'));
if (wildType === 'joker') return (rank === 'W' && (suit === '♥' || suit === '♠'));
return false;
}
if (isWildCard()) return 20;
if (rank === '3') return 3;
if (rank === 'A') return 15;
if (['10', 'J', 'Q', 'K'].includes(rank)) return 10;
if ('2 4 5 6 7 8 9'.split(' ').includes(rank)) return Number(rank);
if (rank === 'W') return 20;
return 0;
}
// UPDATED HERE - count subcontract cards also for Cards and Held stats
function updatePlayerStats(handsObj) {
window.updatePlayerStats = updatePlayerStats;
const customRulesStr = getCookie('customRules');
let wildCardsEnabled = true;
let wildType = 'classic';
try {
if (customRulesStr) {
const cr = JSON.parse(customRulesStr);
wildCardsEnabled = cr.wildCardsChk ?? true;
wildType = (cr.wildType || 'classic').toLowerCase();
}
} catch {}
players.forEach((player, i) => {
const hand = handsObj[player] || [];
const playerDiv = document.getElementById(`player-${i}`);
if (!playerDiv) return;
const stats = playerDiv.querySelector('.stats');
if (!stats) return;
// ----- CARDS & HELD -----
// If the player has already laid down, we *exclude* subcontract cards
// from the stats calculations.
const hasLaidDown = playerDiv.classList.contains('HasLaidDown');
const subcontract = subcontractCards[player] || [];
const cardsForStats = hasLaidDown ? hand : hand.concat(subcontract);
// Count points
let heldPoints = 0;
cardsForStats.forEach(card => {
heldPoints += calculateCardPoints(card, wildCardsEnabled, wildType);
});
const heldPointsDiv = stats.querySelector('.stat-held');
if (heldPointsDiv) heldPointsDiv.textContent = `Held: ${heldPoints}`;
const cardsDiv = stats.querySelector('.stat-cards');
if (cardsDiv) cardsDiv.textContent = `Cards: ${cardsForStats.length}`;
const stillMyTurn = playerDiv.classList.contains('MyTurn');
if (cardsForStats.length === 0) {
endRound(player);
}
});
}
function endRound(triggerPlayer) {
if (roundFinished) return;
roundFinished = true;
const roundScores = [];
players.forEach((p, i) => {
const playerDiv = document.getElementById(`player-${i}`);
const stats = playerDiv?.querySelector('.stats');
if (!stats) return;
const heldDiv = stats.querySelector('.stat-held');
const scoreDiv = stats.querySelector('.stat-score');
const buysDiv = playerDiv.querySelector('.stat-buys');
if (buysDiv) {
// Set the displayed text to “Buys: 3”
buysDiv.textContent = 'Buys: 3';
}
// ----- read numbers ----------------------------------------------------
let heldVal = heldDiv
? Number(heldDiv.textContent.split(':')[1].trim())
: 0
if (window.gameRules.finalShanghai && Hardwindow && roundIndex === 7 && heldVal > 0) {
heldVal += 100;
} else if (Hardwindow && heldVal > 0) {
heldVal += 50;
} else if (Softwindow && heldVal > 0) {
heldVal += 25;
}
let scoreVal = scoreDiv
? Number(scoreDiv.textContent.split(':')[1].trim())
: 0;
// ----- accumulate -------------------------------------------------------
scoreVal = scoreVal + heldVal;
// ----- write back -------------------------------------------------------
if (scoreDiv) {
scoreDiv.textContent = `Score: ${scoreVal}`;
}
// Save this round’s held value for the history table
roundScores.push(heldVal);
});
// -----------------------------------------------------------------------
// 2️⃣ Store the round in the global history array
// -----------------------------------------------------------------------
roundHistory.push({
round: roundIndex, // the round that just finished
scores: roundScores // array of held values, one per player (same order as `players`)
});
// 2️⃣ Show “Round‑Winner” popup
const roundWinnerPopup = document.createElement('div');
roundWinnerPopup.className = 'round-winner-popup';
if (Hardwindow && roundIndex === 7){
roundWinnerPopup.textContent = `${triggerPlayer} won the FINAL Round with a Shanghai! +100 points to everyone else!`;
} else if (Hardwindow) {
roundWinnerPopup.textContent = `${triggerPlayer} won the Round with a Shanghai! +50 points to everyone else!`;
} else if (Softwindow) {
roundWinnerPopup.textContent = `${triggerPlayer} won the Round with a Soft Shanghai! +25 points to everyone else!`;
} else {
roundWinnerPopup.textContent = `${triggerPlayer} won the Round!`;
}
document.body.appendChild(roundWinnerPopup);
const closeRoundWinner = () => {
roundWinnerPopup.removeEventListener('click', closeRoundWinner);
window.removeEventListener('keydown', closeRoundWinner);
roundWinnerPopup.remove();
// 3️⃣ Record scores & show the cumulative scores grid
showScoresPopup();
// 4️⃣ Decide what happens next (next round or game over)
if (roundIndex >= 7) {
// Game finished – highlight lowest total & announce winner
showGameWinnerPopup();
} else {
// Continue – start next round after the scores popup is dismissed
startNextRound();
}
};
roundWinnerPopup.addEventListener('click', closeRoundWinner);
window.addEventListener('keydown', closeRoundWinner);
}
function showScoresPopup() {
let container = document.getElementById('scores-popup');
if (!container) {
container = document.createElement('div');
container.id = 'scores-popup';
container.className = 'scores-popup';
document.body.appendChild(container);
}
let title = container.querySelector('.scores-title');
if (!title) {
title = document.createElement('div');
title.className = 'scores-title';
title.textContent = 'Player Scores';
title.style.textAlign = 'center';
title.style.fontWeight = 'bold';
title.style.marginBottom = '8px';
container.prepend(title);
}
let header = container.querySelector('.scores-header');
if (!header) {
header = document.createElement('div');
header.className = 'scores-header';
const headerHTML =
`<div class="cell corner"></div>` +
players.map(p => `<div class="cell player-name">${p}</div>`).join('');
header.innerHTML = headerHTML;
container.appendChild(header);
}
// Clear previous rows except header and title
[...container.querySelectorAll('.scores-row')].forEach(row => row.remove());
const totalRow = container.querySelector('.scores-total-row');
if (totalRow) totalRow.remove();
// Add all rounds from roundHistory
roundHistory.forEach(rh => {
const row = document.createElement('div');
row.className = 'scores-row';
const roundCell = `<div class="cell round-index">Round ${rh.round}</div>`;
const scoreCells = rh.scores.map(score => `<div class="cell score">${score}</div>`).join('');
row.innerHTML = roundCell + scoreCells;
container.appendChild(row);
});
// Calculate total for each player summing rounds from roundHistory
const totals = players.map((_, i) => {
return roundHistory.reduce((sum, rh) => sum + (rh.scores[i] || 0), 0);
});
const totalLabel = `<div class="cell round-index">Total</div>`;
const totalCells = totals.map(totalScore => `<div class="cell score">${totalScore}</div>`).join('');
const totalHTML = totalLabel + totalCells;
const newTotalRow = document.createElement('div');
newTotalRow.className = 'scores-row scores-total-row';
newTotalRow.innerHTML = totalHTML;
container.appendChild(newTotalRow);
const close = () => {
container.removeEventListener('click', close);
window.removeEventListener('keydown', close);
container.remove();
};
container.addEventListener('click', close);
window.addEventListener('keydown', close);
}
function showGameWinnerPopup() {
// First compute total scores per player across all rounds
const totals = players.map((p, i) => {
let sum = 0;
// Walk through every scores‑row that was added to the scores‑popup
const rows = document.querySelectorAll('#scores-popup .scores-row');
rows.forEach(r => {
const cells = r.querySelectorAll('.cell.score');
const val = Number(cells[i].textContent.trim());
sum += val;
});
return sum;
});
const minScore = Math.min(...totals);
const winners = players.filter((_, i) => totals[i] === minScore);
const winnerName = winners.length === 1 ? winners[0] : winners.join(', ');
// Highlight the lowest total in the grid (add a CSS class)
const rows = document.querySelectorAll('#scores-popup .scores-row');
rows.forEach(r => {
const cells = r.querySelectorAll('.cell.score');
cells.forEach((c, idx) => {
if (totals[idx] === minScore) c.classList.add('lowest-score');
});
});
// Show the final popup
const finalPopup = document.createElement('div');
finalPopup.className = 'game-winner-popup';
finalPopup.textContent = `${winnerName} won the game!`;
document.body.appendChild(finalPopup);
const closeFinal = () => {
finalPopup.removeEventListener('click', closeFinal);
window.removeEventListener('keydown', closeFinal);
finalPopup.remove();
// Optional: you could reset the whole UI here or offer a “New Game” button.
};
finalPopup.addEventListener('click', closeFinal);
window.addEventListener('keydown', closeFinal);
}
async function startNextRound() {
roundFinished = false;
Softwindow = false;
Hardwindow = false;
roundIndex++;
await showRoundPopup(roundIndex);
// 1️⃣ Gather every card back into a single array
const allCards = [];
players.forEach((_, i) => {
const playerDiv = document.getElementById(`player-${i}`);
if (playerDiv) {
playerDiv.classList.remove('MyTurn', 'HasDrawn', 'HasLaidDown', 'Idiscarded');
}
});
players.forEach((p) => {
const hand = hands[p] || [];
allCards.push(...hand);
hands[p] = []; // clear hand for next round
const sub = subcontractCards[p] || [];
allCards.push(...sub);
subcontractCards[p] = []; // clear
const playerDiv = document.getElementById(`player-${p}`);
});
hasDrawn = false;
if (drawPile && drawPile.length) {
allCards.push(...drawPile);
drawPile = [];
}
if (discardPile && discardPile.length) {
allCards.push(...discardPile);
//discardPile = [];
discardPile.length = 0;
}
if (window.initDeckInstance && typeof window.initDeckInstance.shuffle === 'function') {
drawPile = window.initDeckInstance.shuffle(allCards);
}
populateContractSubAreas(roundIndex);
if (RoundStarter >= players.length - 1) {
RoundStarter = -1;
}
RoundStarter++;
const firstPlayerDiv = document.getElementById(`player-${RoundStarter}`);
if (firstPlayerDiv) {
firstPlayerDiv.classList.add('round-starter');
firstPlayerDiv.classList.add('MyTurn');
hasDrawn = false;
//window.hasDrawn = false;
}
// 5️⃣ Deal 10 cards to each player (mirroring initTable logic)
players.forEach(p => {
const dealt = [];
for (let i = 0; i < 10 && drawPile.length; i++) {
dealt.push(drawPile.pop());
}
hands[p] = dealt;
subcontractCards[p] = [];
if (roundIndex === 1 || roundIndex === 4) {
hands[p] = sortByRank(hands[p]);
} else {
hands[p] = sortBySuitThenRank(hands[p]);
}
});
cardManager.renderAllSubcontractAreas();
cardManager.setupDragDrop();
// 6️⃣ Refresh UI – re‑render hands, discard pile, subcontract areas,
// lay‑down buttons and player stats.
renderHands(hands);
cardManager.renderDiscardPile();
refreshLayButtons();
}
function renderHands(handsObj) {
players.forEach((_, i) => {
const handArea = document.getElementById(`hand-${i}`);
if (!handArea) return;
handArea.innerHTML = '';
const draggable = playerHasMyTurn(i);
cardManager.renderCardArray(handsObj[players[i]], handArea, draggable, i, 'hand');
});
updatePlayerStats(handsObj);
}
function sortByRank(cards) {
return cards.sort((a, b) => rankOrder.indexOf(a.rank) - rankOrder.indexOf(b.rank));
}
function sortBySuitThenRank(cards) {
return cards.sort((a,b) => {
const suitDiff = suitOrder.indexOf(a.suit) - suitOrder.indexOf(b.suit);
return suitDiff !== 0 ? suitDiff : rankOrder.indexOf(a.rank) - rankOrder.indexOf(b.rank);
});
}
function showRoundPopup(roundNum) {
return new Promise((resolve) => {
const popup = document.createElement('div');
popup.id = 'round-popup';
popup.classList.add('round-popup');
const contractText = roundContracts[roundNum - 1] || `Round ${roundNum}: Unknown Contract`;
popup.textContent = `Round ${roundNum}:\n${contractText}`;
const lines = popup.textContent.split('\n');
popup.textContent = '';
lines.forEach(line => {
const lineDiv = document.createElement('div');
lineDiv.textContent = line;
popup.appendChild(lineDiv);
});
document.body.appendChild(popup);
function closePopup() {
if (popup.parentNode) popup.parentNode.removeChild(popup);
window.removeEventListener('keydown', onKeyDown);
window.removeEventListener('click', onClick);
resolve(); // Resolve the Promise when popup closes
}
function onKeyDown() { closePopup(); }
function onClick() { closePopup(); }
window.addEventListener('keydown', onKeyDown);
window.addEventListener('click', onClick);
});
}
function layoutPlayers() {
if (!tableContainer || players.length === 0) return;
const w = tableContainer.clientWidth;
const h = tableContainer.clientHeight;
const marginH = 180;
const marginVTop = 180;
const marginVBottom = 270;
const topLen = Math.max(0, w - 2 * marginH);
const rightLen = Math.max(0, h - marginVTop - marginVBottom);
const perimeter = topLen * 2 + rightLen * 2;
const cornerInset = players.length >= 8 ? 110 : 90;
players.forEach((_, i) => {
const playerDiv = document.getElementById(`player-${i}`);
const contractDiv = contracts[i];
if (!playerDiv) return;
let dist = i / players.length * perimeter;
let sideIndex = 0;
const sides = [topLen, rightLen, topLen, rightLen];