-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPoker.js
707 lines (589 loc) · 16 KB
/
Poker.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
// temporary bridge - todo: change clients to get suits from this lib
export const Suit_Heart = 'Heart';
export const Suit_Club = 'Club';
export const Suit_Spade = 'Spade';
export const Suit_Diamond = 'Diamond';
// temporary, allow this to be overriden
export const DefaultDeck =
{
get Suits() { return [Suit_Heart,Suit_Club,Suit_Diamond,Suit_Spade]; },
get Ranks() { return [2,3,4,5,6,7,8,9,10,11,12,13,14]; },
get WildSuit() { return '*'; },
get WildRank() { return -1; },
get HighestRank() { return this.Ranks[this.Ranks.length-1]; },
get RanksDescending() { return DefaultDeck.Ranks.slice().sort(CompareDescending); },
// todo: a more flexible system for two-Rank cards
get AceIsHighAndLow() { return true; },
get Ace() { return 14; },
// should deprecate use of these
get RankAce() { return 14; },
get RankTen() { return 10; },
get RankJack() { return 11; },
get RankQueen() { return 12; },
get RankKing() { return 13; },
};
// html requires default export
//export default DefaultDeck;
// cache the best score for a hand
let BestScoreCache = null;
export function GetBestHandScore()
{
if ( BestScoreCache == null )
{
const Jokers = GetJokerCards(5);
const Hand = GetScoringHand(Jokers);
BestScoreCache = Hand.Score;
}
return BestScoreCache;
}
function CompareAscending(a,b)
{
return a - b;
}
function CompareDescending(a,b)
{
return b-a;
}
function CompareCardsDescendingWildLast(a,b)
{
a = a.Rank;
b = b.Rank;
if ( a == b )
return 0;
if ( a == DefaultDeck.WildRank )
return 1;
if ( b == DefaultDeck.WildRank )
return -1;
return b-a;
}
function IsCardInCards(Needle,Haystack,UseScoreCard=true)
{
if ( UseScoreCard )
return Haystack.find( Match => Match.ScoreCard.Equals(Needle.ScoreCard) ) != null;
return Haystack.find( Match => Match.Equals(Needle) ) != null;
}
function GetHighestRankInCards(Cards)
{
const Ranks = Cards.map( c => c.ScoreCard.Rank );
Ranks.sort(CompareDescending);
return Ranks[0];
}
function IsSameSuit(a,b)
{
a = (a instanceof Card) ? a.Suit : a;
b = (b instanceof Card) ? b.Suit : b;
if ( a == DefaultDeck.WildSuit || b == DefaultDeck.WildSuit )
return true;
return a == b;
}
function IsSameRank(a,b)
{
a = (a instanceof Card) ? a.Rank : a;
b = (b instanceof Card) ? b.Rank : b;
if ( DefaultDeck.AceIsHighAndLow )
{
if ( a == DefaultDeck.Ace && b == 1 )
return true;
if ( b == DefaultDeck.Ace && a == 1 )
return true;
}
if ( a == DefaultDeck.WildRank || b == DefaultDeck.WildRank )
return true;
return a == b;
}
// deep copy of Card objects
// .slice() is just a shallow copy!
function CloneCards(Cards)
{
return Cards.map( c => c.Clone() );
}
export class Card
{
constructor(Suit,Rank,OriginalCard)
{
this.Suit = Suit;
this.Rank = Number(Rank);
if ( !Number.isInteger(this.Rank) )
{
console.error(`Card Rank ${Rank} (${this.Rank}) not integer`);
//throw `Card Rank ${Rank} (${this.Rank}) not integer`;
}
}
get SuitOrWildNull()
{
return this.Suit == DefaultDeck.WildSuit ? null : this.Suit;
}
get RankOrWildNull()
{
return this.Rank == DefaultDeck.WildRank ? null : this.Rank;
}
get IsWild()
{
return !this.SuitOrWildNull || !this.RankOrWildNull;
}
get ScoreCard()
{
return this.RepresentCard ?? this;
}
Equals(that)
{
return (this.Rank == that.Rank) && (this.Suit == that.Suit);
//return IsSameRank(this,that) && IsSameSuit(this,that);
}
Clone()
{
const Clone = new Card( this.Suit, this.Rank );
if ( this.RepresentCard != null )
Clone.RepresentCard = this.RepresentCard.Clone();
return Clone;
}
}
export class Hand
{
constructor(Cards,HandType,Score)
{
this.Cards = CloneCards(Cards);
this.Type = HandType;
this.Score = Number(Score);
if ( !Number.isInteger(this.Score) )
{
console.error(`Card Score ${Score} (${this.Score}) not integer`);
//throw `Card score ${Score} (${this.Score}) not integer`;
}
}
}
// these functions probably want to go into some kind of deck container
export function GetJokerCards(Count=1)
{
const Cards = [];
for ( let i=0; i<Count; i++ )
{
const card = new Card(DefaultDeck.WildSuit,DefaultDeck.WildRank);
Cards.push(card);
}
return Cards;
}
// these functions probably want to go into some kind of deck container
export function GetAllCards()
{
const Cards = [];
for ( let Suit of DefaultDeck.Suits )
{
for ( let Rank of DefaultDeck.Ranks )
{
const card = new Card(Suit,Rank);
Cards.push(card);
}
}
return Cards;
}
// todo: wild first as highest card
function GetSortedFiveCards(Cards)
{
function Compare(a,b)
{
const va = GetCardRank(a);
const vb = GetCardRank(b);
if ( va > vb ) return -1;
if ( va < vb ) return 1;
return 0;
}
Cards.sort( Compare );
Cards.length = Math.min( 5, Cards.length );
return Cards;
}
// this is expecting all the cards to be found
// and does NOT use wilds
function PopMatchingCards(Cards,MatchCards)
{
const Popped = [];
// all matching cards must be found, so
// iterate through them
for ( let m=0; m<MatchCards.length; m++ )
{
const MatchCard = MatchCards[m];
const CardIndex = Cards.findIndex( c => c.Equals(MatchCard) );
if ( CardIndex < 0 )
throw `Matching card ${JSON.stringify(MatchCard)} not found`;
const PoppedCard = Cards.splice(CardIndex,1)[0];
Popped.push( PoppedCard );
}
return Popped;
}
function PopNCardsWithRank(Cards,Rank,ExpectedPopCount)
{
const MinimumPopped = ExpectedPopCount;
const MaxiumumPopped = ExpectedPopCount;
const Matches = Cards.filter( c => IsSameRank(c,Rank) );
if ( Matches.length < MinimumPopped )
return false;
// try and pop wild cards last, so we dont accidentally
// use a wildcard instead of a 7
// then when we need a wild card, we have a 7 but not a 5
Cards.sort(CompareCardsDescendingWildLast);
// but then, we need to iterate backwards when splicing
// so, reverse
Cards = Cards.reverse();
const Popped = [];
for ( let i=Cards.length-1; i>=0; i-- )
{
let MatchCard = Cards[i];
if ( !IsSameRank(MatchCard,Rank) )
continue;
if ( Popped.length >= MaxiumumPopped )
break;
const PoppedCard = Cards.splice(i,1)[0];
Popped.push( PoppedCard );
}
return Popped;
}
function GetCardRank(Card)
{
return Card.Rank;
}
function GetCardSuit(Card)
{
return Card.Suit;
}
// return the best straight+flush hand (5)
function GetStraightFlushHand(Cards)
{
// 678*T is producing a represented 1 or 0 etc
function GetStraightHandOfSuit(Suit)
{
const Hearts = Cards.filter( c => IsSameSuit(c,Suit) );
if ( Hearts.length < 5 )
return false;
const ClonedCards = CloneCards(Hearts);
const StraightHand = GetStraightHand( ClonedCards, Suit );
return StraightHand;
}
// enum suits (into array so .length works)
const Suits = [...new Set( Cards.map(c=>c.Suit) ) ];
function GetStraightFlushForSuit(Suit)
{
// need to ignore matching wild suits here
if ( Suit == DefaultDeck.WildSuit )
{
// unless there are ONLY wild suits!
if ( Suits.length > 1 )
{
return false;
}
}
const SuitedCards = GetStraightHandOfSuit( Suit );
if ( !SuitedCards )
return false;
return SuitedCards;
}
const StraightFlushes = [];
for ( let Suit of Suits )
{
const StraightFlush = GetStraightFlushForSuit(Suit);
if ( !StraightFlush )
continue;
StraightFlushes.push(StraightFlush);
}
if ( StraightFlushes.length == 0 )
return false;
function CompareCardSetDescending(aaa,bbb)
{
const a = GetHighestRankInCards(aaa);
const b = GetHighestRankInCards(bbb);
return b-a;
}
// pick best ranked straight flush
StraightFlushes.sort(CompareCardSetDescending);
return StraightFlushes[0];
}
// return the best flush (5)
function GetFlushHand(Cards)
{
// enum suits
const Suits = [...new Set( Cards.map(c=>c.Suit) )];
for ( let Suit of Suits )
{
// need to ignore matching wild suits here
if ( Suit == DefaultDeck.WildSuit )
{
// unless there are ONLY wild suits!
if ( Suits.length > 1 )
{
continue;
}
}
const SuitedCards = CloneCards(Cards).filter( c => IsSameSuit(c,Suit) );
function IsCardNotAlreadyFound(Card)
{
return SuitedCards.find( c => c.Equals(Card) ) == null;
}
function AddRepresentedCard(MatchCard)
{
if ( MatchCard.IsWild )
{
// todo: get a rank that doesnt then make a straight flush...
// gr: or is that not possible in practise, as the wild card would have already matched a straight flush...
// but we should avoid existing card
let PossibleRepresents = DefaultDeck.RanksDescending.map( r => new Card(Suit,r) );
PossibleRepresents = PossibleRepresents.filter(IsCardNotAlreadyFound);
const RepCard = PossibleRepresents[0];
MatchCard.RepresentCard = RepCard;
}
}
SuitedCards.forEach( AddRepresentedCard );
if ( SuitedCards.length >= 5 )
return GetSortedFiveCards(SuitedCards);
}
return false;
}
function IsDescendingSequence(Array)
{
for ( let i=1; i<Array.length; i++ )
if ( Array[i-1] != Array[i]+1 )
return false;
return true;
}
// return the best straight hand
// todo: properly handle 6 card straight etc
function GetStraightHand(Cards,RepresentSuit=null,StraightLength=5)
{
function FindStraightStartingWithRank(FirstRank)
{
// wild cards mean we can't just grab sorted chunks any more
const TestCards = CloneCards(Cards);
const PoppedCards = [];
for ( let Rank=FirstRank; Rank>=0; Rank-- )
{
const Popped = PopNCardsWithRank(TestCards,Rank,1);
// required next card missing
if ( !Popped )
return false;
function SetRepCard(MatchCard)
{
if ( MatchCard.RepresentCard != null )
throw `Modifying card with existing rep card`;
// if the card that matched was wild, make it represent an equivelent card
if ( !MatchCard.IsWild )
return;
// if RepresentSuit == null, this is not a straight flush
// so we need to pick a suit that's not going to make a straight flush
if ( !RepresentSuit )
{
console.warn(`todo: calculate suit for ${Rank} which doesn't cause a straight flush`);
RepresentSuit = DefaultDeck.Suits[0];
}
const RepRank = MatchCard.RankOrWildNull ?? Rank;
// todo: get a suit that's unused in this meld
const RepSuit = MatchCard.SuitOrWildNull ?? RepresentSuit;
MatchCard.RepresentCard = new Card( RepSuit, RepRank );
}
Popped.forEach( SetRepCard );
PoppedCards.push(...Popped);
// remove to make unlimited straight
if ( PoppedCards.length == StraightLength )
break;
}
// didn't make a straight
if ( PoppedCards.length < StraightLength )
return false;
return PoppedCards;
//return GetSortedFiveCards(StraightCards);
}
const Ranks = Cards.map( GetCardRank );
// remove duplicates
let UniqueRanks = [...new Set(Ranks)];
const WildCardCount = Ranks.filter( r => r==DefaultDeck.WildRank ).length;
// UniqueRanks includes 1 wild card. Additional wildcards can count as other Ranks
const AdditionalUniqueRanks = Math.max(0,WildCardCount-1);
if ( UniqueRanks.length+AdditionalUniqueRanks < StraightLength )
return false;
UniqueRanks = Ranks.sort(CompareDescending);
// if we have at least one wild card, we need to try a straight
// with every rank going down... we don't even need to check the rest
if ( WildCardCount > 0 )
UniqueRanks = DefaultDeck.RanksDescending;
// for each number, count up N in a row
for ( let i=0; i<UniqueRanks.length; i++ )
{
const Rank = UniqueRanks[i];
const Straight = FindStraightStartingWithRank(Rank);
if ( !Straight )
continue;
return Straight;
}
return false;
}
function GetFullHouseHand(AllCards)
{
const RemainingCards = CloneCards(AllCards);
// pop trips first
const AllTrips = GetAllMeldsInHand(RemainingCards,3);
if ( AllTrips.length < 1 )
return false;
const BestTrips = AllTrips[0];
const Trips = PopMatchingCards(RemainingCards,BestTrips);
// now pop best pair
const AllPairs = GetAllMeldsInHand(RemainingCards,2);
if ( AllPairs.length < 1 )
return false;
const BestPair = AllPairs[0];
const Pair = PopMatchingCards(RemainingCards,BestPair);
const FullHouseCards = Trips.concat( Pair );
return GetSortedFiveCards( FullHouseCards );
}
function GetFiveOfAKindHand(Cards)
{
const Quints = GetAllMeldsInHand(Cards,5);
if ( Quints.length < 1 )
return false;
return Quints[0];
}
function GetFourOfAKindHand(Cards)
{
const Quads = GetAllMeldsInHand(Cards,4);
if ( Quads.length < 1 )
return false;
return Quads[0];
}
function GetThreeOfAKindHand(Cards)
{
const Trips = GetAllMeldsInHand(Cards,3);
if ( Trips.length < 1 )
return false;
return Trips[0];
}
function GetAllMeldsInHand(AllCards,MeldSize)
{
const Ranks = AllCards.map( GetCardRank ).sort( CompareDescending );
const UniqueRanks = new Set(Ranks);
// to make this work with wild cards easily
// pop pairs from the card list until we run out
let RemainingCards = CloneCards(AllCards);
const Pairs = [];
for ( let Rank of UniqueRanks )
{
// if we test wild against everything, we'll get spurious matches
// *==*, *==3, *==4, *==5 etc
// so treat wild card as highest rank, which will then make multiple wildcards work
// then A==*, A!==4, A!==5
if ( Rank == DefaultDeck.WildRank )
Rank = DefaultDeck.HighestRank;
const Pair = PopNCardsWithRank(RemainingCards,Rank,MeldSize);
if ( !Pair )
continue;
function SetRepCard(MatchCard)
{
if ( MatchCard.RepresentCard != null )
throw `Modifying card with existing rep card`;
// if the card that matched was wild, make it represent an equivelent card
if ( !MatchCard.IsWild )
return;
// we need to pick a suit that's not going to make a flush pair
// so just make them all and use one that's not in the pair we're returning
// todo: ideally not in AllCards?
const UseScoreCard = true;
const PossibleRepresents = DefaultDeck.Suits.map( s => new Card(s,Rank) ).filter( c => !IsCardInCards(c,Pair,UseScoreCard) );
if ( PossibleRepresents.length > 0 )
{
MatchCard.RepresentCard = PossibleRepresents[0];
}
}
Pair.forEach( SetRepCard );
Pairs.push(Pair);
}
return Pairs;
}
function GetTwoPairHand(Cards)
{
const Pairs = GetAllMeldsInHand(Cards,2);
if ( Pairs.length < 2 )
return false;
const AllCards = Pairs[0].concat(Pairs[1]);
return AllCards;
}
function GetOnePairHand(Cards)
{
const Pairs = GetAllMeldsInHand(Cards,2);
if ( Pairs.length < 1 )
return false;
const AllCards = Pairs[0];
return AllCards;
}
function GetHighCardHand(Cards)
{
if ( Cards.length == 0 )
return false;
const Ranks = Cards.map( GetCardRank ).sort( CompareDescending );
const FirstHighest = Cards.find( c => IsSameRank( c, Ranks[0] ) );
if ( FirstHighest.IsWild )
{
const RepRank = DefaultDeck.HighestRank;
const RepSuit = DefaultDeck.Suits[0];
FirstHighest.RepresentCard = new Card(RepSuit,RepRank);
}
return [FirstHighest];
}
export function GetScoringHand(Cards)
{
const HandTypes =
[
`Straight Flush`,
`Five Of A Kind`,
`Four Of A Kind`,
`Full House`,
`Flush`,
`Straight`,
`Three Of A Kind`,
`Two pair`,
`One Pair`,
`High Card`,
`No Cards`
];
const GetHandFuncs =
[
GetStraightFlushHand,
GetFiveOfAKindHand,
GetFourOfAKindHand,
GetFullHouseHand,
GetFlushHand,
GetStraightHand,
GetThreeOfAKindHand,
GetTwoPairHand,
GetOnePairHand,
GetHighCardHand
];
// best denominator you can get is 14*5
// thus each score jumps by this + 1?
const MaxHandSize = 5;
const Denom = (DefaultDeck.HighestRank * MaxHandSize) + 1;
const HandBaseScores =
[
Denom*9,
Denom*8,
Denom*7,
Denom*6,
Denom*5,
Denom*4,
Denom*3,
Denom*2,
Denom*1,
Denom*0,
];
if ( Cards.length == 0 )
return new Hand( [], HandTypes.slice(-1)[0], 0 );
for ( let f=0; f<GetHandFuncs.length; f++ )
{
const GetHandFunc = GetHandFuncs[f];
const HandCards = GetHandFunc( Cards );
if ( HandCards === false )
continue;
const HandType = HandTypes[f];
// gr: this score also needs to include kickers
// we should probably modify all funcs to return N cards
let Score = HandBaseScores[f];
for ( let Card of HandCards )
Score += Card.ScoreCard.Rank;
return new Hand( HandCards, HandType, Score );
}
throw "Shouldn't reach here, GetScoringHand should always give a result";
}