-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
2594 lines (2130 loc) · 71.4 KB
/
script.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
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
"use strict";
console.log("My first project");
// DOM Elements
const btnInit = document.querySelector(".btn-init");
const btnPlayers = document.querySelector(".btn-players");
const btnDeal = document.querySelector(".btn-deal");
const btnFlop = document.querySelector(".btn-flop");
const btnTurn = document.querySelector(".btn-turn");
const btnRiver = document.querySelector(".btn-river");
const btnEval = document.querySelector(".btn-eval");
const btnReset = document.querySelectorAll(".btn-reset");
const btnTurbo = document.querySelector(".btn-turbo");
let btnPlyr;
let btnCall;
let btnRaise;
let btnAllIn;
let btnFold;
let formPlyr;
let inputPlyr;
let gameCounter = 0;
const btnNewGame = document.querySelector(".btn-newGame");
const gameInfoPot = document.querySelector(".game-info-pot");
const gameInfoCall = document.querySelector(".game-info-call");
const gameInfoCards = document.querySelector(".game-info-cards");
const gameInfoPhase = document.querySelector(".game-info-phase");
const gameInfoNo = document.querySelector(".game-info-no");
let cardCurBet;
let cardCurHand;
let cardCurBal;
let textbox = document.querySelector(".textarea");
// Design a game of poker
// Implement logic of shuffling, distributing cards to 4 players plus house
// Implement logic of who wins
// Implement raise/calls, player rotation
// let deck = [{ suit: "Diamonds", rank: "Ace" }];
// Global variable/state
let deck = [];
let players = [];
let dealer;
let activePlayers;
let evalPlayer = [];
let gameState;
let game;
let stalePlayer = [];
let muckPlayer = [];
let muckCards = [];
const gameStateArr = [
"reset",
"initGame",
"setPlayers",
"dealPlayers",
"blinds",
"bet1",
"flop",
"bet2",
"turn",
"bet3",
"river",
"bet4",
"winner",
];
gameState = gameStateArr[0];
const handRanking = [
"Royal flush",
"Straight flush",
"Four of a kind",
"Full house",
"Flush",
"Straight",
"Three of a kind",
"Two pair",
"Pair",
"High Card",
];
console.log(gameStateArr);
function addTextBox(text, numLine) {
let newLineArr = [];
let newLineStr = "";
for (let i = 0; i < numLine; i++) {
newLineArr.push("\n");
}
newLineArr.forEach((val) => (newLineStr += val));
textbox.value += newLineStr + text;
const textboxHeight = textbox.scrollHeight;
textbox.scrollTop = textbox.scrollHeight;
}
function addTextBox2(text, numLine) {
let n = 0;
const speed = 5;
let newLineArr = [];
let newLineStr = "";
for (let i = 0; i < numLine; i++) {
newLineArr.push("\n");
}
newLineArr.forEach((val) => (newLineStr += val));
const combinedText = newLineStr + text;
const typeWriter = function () {
if (n < text.length) {
textbox.value += text.charAt(n);
n++;
const textboxHeight = textbox.scrollHeight;
textbox.scrollTop = textbox.scrollHeight;
setTimeout(typeWriter, speed);
}
};
typeWriter();
}
addTextBox2(
"Welcome!\n\nThis app is completely built on vanilla javascript and is my first ever coding project! This version runs completely on client-side browser!\n\nIt simulates a complete cycle of a Texas Hold 'em poker game, with basic features i.e. betting, calling, raising, checking, folding and other game logic e.g. determining the hand of a player, comparing player's cards at the end of betting, resolving ties and dealing with tiebreakers, selecting a winner(s), player rotation etc.\n\nAt the end of a game, the winner takes the pot amount and a new game can be started by pressing the Start Game! button at the top.\n\nBalances are brought forward to each game and the game can continue until a player loses their entire balance. The current game number is shown on the top right!\n\nA basic rundown of Texas Hold 'em can be found in the link below.\n\nIn this game, 2 to 10 players can be simulated starting with 1000 balance per player.\n\nPlayers cards are revealed on purpose to demonstrate card evaluation logic.\n\nClick on Start Game! to start a new game! The recommended small blind and big blinds are 1 & 2 usually starting with Player 3 and 2 respectively! The minimum bets are Calls (see above), any bets larger than Calls are Raise.\n\nHave fun!!"
);
const resetGame = function () {
gameState = gameStateArr[0];
deck = [];
players = [];
activePlayers;
dealer;
evalPlayer = [];
stalePlayer = [];
game;
// remove buttons
document.querySelectorAll(".btn-plyr").forEach(function (a) {
a.remove();
});
console.log("Game reset, please initialize game to play!");
textbox.value = "Reset! Press Initialize game to start!";
};
const suit = ["Clubs", "Diamonds", "Hearts", "Spades"];
const rank = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"];
// Refactor for entire deck
const generateDeck = function (suit, rank) {
for (let n = 0; n < suit.length; n++) {
for (let i = 0; i < rank.length; i++) {
deck.push({
suit: suit[n],
rank: rank[i],
indexOfRank: rank.indexOf(rank[i]),
});
}
}
};
// Fisher Yates Shuffle
// * source https://medium.com/swlh/the-javascript-shuffle-62660df19a5d
const fisYatesShuff = function () {
let randomCard;
let tempX;
const shuffle = function () {
for (let i = deck.length - 1; i > -1; i -= 1) {
randomCard = Math.floor(Math.random() * i); // Generate random no using index
tempX = deck[i]; // tempX is the last card, held temporarily
deck[i] = deck[randomCard]; // changing position, random card is placed at the end of deck
deck[randomCard] = tempX; // swap previous last card with random card, iterate through deck.length
}
return deck;
};
// double shuffle
shuffle();
shuffle();
return deck;
};
// Player Class prototype
const PlayerCl = class {
constructor(playerNo, hand, chips, currBet, active, startTurn, betRound) {
this.playerNo = playerNo;
this.hand = [];
this.chips = { startBal: 1000, currBal: 1000, movement: [], movType: [] };
this.currBet = 0;
this.active = true;
this.startTurn = false;
this.betRound = true;
this.allIn = false;
}
// ********* METHODS **********
showHand() {
let playerHandArr = [];
let playerHandGameArr = [];
for (let i = 0; i < this.hand.length; i++) {
let { rank: playerRank, suit: playerSuit } = this.hand[i];
playerHandArr.push(` ${playerRank} of ${playerSuit}`);
}
console.log(`${this.playerNo} has ${playerHandArr}`);
addTextBox(`${this.playerNo} has${playerHandArr}`, 1);
}
smallBlind(betValue) {
// prompt player to bet
let smallBlindAmount = betValue;
// change type to number
smallBlindAmount = Number(smallBlindAmount);
// value must be integer and more than 0
if (
Number.isInteger(smallBlindAmount) &&
smallBlindAmount > 0
// smallBlindAmount < this.chips.currBal
) {
// print to console amount bet
console.log(
`${this.playerNo} has placed small blind $${smallBlindAmount}`
);
addTextBox(
`${this.playerNo} has placed small blind $${smallBlindAmount}`,
1
);
// store current smallBlindAmount
// this.currBet = smallBlindAmount;
dealer.smallBlind = smallBlindAmount;
this.currBet = smallBlindAmount;
dealer.pot += smallBlindAmount;
this.chips.movType.push("Small Blind");
// only approve if bet amount is less than current balance
// if conditions are true, then push bet to movement array
this.chips.movement.push(smallBlindAmount);
// deduct current balance
this.chips.currBal -= smallBlindAmount;
// set betRound to false
// this.plyrCompleteBetRound(); --> not necessary as small blind player will always have to call, will only complete bet round after calling
this.plyrEndTurn();
}
}
smallBlindCall(betValue) {
this.call(betValue);
this.plyrEndTurn();
}
bigBlind(betValue) {
let bigBlindAmount = betValue;
// change type to number
bigBlindAmount = Number(bigBlindAmount);
// value must be integer and more than 0
if (
Number.isInteger(bigBlindAmount) &&
bigBlindAmount >= dealer.smallBlind * 2
// bigBlindAmount < this.chips.currBal
) {
// print to console amount bet
console.log(`${this.playerNo} has placed big blind $${bigBlindAmount}`);
addTextBox(`${this.playerNo} has placed big blind $${bigBlindAmount}`, 1);
// store current bigBlindAmount
// this.currBet = bigBlindAmount;
dealer.bigBlindAmount = bigBlindAmount;
dealer.minCall = bigBlindAmount;
this.currBet = bigBlindAmount;
dealer.pot += bigBlindAmount;
this.chips.movType.push("Big Blind");
// only approve if bet amount is less than current balance
// if conditions are true, then push bet to movement array
this.chips.movement.push(bigBlindAmount);
// deduct current balance
this.chips.currBal -= bigBlindAmount;
// set betRound to false
this.plyrCompleteBetRound();
this.plyrEndTurn();
// bigblind advances game state
dealer.setGameState(5);
} else if (bigBlindAmount < dealer.smallBlind * 2) {
// alert
alert(
`Bet amount too low, big blind has to be twice the amount of small blind ${dealer.smallBlind}`
);
// and rerun function
// this.bigBlind();
}
}
allInBet(betValue) {
// check if value in prompt is valid/true
// prompt to take in a value
let allInAmount = betValue;
// change type to number
allInAmount = Number(allInAmount);
// value must be integer and more than 0
if (
Number.isInteger(allInAmount) &&
allInAmount > 0 &&
allInAmount === this.chips.currBal
) {
this.allIn = true;
// store current allInAmount
this.currBet = allInAmount;
// print to console amount bet
console.log(`${this.playerNo} has went ALL IN ${this.currBet}!`);
addTextBox(`${this.playerNo} has went ALL IN ${this.currBet}!`, 2);
// only approve if bet amount is less than current balance
// if conditions are true, then push bet to movement array
this.chips.movement.push(allInAmount);
this.chips.movType.push("ALL IN");
// deduct current balance
this.chips.currBal -= allInAmount;
const { amount, player } = dealer.potMov;
dealer.pot += allInAmount;
dealer.potMov.amount.push(allInAmount);
dealer.potMov.player.push(this.playerNo);
// set betRound to false
this.plyrCompleteBetRound();
// end turn and ask dealer to start next player's turn
this.plyrEndTurn();
// if player bets more than balance
}
}
bets(betValue) {
if (this.active === true && activePlayers === 1) {
console.log(`${this.playerNo} wins!`);
addTextBox(`${this.playerNo} wins!`, 1);
gameState = gameStateArr[12];
return;
}
if (this.active === true && this.startTurn === true) {
// check if value in prompt is valid/true
// prompt to take in a value
let betAmount = betValue;
// console.log(`${this.playerNo} place your bets!`);
// addTextBox(`${this.playerNo} place your bets!`, 2);
if (betAmount === "fold") {
this.fold();
return;
}
// change type to number
betAmount = Number(betAmount);
// check
if (dealer.minCall === 0 && betAmount === 0) {
this.check();
return;
}
if (dealer.allIn === true) {
if (betAmount === this.chips.currBal) {
this.allInBet(betAmount);
return;
}
if (betAmount === dealer.minCall) {
this.call(betAmount);
}
return;
}
// value must be integer and more than 0
if (
Number.isInteger(betAmount) &&
betAmount > 0 &&
betAmount <= this.chips.currBal &&
this.currBet + betAmount >= dealer.minCall
) {
if (betAmount < dealer.minCall) {
this.call(betAmount);
return;
}
// store current betAmount
this.currBet = betAmount;
// print to console amount bet
console.log(`${this.playerNo} has placed ${betAmount}`);
addTextBox(`${this.playerNo} has placed ${betAmount}`, 2);
// only approve if bet amount is less than current balance
// if conditions are true, then push bet to movement array
this.chips.movement.push(betAmount);
if (this.currBet === dealer.minCall) {
this.chips.movType.push("Call");
console.log(`${this.playerNo} has called`);
addTextBox(`${this.playerNo} has called`, 1);
}
// player goes all in
if (this.currBet === this.chips.currBal) {
dealer.minCall = this.currBet;
dealer.allIn = true;
this.allIn = true;
console.log(
`${this.playerNo} has raise call to $${dealer.minCall}, dealer to check bets!`
);
addTextBox(
`${this.playerNo} has went ALL IN! Raise to meet call ${dealer.minCall}!`,
2
);
this.chips.movType.push("ALL IN");
players.forEach((ele, i) => {
if (players[i].playerNo !== this.playerNo) {
players[i].betRound = true;
}
});
alert(
`${this.playerNo} has went ALL IN! Raise to meet call ${dealer.minCall}!`
);
}
// deduct current balance
this.chips.currBal -= betAmount;
if (this.currBet > dealer.minCall && dealer.minCall !== 0) {
dealer.minCall = this.currBet;
console.log(
`${this.playerNo} has raise call to $${dealer.minCall}, dealer to check bets!`
);
this.chips.movType.push("Raise");
players.forEach((ele, i) => {
if (players[i].playerNo !== this.playerNo) {
players[i].betRound = true;
}
});
alert(
`${this.playerNo} has raise! Raise to meet call ${dealer.minCall}!`
);
} else if (dealer.minCall === 0) {
dealer.minCall = betAmount;
this.chips.movType.push("Bet");
}
const { amount, player } = dealer.potMov;
dealer.pot += betAmount;
dealer.potMov.amount.push(betAmount);
dealer.potMov.player.push(this.playerNo);
// set betRound to false
this.plyrCompleteBetRound();
// end turn and ask dealer to start next player's turn
this.plyrEndTurn();
// if player bets more than balance
} else if (betAmount > this.chips.currBal) {
// alert
alert("Insufficient balance!");
// and rerun function
// this.bets();
} else if (betAmount < dealer.minCall) {
// alert
alert(
`Bet amount too low, call ${dealer.minCall} or raise! Your current bet is ${this.currBet}`
);
// and rerun function
// this.bets();
} else if (betAmount < dealer.minCall && betAmount < this.chips.currBal) {
// alert
alert(`Bet amount too low, call ${dealer.minCall} or raise!`);
// and rerun function
// this.bets();
} else {
// if player include value that is not integer or negative value
alert("Please enter whole values more than zero!");
// rerun function
// this.bets();
}
}
}
call(betValue) {
if (this.active === true) {
// check if value in prompt is valid/true
// prompt to take in a value
let raiseAmount = betValue;
// prompt(
// `${this.playerNo} needs to raise! Your current bet is ${this.currBet}. To fold, type "fold" (without quotes!)`
// );
if (raiseAmount === "fold") {
this.fold();
return;
}
// change type to number
raiseAmount = Number(raiseAmount);
// value must be integer and more than 0
const currAddRaise = this.currBet + raiseAmount;
if (
Number.isInteger(raiseAmount) &&
raiseAmount > 0 &&
raiseAmount <= this.chips.currBal &&
currAddRaise >= dealer.minCall
) {
// store current raiseAmount
this.currBet = currAddRaise;
// print to console amount bet
console.log(`${this.playerNo} has met the raised ${this.currBet}`);
addTextBox(`${this.playerNo} has met the raised ${this.currBet}`, 2);
// only approve if bet amount is less than current balance
// if conditions are true, then push bet to movement array
this.chips.movement.push(raiseAmount);
if (this.currBet === dealer.minCall) {
this.chips.movType.push("Call");
}
// deduct current balance
this.chips.currBal -= raiseAmount;
if (currAddRaise > dealer.minCall && dealer.minCall !== 0) {
dealer.minCall = currAddRaise;
console.log(
`Minimum call is ${dealer.minCall}, dealer to check bets`
);
this.chips.movType.push("Raise");
alert(
`${this.playerNo} has raise! Raise to meet call ${dealer.minCall}!`
);
// if this player raises, all other players are still in the round.
}
const { amount, player } = dealer.potMov;
dealer.pot += raiseAmount;
dealer.potMov.amount.push(raiseAmount);
dealer.potMov.player.push(this.playerNo);
// set betRound to false
this.plyrCompleteBetRound();
// end turn and ask dealer to start next player's turn
this.plyrEndTurn();
// if player bets more than balance
} else if (raiseAmount > this.chips.currBal) {
// alert
alert("Insufficient balance!");
// and rerun function
// this.call();
} else if (currAddRaise < dealer.minCall) {
// alert
alert(
`Raise amount too low! Your current bet is ${
this.currBet
}, raise bet by ${dealer.minCall - this.currBet} to stay in the game!`
);
// and rerun function
// this.call();
} else if (
currAddRaise < dealer.minCall &&
raiseAmount < this.chips.currBal
) {
// alert
alert(
`You don't have enough chips to meet the raise ${dealer.minCall}. Type "fold" to forfeit!`
);
// and rerun function
// this.call();
} else {
// if player include value that is not integer or negative value
alert("Please enter whole values more than zero!");
// rerun function
// this.call();
}
}
}
fold() {
if (this.active === true && this.startTurn === true) {
activePlayers -= 1;
// find this player's index in players array
// const i = players.indexOf(this);
//put into muck pile for record purposes
muckCards.push(...this.hand);
//remove hand
this.hand = [];
this.currBet = 0;
this.chips.movement.push(0);
this.chips.movType.push("Fold");
this.active = false;
console.log(`${this.playerNo} has folded!`);
addTextBox(`${this.playerNo} has folded!`, 2);
// set betRound to false
this.plyrCompleteBetRound();
// end turn and ask dealer to start next player's turn
this.plyrEndTurn();
}
}
check() {
console.log(`${this.playerNo} has checked`);
addTextBox(`${this.playerNo} has checked`, 2);
const { amount, player } = dealer.potMov;
// dealer.pot += betAmount;
dealer.potMov.amount.push(0);
dealer.potMov.player.push(this.playerNo);
this.chips.movement.push(0);
this.chips.movType.push("Check");
// set betRound to false
this.plyrCompleteBetRound();
// end turn and ask dealer to start next player's turn
this.plyrEndTurn();
}
plyrEndTurn() {
// end turn and ask dealer to start next player's turn
this.startTurn = false;
dealer.startNextPlyrTurn();
}
plyrCompleteBetRound() {
this.betRound = false;
console.log(`${this.playerNo} bet round is completed`);
}
};
// Evaluate Class prototype
const Evaluate = class {
constructor(
player,
playerInitIndex,
cards,
arrIndexOfRank,
arrSuit,
arrRank,
result
) {
this.player = player;
this.playerInitIndex = playerInitIndex;
this.cards = [];
this.arrIndexOfRank = [];
this.arrSuit = [];
this.arrRank = [];
this.result = {
bestHand: 11,
resultIndexRank: [],
resultRank: [],
resultSuit: [],
ogIndex: [],
finalFive: { finalRank: [], finalSuit: [], finalRankIdx: [] },
};
}
// METHODS
findOutcomes() {
this.findAll();
this.finalFive();
}
clearPushStrNArr() {
this.result.resultIndexRank = [];
this.result.resultRank = [];
this.result.resultSuit = [];
this.result.ogIndex = [];
}
spliceErrors(startNo, noOfCards) {
this.result.resultIndexRank.splice(startNo, noOfCards);
this.result.resultRank.splice(startNo, noOfCards);
this.result.resultSuit.splice(startNo, noOfCards);
this.result.ogIndex.splice(startNo, noOfCards);
}
findAll() {
// Layout of function is
// Find this pattern/arrangement of cards, and log into a str
// If length of string is equals to number of expected cards, log and return results
let _player = this.player;
let _arrRank = this.arrRank;
let _arrSuit = this.arrSuit;
let _arrIndexOfRank = this.arrIndexOfRank;
let { bestHand, resultIndexRank, resultRank, resultSuit, ogIndex } =
this.result;
let str = [];
let ranking;
let fourOfAKind = false;
let threeOfAKind = false;
let straight = false;
let count = 0;
let flush = false;
let royalFlush = false;
let straightFlush = false;
let fullHouse = false;
let pair = false;
const pushStrNArr = function (n) {
// Place in string array
str.push(`${_arrRank[n]} of ${_arrSuit[n]}`);
// Push
resultIndexRank.push(_arrIndexOfRank[n]);
resultRank.push(_arrRank[n]);
resultSuit.push(_arrSuit[n]);
ogIndex.push(n);
};
const clearStr = function () {
str = [];
};
const spliceErrorsStr = function (startNo, noOfCards) {
str.splice(startNo, noOfCards);
};
// findFourOfAKind
this.arrRank.forEach((val, i, arr) => {
if (val === arr[i + 1] && val === arr[i + 2] && val === arr[i + 3]) {
fourOfAKind = true;
// globalFourOfAKind = true;
for (let n = i; n < i + 4; n++) {
pushStrNArr(n);
}
}
});
// log if conidtions for four of a kind is found
if (fourOfAKind === true) {
this.result.bestHand = 2;
console.log(`${this.player} has FOUR OF A KIND ${[...str]}!`);
return;
}
// find full house
if (fourOfAKind !== true) {
let startIndex3Kind;
function findThreeOfAKind() {
_arrRank.forEach((val, i, arr) => {
// two parts first find 3 of a kind, second part find pair
// first part - find three similar cards
if (val === arr[i + 1] && val === arr[i + 2]) {
startIndex3Kind = i;
threeOfAKind = true;
for (let n = i; n < i + 3; n++) {
pushStrNArr(n);
}
}
});
}
findThreeOfAKind();
if (str.length === 6) {
this.spliceErrors(0, 3);
spliceErrorsStr(0, 3);
}
// second part - find pair, ignore if start index is the same as 3 of a kind, will lead to duplicate
function findPair() {
_arrRank.forEach(function (val, i, arr) {
if (
val === arr[i + 1] &&
val !== arr[i + 2] &&
i !== startIndex3Kind &&
i !== startIndex3Kind + 1
) {
pair = true;
for (let n = i; n < i + 2; n++) {
pushStrNArr(n);
}
}
});
}
findPair();
if (str.length === 7) {
this.spliceErrors(0, 2);
spliceErrorsStr(0, 2);
}
if (pair === true && threeOfAKind === false) {
pair = false;
this.spliceErrors(0, str.length);
clearStr();
}
}
// log if conidtions for straight is found - logic for 3 of a kind overlaps, if str.length = 3
if (threeOfAKind === true && pair === false) {
this.result.bestHand = 6;
if (str.length === 6) {
this.spliceErrors(0, 3);
spliceErrorsStr(0, 3);
}
console.log(`${this.player} has THREE OF A KIND ${[...str]}!`);
return;
}
// log if conidtions for full house is found
if (threeOfAKind === true && pair === true) {
fullHouse = true;
// globalFullHouse = true;
this.result.bestHand = 3;
console.log(`${this.player} has FULL HOUSE ${[...str]}!`);
return;
}
// find flush
let flushIdx = [];
str = [];
for (let i = 0; i < suit.length; i++) {
// clearPushStrNArr();
flushIdx = [];
// for (let n = 0; n < this.arrSuit.length; n++)
this.arrSuit.forEach(function (val, n) {
if (val === suit[i]) flushIdx.push(n);
});
if (flushIdx.length < 5) {
flushIdx = [];
}
if (
flushIdx.length === 5 ||
flushIdx.length === 6 ||
flushIdx.length === 7
) {
flush = true;
// globalFlush = true;
// this.result.bestHand = 4;
flushIdx.forEach((val) => {
pushStrNArr(val);
});
}
}
// log if conidtions for flush is found
if (flush === true) {
let flushCount = 0;
let flushIsStraight;
for (let n = 1; n < resultIndexRank.length; n++) {
flushIsStraight = resultIndexRank[n] - n;
if (resultIndexRank[0] === flushIsStraight) {
flushCount += 1;
}
}
if (flushCount === 5) {
this.spliceErrors(0, 1);
spliceErrorsStr(0, 1);
}
if (flushCount === 6) {
this.spliceErrors(0, 2);
spliceErrorsStr(0, 1);
}
if (resultIndexRank[0] === 8) {
royalFlush = true;
// globalRoyalFlush = true;
this.result.bestHand = 0;
console.log(`${this.player} has ROYAALLLL FLUSHHHHH${[...str]}`);
return;
}
if (flushCount === 4 || flushCount === 5 || flushCount === 6) {
straightFlush = true;
// globalStraightFlush = true;
this.result.bestHand = 1;
console.log(`${this.player} has STRAIGHT FLUSHHHHHHH${[...str]}`);
return;
}
if (flushCount < 4) {
this.result.bestHand = 4;
console.log(`${_player} has A ${resultSuit[0]} FLUSH ${[str]}!`);
return;
}
}
// findStraight
this.arrIndexOfRank.forEach((val, i, arr) => {
let isStraight;
// find sequence of number that is equal to firstNo (val) for straight
for (let n = 1; n < 5; n++) {
isStraight = arr[i + n] - n;
if (val === isStraight) {
count += 1;
} else {
return;
}
}
if (count === 4) {
straight = true;
str = [];
for (let y = i; y < i + 5; y++) {
pushStrNArr(y);
}
}
});
// log if conidtions for straight is found
// condition for straight
if (straight === true) {
// globalStraight = true;
this.result.bestHand = 5;
if (resultIndexRank.length === 10) {
this.spliceErrors(0, 5);
spliceErrorsStr(0, 5);
}
if (resultIndexRank.length === 15) {
this.spliceErrors(0, 10);
spliceErrorsStr(0, 10);
}
if (resultIndexRank.length !== 5) {
console.error("Look into straights, more than 5 cards");
}