-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·931 lines (729 loc) · 25.6 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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
let game;
let $moveSource;
let $buildPiles = [];
let $cpuHandRow;
let $cpuDiscardRow;
let $cpuHand = [];
let $humanHand = [];
let $humanHandRow;
let $humanDiscardRow;
let $cpuDiscardPiles = [];
let $humanDiscardPiles = [];
let $discardPileContents;
let $cpuStockPile;
let $humanStockPile;
let $drawPile;
let $appName;
let $record;
let $newGame;
let $humanPlayerArea;
let $cpuPlayerArea;
let $help;
let longPressTimer;
let didLongPress = false;
let animationDuration = 600;
function _loadElementsFromPage() {
$appName = document.getElementById("app-name");
$help = document.getElementById("help");
$record = document.getElementById("record");
// CPU player
$cpuPlayerArea = document.getElementById("cpu-player-area");
for (let i = 0; i < 5; ++i)
$cpuHand[i] = document.getElementById(`cpu-hand-${i}`);
for (let i = 0; i < 4; ++i)
$cpuDiscardPiles[i] = document.getElementById(`cpu-discard-${i}`);
$cpuStockPile = document.getElementById("cpu-stock");
$cpuHandRow = document.getElementById("cpu-hand");
$cpuDiscardRow = document.getElementById("cpu-discard");
// Human player
$humanPlayerArea = document.getElementById("human-player-area");
$humanHandRow = document.getElementById("human-hand");
$humanDiscardRow = document.getElementById("human-discard");
for (let i = 0; i < 5; ++i) {
$humanHand[i] = document.getElementById(`human-hand-${i}`);
$humanHand[i].addEventListener("click", _didClickHumanHandCard);
}
for (let i = 0; i < 4; ++i) {
$humanDiscardPiles[i] = document.getElementById(`human-discard-${i}`);
$humanDiscardPiles[i].addEventListener('mousedown', () => startLongPressTimer(i));
$humanDiscardPiles[i].addEventListener('mouseup', endLongPress);
$humanDiscardPiles[i].addEventListener('touchstart', () => startLongPressTimer(i));
$humanDiscardPiles[i].addEventListener('touchend', endLongPress);
$humanDiscardPiles[i].addEventListener("click", _didClickHumanDiscardPile);
}
$discardPileContents = document.getElementById("discard-pile-contents");
$humanStockPile = document.getElementById("human-stock");
$humanStockPile.addEventListener("click", _didClickHumanStockPile);
// Shared build and draw piles
for (let i = 0; i < 4; ++i) {
$buildPiles[i] = document.getElementById(`build-${i}`);
$buildPiles[i].addEventListener("click", _didClickBuildPile);
}
$drawPile = document.getElementById("draw");
// Controls
document
.getElementById("toggle-help")
.addEventListener("click", _didClickHelp);
$newGame = document.getElementById("new-game");
$newGame.addEventListener("click", _didClickNewGame);
}
function animateCSS($el, animationName, callback) {
const $node = $el || document.querySelector($el);
$node.classList.add('animated', animationName);
function handleAnimationEnd() {
$node.classList.remove('animated', animationName);
$node.removeEventListener("animationend", handleAnimationEnd);
if (typeof callback === "function") callback();
}
$node.addEventListener("animationend", handleAnimationEnd);
}
function _didClickHelp() {
if ($help.classList.contains("hidden")) {
$help.classList.remove("hidden");
document.querySelectorAll('.help-label').forEach(label => {
label.classList.remove("hidden");
});
}
else {
$help.classList.add("hidden");
document.querySelectorAll('.help-label').forEach(label => {
label.classList.add("hidden");
});
}
document.body.classList.toggle("overflow");
}
function _didClickNewGame() {
game = new Game(gameDelegate);
game.start();
}
// Human player clicked a card in their own hand with the intent
// of move the selected card to one of the shared build piles or one
// of their own discard piles.
// Rules:
// - Cannot select empty card in hand.
// - Selecting same hand card deselects it.
function _didClickHumanHandCard(event) {
if (!game.isActive || !game.currentTurn.player.isHuman) return;
let $node = event.target;
let handCardNumber = parseInt($node.id.replace("human-hand-", ""), 10);
let card = game.humanPlayer.hand.cards[handCardNumber];
if (!card) return;
if ($node === $moveSource) {
$moveSource = null;
$node.classList.remove("selected");
} else {
if ($moveSource) $moveSource.classList.remove("selected");
$moveSource = $node;
$node.classList.add("selected");
}
}
// Human player clicked one of their own discard piles.
// If there's a selected card already (move source) in the player's hand,
// that card is discarded.
// If there is no selected card, the top card of the discard pile becomes
// the move source with the intent that the player will click a build pile
// next.
// Rules:
// - No reason to select an empty discard pile as source of card move.
// - Selecting same discard pile deselects it.
// - Discarding a hand card ends the player's turn.
function _didClickHumanDiscardPile(event) {
if (!game.isActive || !game.currentTurn.player.isHuman || didLongPress) return;
let $node = event.target;
let discardPileNumber = parseInt($node.id.replace("human-discard-", ""), 10);
if (!$moveSource && game.humanPlayer.discardPiles[discardPileNumber].isEmpty)
return;
if ($node === $moveSource) {
$moveSource = null;
$node.classList.remove("selected");
} else if ($moveSource && $moveSource.id.startsWith("human-hand-")) {
let handCardNumber = parseInt(
$moveSource.id.replace("human-hand-", ""),
10
);
game.performDiscardAction(
new DiscardAction(discardPileNumber, handCardNumber)
);
} else {
if ($moveSource) $moveSource.classList.remove("selected");
$moveSource = $node;
$node.classList.add("selected");
}
}
// Human player has clicked a shared build pile.
// If a card has been selected (move source), the intent is to moved the selected card to this pile.
// The source may be the player stock pile; or
// the source may be 1 of the 4 player discard piles; or
// the source may be 1 of the 5 cards in the player's hand.
function _didClickBuildPile(event) {
if (!game.isActive || !game.currentTurn.player.isHuman) return;
let $node = event.target;
let buildPileNumber = parseInt($node.id.replace("build-", ""), 10);
if ($moveSource) {
if ($moveSource.id === "human-stock") {
try {
game.performPlayStockAction(new PlayStockAction(buildPileNumber));
} catch (e) {
console.warn(e);
}
} else if ($moveSource.id.startsWith("human-hand-")) {
let handCardNumber = parseInt(
$moveSource.id.replace("human-hand-", ""),
10
);
try {
game.performPlayHandAction(
new PlayHandAction(buildPileNumber, handCardNumber)
);
} catch (e) {
console.warn(e);
}
} else if ($moveSource.id.startsWith("human-discard-")) {
let discardPileNumber = parseInt(
$moveSource.id.replace("human-discard-", ""),
10
);
try {
game.performPlayDiscardAction(
new PlayDiscardAction(buildPileNumber, discardPileNumber)
);
} catch (e) {
console.warn(e);
}
}
}
}
// Clicking the player stock pile selects its top card.
function _didClickHumanStockPile(event) {
if (!game.isActive || !game.currentTurn.player.isHuman) return;
let $node = event.target;
if ($moveSource) $moveSource.classList.remove("selected");
$moveSource = $node;
$node.classList.add("selected");
}
function _deselectAllCards() {
for (let $card of document.getElementsByClassName("selected"))
$card.classList.remove("selected");
$moveSource = null;
}
function _syncPile(
$pile,
pile,
showEffectiveWildCardValues = false,
attention = true
) {
$pile.classList.remove("selected");
if (pile.isEmpty) {
$pile.textContent = null;
$pile.classList.add("empty");
} else {
$pile.classList.remove("empty");
if (showEffectiveWildCardValues) {
$pile.textContent = pile.peekTop().number;
} else {
$pile.textContent = pile.peekTop().toString();
}
if (attention) animateCSS($pile, "heartBeat");
}
$pile.setAttribute("data-badge", pile.cardCount);
}
function _syncDrawPileBadge() {
$drawPile.setAttribute("data-badge", game.drawPile.cardCount);
}
function _currentHand() {
let player = game.currentTurn.player;
let $hand = player.isHuman ? $humanHand : $cpuHand;
let hand = player.hand;
return [$hand, hand];
}
function _currentHandCard(handCardNumber) {
let [$hand, hand] = _currentHand();
return [$hand[handCardNumber], hand.cards[handCardNumber]];
}
function _syncCard($card, card) {
if (!card) {
$card.textContent = null;
$card.classList.remove("selected");
$card.classList.add("empty");
} else {
if (game.currentTurn.player.isHuman) $card.textContent = card.toString();
$card.classList.remove("empty");
}
if (card) animateCSS($card, "heartBeat");
}
function _syncCurrentHandCard(handCardNumber) {
let [$card, card] = _currentHandCard(handCardNumber);
_syncCard($card, card);
}
// Returns the DOM element of the given discard pile for the current turn's player
// as well as the model thereof.
function _currentDiscardPile(discardPileNumber) {
let player = game.currentTurn.player;
let $discardPile = player.isHuman
? $humanDiscardPiles[discardPileNumber]
: $cpuDiscardPiles[discardPileNumber];
let discardPile = player.discardPiles[discardPileNumber];
return [$discardPile, discardPile];
}
// Updates the displayed top card of the given discard pile for the current turn's player
// from the model thereof.
function _syncCurrentDiscardPile(discardPileNumber) {
let [$discardPile, discardPile] = _currentDiscardPile(discardPileNumber);
_syncPile($discardPile, discardPile);
}
// Returns the DOM element of the stock pile for the current turn's player
// as well as the model thereof.
function _currentStockPile() {
let player = game.currentTurn.player;
let $stockPile = player.isHuman ? $humanStockPile : $cpuStockPile;
return [$stockPile, player.stockPile];
}
// Updates the displayed top card of the stock pile for the current turn's player
// from the model thereof.
function _syncCurrentStockPile(attention) {
let [$stockPile, stockPile] = _currentStockPile();
_syncPile($stockPile, stockPile, false, attention);
}
// Returns the DOM element of the given build pile as well as the model thereof.
function _buildPile(buildPileNumber) {
let $buildPile = $buildPiles[buildPileNumber];
let buildPile = game.buildPiles[buildPileNumber];
return [$buildPile, buildPile];
}
// Updates the displayed top card of the given build from the model thereof.
function _syncBuildPile(buildPileNumber) {
let [$buildPile, buildPile] = _buildPile(buildPileNumber);
_syncPile($buildPile, buildPile, true);
}
function _isCPUCurrent() {
return !game.currentTurn.player.isHuman;
}
function _isHumanCurrent() {
return game.currentTurn.player.isHuman;
}
// The CPU player can play a card to a build pile if:
// - the card is wild; or
// - the card is 1 more than the top build pile card; or
// - the build pile is empty and the card is a 1.
//
// Returns the build pile number that can be played if any.
function _cpuCanPlayCard(card) {
for (let i = 0; i < 4; ++i) {
let buildPile = game.buildPiles[i];
if (
(!buildPile.isEmpty && buildPile.peekTop().number + 1 === card.number) ||
card.isWild ||
(buildPile.isEmpty && card.number === 1)
)
return i;
}
}
// Determines and submits one game action based on visible game state. Just
// like the human player, should this CPU player's action not cause the CPU
// player's turn to conclude, this will be called again.
//
// The delay is so the human player can see what is happening at each step.
let _nextTimeout;
function _submitNextCPUAction() {
if (_nextTimeout) clearTimeout(_nextTimeout);
_nextTimeout = setTimeout(_nextCPUAction, 1000);
}
// *************************************************************
// There is NO strategy in this current version!
// *************************************************************
// We first try stock pile and if we can play the top card, we do.
// Next, we try our hand cards.
// Next, we try our discard piles' top cards.
function _nextCPUAction() {
console.log("next cpu action");
// Can we play from our stock pile to any of the build piles?
let buildPileNumber = _cpuCanPlayCard(game.cpuPlayer.stockPile.peekTop());
if (buildPileNumber !== undefined) {
console.log("cpu plays stock pile to build pile", buildPileNumber);
game.performPlayStockAction(new PlayStockAction(buildPileNumber));
return;
}
// No, we cannot. Can we play any of our hand cards to any build pile?
for (let i = 0; i < 5; ++i) {
let card = game.cpuPlayer.hand.getCard(i);
if (!card) continue;
buildPileNumber = _cpuCanPlayCard(card);
if (buildPileNumber !== undefined) {
console.log("cpu plays hand card", i, "to build pile", buildPileNumber);
game.performPlayHandAction(new PlayHandAction(buildPileNumber, i));
return;
}
}
// No, we cannot. Can we play any of our discard piles' top cards to any build pile?
for (let discardPileNumber = 0; discardPileNumber < 4; ++discardPileNumber) {
let discardPile = game.cpuPlayer.discardPiles[discardPileNumber];
if (discardPile.isEmpty) continue;
let card = discardPile.peekTop();
buildPileNumber = _cpuCanPlayCard(card);
if (buildPileNumber !== undefined) {
console.log(
"cpu plays discard pile",
discardPileNumber,
"to build pile",
buildPileNumber
);
game.performPlayDiscardAction(
new PlayDiscardAction(buildPileNumber, discardPileNumber)
);
return;
}
}
console.log("cpu cannot play anything; discarding...");
// No, we cannot. Thus, we have to discard a card from our hand to one of the discard piles.
// Which card should we discard? Which pile should we discard to?
let nonEmptyHandCards = [];
for (let handCardNumber = 0; handCardNumber < 5; ++handCardNumber) {
let card = game.cpuPlayer.hand.getCard(handCardNumber);
if (card !== undefined) nonEmptyHandCards.push({ handCardNumber, card });
}
console.log("...nonEmptyHandCards", nonEmptyHandCards);
// If we have an empty pile we use that discard pile. We pick the highest
// value card in our hand so as to build discard piles in descending order which
// might help with "runs" (9 on a 10 means if we play 9 we can play the 10).
for (let discardPileNumber = 0; discardPileNumber < 4; ++discardPileNumber) {
let discardPile = game.cpuPlayer.discardPiles[discardPileNumber];
if (discardPile.isEmpty) {
let bestHandCardNumber = -1;
let maxValue = -1;
for (let { handCardNumber, card } of nonEmptyHandCards) {
if (card.isWild) continue;
if (card.number > maxValue) {
maxValue = card.number;
bestHandCardNumber = handCardNumber;
}
}
if (bestHandCardNumber !== -1) {
console.log(
"... found empty discard pile",
discardPileNumber,
"with best card to discard at",
bestHandCardNumber
);
game.performDiscardAction(
new DiscardAction(discardPileNumber, bestHandCardNumber)
);
return;
}
}
}
// Else we find all the discard piles whose top card is greater than our hand card.
let diffs = [];
for (let { handCardNumber, card } of nonEmptyHandCards) {
for (
let discardPileNumber = 0;
discardPileNumber < 4;
++discardPileNumber
) {
let discardPile = game.cpuPlayer.discardPiles[discardPileNumber];
let topCard = discardPile.peekTop();
let diff = topCard.isWild ? 1e8 : topCard.number - card.number;
if (diff > 0) {
diffs.push({ handCardNumber, discardPileNumber, diff });
}
}
}
if (diffs.length === 0) {
// There aren't any discard piles whose top card is greater than any of our hand cards.
// Thus, we pick a random discard pile.
let randomHandCardNumberIndex = Math.floor(
Math.random() * nonEmptyHandCards.length
);
let handCardNumber =
nonEmptyHandCards[randomHandCardNumberIndex].handCardNumber;
let discardPileNumber = Math.floor(Math.random() * 4);
console.log(
"cpu discards",
handCardNumber,
"to discard pile",
discardPileNumber
);
game.performDiscardAction(
new DiscardAction(discardPileNumber, handCardNumber)
);
} else {
// We want the minimum difference between discard pile and hand card.
// E.g. 10 in discard, 10 in hand is great; 10 vs 9, OK; 10 vs 2, not so good.
diffs.sort((a, b) => {
if (a.diff === b.diff) return 0;
return a.diff < b.diff ? -1 : 1;
});
let { handCardNumber, discardPileNumber } = diffs[0];
console.log(
"cpu discards",
handCardNumber,
"to discard pile",
discardPileNumber
);
game.performDiscardAction(
new DiscardAction(discardPileNumber, handCardNumber)
);
}
}
// The game delegate recieves notifications from the game model and updates the
// UI accordingly.
let gameDelegate = {
gameDidStart() {
$appName.textContent = "Skeep";
_syncDrawPileBadge();
for (let i = 0; i < 4; ++i) {
_syncBuildPile(i);
_syncPile(
$cpuDiscardPiles[i],
game.cpuPlayer.discardPiles[i],
true,
false
);
_syncPile(
$humanDiscardPiles[i],
game.humanPlayer.discardPiles[i],
true,
false
);
}
_syncPile($humanStockPile, game.humanPlayer.stockPile, false, false);
_syncPile($cpuStockPile, game.cpuPlayer.stockPile, false, false);
for (let i = 0; i < 5; ++i) {
_syncCard($humanHand[i], game.humanPlayer.hand[i]);
_syncCard($cpuHand[i], game.cpuPlayer.hand[i]);
}
},
turnDidStart() {
_deselectAllCards();
if (_isCPUCurrent()) {
$cpuPlayerArea.classList.add("active");
$humanPlayerArea.classList.remove("active");
} else {
$humanPlayerArea.classList.add("active");
$cpuPlayerArea.classList.remove("active");
}
// Wait for the animation to finish before dealing cards.
return animationDuration * 1.6;
},
turnDidEnd() {
_deselectAllCards();
return animationDuration * 1.6;
},
// Cards were dealt in the model. Let's let any animations
// finish from the previous turn (hence, later). Then, show
// the player who's up, animate the dealt cards, update pile counts,
// and if the CPU is now up, have it play its next action.
didDealCards: function(cardsDrawn, handCardNumbers) {
let delay = 0;
for (let cardNumber of handCardNumbers) {
let thisDelay = delay;
delay += 250;
setTimeout(() => _syncCurrentHandCard(cardNumber), thisDelay);
}
_syncDrawPileBadge();
_syncCurrentStockPile(false);
setTimeout(() => {
if (_isCPUCurrent()) _submitNextCPUAction();
}, 1000);
},
didPlayHandCard({ buildPileNumber, handCardNumber }) {
console.log("delegate.didPlayHandCard");
_syncBuildPile(buildPileNumber);
_syncCurrentHandCard(handCardNumber);
_deselectAllCards();
if (_isCPUCurrent()) _submitNextCPUAction();
},
didPlayStockCard({ buildPileNumber }) {
_syncBuildPile(buildPileNumber);
_syncCurrentStockPile();
_deselectAllCards();
if (_isCPUCurrent()) _submitNextCPUAction();
},
didPlayDiscardCard({ discardPileNumber, buildPileNumber }) {
_syncBuildPile(buildPileNumber);
_syncCurrentDiscardPile(discardPileNumber);
_deselectAllCards();
if (_isCPUCurrent()) _submitNextCPUAction();
},
didDiscardHandCard({ handCardNumber, discardPileNumber }) {
_syncCurrentDiscardPile(discardPileNumber);
_syncCurrentHandCard(handCardNumber);
_deselectAllCards();
},
didClearBuildPile(buildPileNumber) {
setTimeout(() => _syncBuildPile(buildPileNumber), 1000);
},
didRecreateDrawPile() {
_syncDrawPileBadge();
},
gameDidEnd() {
let text = game.winner.isHuman ? "YOU WIN! 🤘" : "I WON. 🐙";
$appName.textContent = text;
animateCSS($appName, "tada");
$humanHandRow.classList.remove("active");
$cpuHandRow.classList.remove("active");
if (game.winner.isHuman) _humanDidWin();
else _cpuDidWin();
_deselectAllCards();
_hideDiscardPileDisplay();
}
};
function _loadStoredRecord() {
if (localStorage.getItem("record")) {
let record = JSON.parse(localStorage.getItem("record"));
$record.textContent = `${record.humanWins} - ${record.cpuWins}`;
} else {
localStorage.setItem("record", JSON.stringify({ humanWins: 0, cpuWins: 0 }));
}
}
function _withStoredRecord(callback) {
let record = JSON.parse(localStorage.getItem("record"));
callback(record);
localStorage.setItem("record", JSON.stringify(record));
$record.textContent = `${record.humanWins} - ${record.cpuWins}`;
}
function _humanDidWin() {
_withStoredRecord(record => record.humanWins++)
party.confetti(document.body, {
count: party.variation.range(1000, 20000),
shapes: ["star", "roundedSquare"],
});
}
function _cpuDidWin() {
_withStoredRecord(record => record.cpuWins++)
}
function dragDidStart(ev) {
if (_isCPUCurrent()) {
ev.preventDefault();
return;
}
clearTimeout(longPressTimer);
ev.dataTransfer.setData("text/plain", ev.target.id);
ev.dataTransfer.effectAllowed = "move";
}
function dragDidHover(ev) {
ev.preventDefault();
if (_isCPUCurrent()) return;
document.querySelectorAll('.drag-hovered').forEach(node => node.classList.remove('drag-hovered'));
ev.target.classList.add("drag-hovered");
ev.dataTransfer.dropEffect = "move";
}
function dragDidDrop(ev) {
ev.preventDefault();
document.querySelectorAll('.drag-hovered').forEach(node => node.classList.remove('drag-hovered'));
if (_isCPUCurrent()) return;
let $node = ev.target;
let sourceId = ev.dataTransfer.getData("text/plain");
let buildPileNumber = parseInt($node.id.replace("build-", ""), 10);
let discardPileNumber = parseInt($node.id.replace("human-discard-", ""), 10);
if (!isNaN(buildPileNumber)) _didDropOnBuildPile(buildPileNumber, sourceId);
else if (!isNaN(discardPileNumber))
_didDropOnDiscardPile(discardPileNumber, sourceId);
}
// Can drag from discard pile, stock pile, or card in hand.
function _didDropOnBuildPile(buildPileNumber, sourceId) {
if (sourceId === "human-stock") {
try {
game.performPlayStockAction(new PlayStockAction(buildPileNumber));
} catch (e) {
console.warn(e);
}
} else if (sourceId.startsWith("human-hand-")) {
let handCardNumber = parseInt(sourceId.replace("human-hand-", ""), 10);
try {
game.performPlayHandAction(
new PlayHandAction(buildPileNumber, handCardNumber)
);
} catch (e) {
console.warn(e);
}
} else if (sourceId.startsWith("human-discard-")) {
let discardPileNumber = parseInt(
sourceId.replace("human-discard-", ""),
10
);
try {
game.performPlayDiscardAction(
new PlayDiscardAction(buildPileNumber, discardPileNumber)
);
} catch (e) {
console.warn(e);
}
}
}
function _didDropOnDiscardPile(discardPileNumber, sourceId) {
if (sourceId.startsWith("human-hand-")) {
let handCardNumber = parseInt(sourceId.replace("human-hand-", ""), 10);
game.performDiscardAction(
new DiscardAction(discardPileNumber, handCardNumber)
);
}
}
function startLongPressTimer(pileIndex) {
clearTimeout(longPressTimer);
longPressTimer = setTimeout(() => {
_didLongPressDiscardPile(pileIndex)
didLongPress = true;
}, 400);
}
function endLongPress(event) {
clearTimeout(longPressTimer);
longPressTimer = null;
if (didLongPress) {
event.preventDefault();
// Let click handler see that there was a long press.
setTimeout(() => didLongPress = false, 0);
}
}
function _didLongPressDiscardPile(index) {
const discardPile = game.humanPlayer.discardPiles[index];
if (discardPile.isEmpty || discardPile.cards.length == 1) return false;
$discardPileContents.innerHTML = discardPile.cards.at(-2).toString();
console.log('pile index', index);
const $pile = document.getElementById(`human-discard-${index}`);
$pile.style.zIndex = 2;
// Move the discard pile contents to the exact same position as $pile
$discardPileContents.parentNode.removeChild($discardPileContents);
const pileStyle = window.getComputedStyle($pile);
$discardPileContents.style.left = `${$pile.offsetLeft}px`;
$discardPileContents.style.top = `${$pile.offsetTop}px`;
$discardPileContents.style.width = `${pileStyle.width}`;
$discardPileContents.style.height = `${pileStyle.height}`;
$discardPileContents.classList.remove('hidden');
$pile.parentNode.appendChild($discardPileContents);
$pile.style.boxShadow = '0 2px 8px 0 rgba(0, 0, 0, 0.4)';
animateCSS($pile, 'slideOutLeft',
() => {
animateCSS($pile, 'slideInLeft', () => {
_hideDiscardPileDisplay();
$pile.style.boxShadow = '';
});
}
);
}
function addAutoRemoveEventListener(target, type, listenerFn, options) {
function oneTimeListener(event) {
listenerFn(event);
target.removeEventListener(type, oneTimeListener, options);
}
target.addEventListener(type, oneTimeListener, options);
}
function _hideDiscardPileDisplay() {
$discardPileContents.classList.add('hidden');
}
// When the DOM is ready, find our elements and start the game.
window.addEventListener("DOMContentLoaded", event => {
game = new Game(gameDelegate);
_loadElementsFromPage();
_loadStoredRecord();
document.querySelectorAll('.card').forEach(element => {
element.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
});
function setViewportHeight() {
document.documentElement.style.setProperty('--vh', `${window.innerHeight * 0.01}px`);
}
setViewportHeight();
window.addEventListener('resize', setViewportHeight);
game.start();
});