-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfivecarddraw.py
1579 lines (1323 loc) · 54 KB
/
fivecarddraw.py
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
from functools import reduce
from itertools import groupby
from math import inf
from random import choice, shuffle
class Card(object):
"""
A class to represent a card.
Attributes
----------
MASK : str
a guide for intepreting the binary encoding of the card
PRIMES : tuple
a cipher for encoding the card value as a prime
_prime : int
the prime encoding of the card value
_rank : int
the decimal encoding of the card value
_suit : int
the binary, one hot encoding of the card suit
_value : int
the binary, one hot encoding of the card value
b : int
the binary encoding of the card that combines _prime, _rank, _suit and _value
value_r : str
the str representation of card value
suit_r : str
thr str representation of card suit
value_i : int
a class parameter for the card value
suit_i : int
a class parameter for the card suit
"""
def __init__(self, value : int, suit : int):
"""
Constructs all the necessary attributes for the card object.
Parameters
----------
value : card value
suit : card suit
"""
# assert acceptable parameters
try:
value %= 13
suit %= 4
except TypeError:
raise TypeError("Card objects only allow integers as arguments.")
# encode card as integer for fast hand ranking
self.MASK = "xxxAKQJT98765432♣♢♡♠RRRRxxPPPPPP"
self.PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41)
self._prime = self.PRIMES[value]
self._rank = value << 8
self._suit = (2 ** suit) << 12
self._value = (2 ** value) << 16
self.b = self._prime + self._rank + self._suit + self._value
# encode card as string for representation
self.VALUES = ("2","3","4","5","6","7","8","9","10","J","Q","K","A")
self.SUITS = "♠♡♢♣"
self.value_r, self.suit_r = self.VALUES[value], self.SUITS[suit]
self.r = self.value_r + self.suit_r
# store input parameters
self.value_i, self.suit_i = value, suit
def __repr__(self):
"""Displays the card value and card suit when the card object is printed."""
return self.r
def __str__(self):
"""Converts the card object to a string dispalying the card value and card suit."""
return self.r
def __int__(self):
"""Converts the card object to an integer that encodes the card value and card suit."""
return self.b
def __hash__(self):
"""Creates a hash that's derived from the card value and card suit."""
return hash((self.value_i, self.suit_i, self.b))
def __eq__(self, other):
"""Compares the hash of the card object with others."""
return hash(self) == hash(other)
class Deck(object):
"""
A class to represent a deck of cards.
Attributes
----------
state : list[Card]
the order of the cards in the deck
t : int
the amount of cards no longer in the deck
Methods
-------
Shuffle :
Shuffles order of remaining cards in deck.
CollectCards :
Set the amount of cards no longer in the deck to 0.
DepartedCards :
Get a list of the cards no longer in the deck.
RemainingCards :
Get a list of the cards remaining in the deck.
"""
def __init__(self):
"""Constructs all the necessary attributes for the deck object."""
# create list of 52 unique cards
self.state = [Card(v, s) for v in range(13) for s in range(4)]
# initialise tracking attribute for tracking remaining cards in deck
self.t = 0
def __repr__(self):
"""Displays the remaining cards in the deck when the deck object is printed."""
return str(self.RemainingCards())
def __str__(self):
"""Converts the deck object to a string displaying the remaining cards in the deck."""
return str(self.RemainingCards())
def __iter__(self):
"""Converts the deck object to an iterator providing each card of a 52-card deck."""
return self.state
def __next__(self):
"""Provides the top card of the deck."""
# assert there is a remaining card in deck
try:
top_card = self.RemainingCards()[0]
except IndexError:
raise StopIteration("No more cards in the deck")
# return first remaining card as top card and update tracker
self.t += 1
return top_card
def __len__(self):
"""Provides the amount of cards remaining in deck."""
return 52 - self.t
def Shuffle(self):
"""
Shuffles the order of remaining cards in deck.
Side effects
------------
The state attribute is permutated.
"""
departed_cards = self.DepartedCards()
remaining_cards = self.RemainingCards()
shuffle(remaining_cards)
self.state = departed_cards + remaining_cards
def CollectCards(self):
"""
Set the amount of cards no longer in the deck to 0.
Side effects
------------
The t attribute is set to 0.
"""
self.t = 0
def DepartedCards(self) -> list[Card]:
"""
Get a list of the cards no longer in the deck.
"""
return self.state[:self.t]
def RemainingCards(self) -> list[Card]:
"""
Get a list of the cards remaining in the deck.
"""
return self.state[self.t:]
class HandTracker(object):
"""
A class to handle card dynamics during a game of five card draw poker.
Attributes
----------
DECK : Deck
a deck of cards
hands : dict
player hand data
FLUSH_RANKS : dict
ratings for flush hands
UNIQUE_5_RANKS : dict
ratings for hands with 5 unique-valued cards and different suits
DUPE_RANKS : dict
ratings for hands with at least one pair of cards with the same card value.
Methods
-------
TrackPlayers :
Begin tracking players.
UntrackPlayers :
Stop tracking players.
AssignCards :
Associate cards with a player.
UnassignCards :
Stop associating cards with a player.
DealHand :
Get top five cards of the deck.
DealPlayersIn :
Deal cards to each player being tracked.
SwapCards :
Get a list of cards to replace some discarded cards.
SwapPlayersCards :
Replace the discarded cards of a tracked player.
AllowDiscards :
Decide if discarding chosen cards is allowed.
CollectCards :
Remove cards from tracked players and return them to the deck.
ShuffleDeck :
Shuffles order of remaining cards in deck.
LoadData :
Load the ratings for each possible hand in five card draw poker.
HasFlush :
Determines if a hand contains a flush.
HasUnique5 :
Determines if a hand contains five unique valued cards.
TwosEncoding :
Convert hand to a sum of powers of two.
PrimesEncoding :
Convert hand to a product of prime numbers.
EvaluateHand :
Get the rating of a hand.
EvaluatePlayersIn :
Store the rating of each tracked players hand.
TrackedPlayers :
Get a list of players being tracked.
TrackedHand :
Get a list of cards assigned to a player.
"""
def __init__(self):
"""Constructs all the necessary attributes for the handtracker object."""
# create a deck
self.DECK = Deck()
# create a state for player hand data
self.players = {}
# load data containing ratings of all possible five card hands
self.LoadData()
def TrackPlayers(self, names : list[str]):
"""
Inserts some names into the tracker so the tracker can begin storing data about them.
Parameters
----------
names : the names of players
Side effects
------------
The players attribute gets additional keys.
"""
# assert player is not being tracked already
for name in names:
if name in self.players:
raise Exception(f"{name} is already being tracked.")
# begin tracking players
self.players.update({name : {"cards" : []} for name in names})
def UntrackPlayers(self, names : list[str]):
"""
Removes some names from the tracker.
Parameters
----------
names : the names of players
Side effects
------------
The players attribute loses some keys.
"""
for name in names:
# assert each player was being tracked
try:
# stop tracking player
del self.players[name]
except KeyError:
raise KeyError(f"{name} is not being tracked.")
def AssignCards(self, name : str, cards : list[Card]):
"""
Allocates additional cards to a player.
Parameters
----------
name : the name of a player
cards : cards to assign to the player
Side effects
------------
The players attribute has some values updated.
"""
# assert player is being tracked
try:
# allocate cards to player
self.players[name]["cards"].extend(cards)
except KeyError:
raise KeyError(f"{name} is not being tracked.")
def UnassignCards(self, name : str, cards : list[Card]):
"""
Unallocates specifric cards from a player.
Parameters
----------
name : the name of a player
cards : cards to unassign from the player
Side effects
------------
The players attribute has some values updated.
"""
# assert player is holding all cards
if set(cards).intersection(self.Hand(name)) != set(cards):
raise Exception(f"{name} is not holding some of {cards}.")
# assert player is being tracked
try:
# unallocate cards from player
self.players[name]["cards"] = [card for card in self.Hand(name) if card not in cards]
except KeyError:
raise KeyError(f"{name} is not being tracked.")
def DealHand(self) -> list[Card]:
"""
Provide five cards from the deck.
Side effects
------------
The DECK.t attribute is increased by five.
"""
# assert enough cards are in the deck to deal
if 5 > len(self.DECK):
Exception("There are not enough cards remaining in the deck.")
# return a five card hand
hand = [next(self.DECK) for _ in range(5)]
return hand
def DealPlayersIn(self):
"""
Provides five cards to all players being tracked.
Side effects
------------
The players attribute has some values updated.
"""
# determine if enough cards are in the deck to deal everyone hands
if len(self.players) * 5 > len(self.DECK):
Exception("There are not enough cards remaining to deal all players hands.")
# deal hands to tracked players
for player in self.players:
hand = self.DealHand()
self.AssignCards(player, hand)
def SwapCards(self, discards : list[Card]) -> list[Card]:
"""
Provides cards to replace some discarded cards.
Parameters
----------
discards : cards to swap
Side effects
------------
The DECK attribute has the t attribute increased by the amount of cards being discarded.
"""
# assert enough cards in deck
if len(self.DECK) < len(discards):
raise Exception(f"Not enough cards in deck to swap {discards}.")
# get new cards and return them
new_cards = [next(self.DECK) for _ in range(len(discards))]
return new_cards
def SwapPlayersCards(self, name : str, discards : list[Card]):
"""
Provides cards to replace some cards discarded by a tracked player.
Parameters
----------
name : name of tracked player
discards : cards to swap
Side effects
------------
The DECK attribute has the t attribute increased by the amount of cards being discarded.\n
The players attribute has some values updated.
"""
# assert enough cards in deck
if len(self.DECK) < len(discards):
raise Exception(f"Not enough cards in deck to swap {discards}.")
# remove discards from hand
self.UnassignCards(name, discards)
# get new cards and assign to player
new_cards = [next(self.DECK) for _ in range(len(discards))]
self.AssignCards(name, new_cards)
def AllowDiscards(self, hand : list[Card], discards : list[Card]) -> bool:
"""
Decides if discarding a selection of cards from a hand is acceptible in five card draw.
Parameters
----------
hand : the hand to discard from
discards : the selection of cards to discard
"""
# assert 5 card hands
if len(hand) != 5 or len(discards) > 5:
raise Exception("Unknown variant of poker.")
# the whole hand cannot be discarded
if len(discards) == 5:
return False
# if four cards are discarded the last card must be an ace
remaining = [card for card in hand if card not in discards]
# hand will be multiple of 41 if it has an ace, otherwise it will have a remainder
if len(discards) == 4 and self.PrimesEncoding(remaining) % 41:
return False
# discard request approved
return True
def CollectCards(self):
"""
Puts all cards back in the deck.
Side effects
------------
The deck attribute has the t attribute set to 0. \n
The players attribute is cleared.
"""
self.DECK.CollectCards()
players = self.TrackedPlayers()
self.UntrackPlayers(players)
def ShuffleDeck(self):
"""
Shuffles the remaining cards in the deck .
Side effects
------------
The deck attribute has the state attribute permutated.
"""
self.DECK.Shuffle()
def LoadData(self):
"""
Constructs all the hand ranking attributes for the handtracker object.
Side effects
------------
The FLUSH_RANKS attribute is created. \n
The UNIQUE5_RANKS attribute is created. \n
The DUPES_RANKS attribute is created.
"""
# create ciphers for reading and encoding hands for fast hand ranking
PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41)
DV = {char : 2 ** i for i, char in enumerate("23456789TJQKA")}
DP = {char : PRIMES[i] for i, char in enumerate("23456789TJQKA")}
CLASSES = {
"HC" : "high card",
"1P" : "pair",
"2P" : "two pair",
"3K" : "three of a kind",
"SS" : "straight",
"FF" : "flush",
"FH" : "full house",
"4K" : "four of a kind",
"SF" : "straight flush",
"RF" : "royal flush"}
# store ratings of all hands with flushes
self.FLUSH_RANKS = {}
# read data
with open("data/flushes.txt", "r") as file:
for line in file:
# locate and encode hand as sum of powers of two
hand = reduce(lambda x, y : x+y, map(lambda x : DV[line[int(x)]], "45678"))
# store hand ratings by integer key
self.FLUSH_RANKS[hand] = []
# store numerical rating
self.FLUSH_RANKS[hand].append(int(str(line)[11:]))
# store categorical rating
self.FLUSH_RANKS[hand].append(CLASSES[str(line[:2])])
# store ratings of all non-flush hands with 5 unique card values
self.UNIQUE5_RANKS = {}
# read data
with open("data/uniquefive.txt", "r") as file:
for line in file:
# locate and encode hand as sum of powers of two
hand = reduce(lambda x, y : x+y, map(lambda x : DV[line[int(x)]], "45678"))
# store hand ratings by integer key
self.UNIQUE5_RANKS[hand] = []
# store numerical rating
self.UNIQUE5_RANKS[hand].append(int(str(line)[11:]))
# store categorical rating
self.UNIQUE5_RANKS[hand].append(CLASSES[str(line[:2])])
# store ratings of all hands with duplicate card values
self.DUPE_RANKS = {}
# read data
with open("data/dupes.txt", "r") as file:
for line in file:
# locate and encode hand as product of primes
hand = reduce(lambda x, y : x*y, map(lambda x : DP[line[int(x)]], "45678"))
# store hand ratings by integer key
self.DUPE_RANKS[hand] = []
# store numerical rating
self.DUPE_RANKS[hand].append(int(str(line)[11:]))
# store categorical rating
self.DUPE_RANKS[hand].append(CLASSES[str(line[:2])])
def HasFlush(self, cards : list[Card]) -> bool:
"""
Check if a hand contains a flush.
Parameters
----------
cards : hand to check
"""
# look at suit bits of each card
suit_mask = 15 << 12
has_flush = reduce(lambda x, y : x&y, map(lambda x : int(x), cards)) & suit_mask
return bool(has_flush)
def HasUnique5(self, cards : list[Card]) -> bool:
"""
Check if a hand contains five unique cards.
Parameters
----------
cards : hand to check
"""
# look at value bits of each card
values = reduce(lambda x, y : x|y, map(lambda x : int(x), cards)) >> 16
has_unique5 = bin(values).count("1") == 5
return has_unique5
def TwosEncoding(self, cards : list[Card]) -> int:
"""
Convert hand to a sum of powers of two.
Parameters
----------
cards : hand to convert
"""
return reduce(lambda x, y : x|y, map(lambda x : int(x), cards)) >> 16
def PrimesEncoding(self, cards : list[Card]) -> int:
"""
Convert hand to a product of primes.
Parameters
----------
cards : hand to convert
"""
return reduce(lambda x, y : x*y, map(lambda x : int(x) & 255, cards))
def EvaluateHand(self, hand : list[Card]) -> tuple[int, str]:
"""
Evaluates a hand both numerically and categorically.
Parameters
----------
hand : hand to evaluate
"""
# assert 5 card hands
if len(hand) != 5 :
raise Exception("Unknown variant of poker.")
# encode hand as int and use as key to get rank
if self.HasFlush(hand):
key = self.TwosEncoding(hand)
return self.FLUSH_RANKS[key]
elif self.HasUnique5(hand):
key = self.TwosEncoding(hand)
return self.UNIQUE5_RANKS[key]
else:
key = self.PrimesEncoding(hand)
return self.DUPE_RANKS[key]
def EvaluatePlayersIn(self):
"""
Evaluates the hands of tracked players.
Side effects
------------
hands : The players attribute has some values updated.
"""
# evaluate hands of players being tracked and store the info
for player in self.players:
hand = self.Hand(player)
rank_n, rank_c = self.EvaluateHand(hand)
self.players[player]["rank_n"] = rank_n
self.players[player]["rank_c"] = rank_c
def TrackedPlayers(self) -> list:
"""
Provides the names of players being tracked.
"""
return [*self.players]
def Hand(self, name : str) -> list[Card]:
"""
Provides the hand of a player being tracked.
"""
# assert player is being tracked and return hand
try:
return self.players[name]["cards"]
except KeyError:
raise KeyError(f"{name} is not being tracked.")
class SeatTracker(object):
"""
A class to handle seating dynamics during a game of five card draw poker.
Attributes
----------
seats : list[str]
seat vacancies and occupants indexed by seat number
players : dict
player seating data
button : dict
button assignment data
L : int
the maximum player capacity of the tracker
Methods
-------
OccupySeat :
Assign a player to a seat
EmptySeat :
Unassign a player from a seat
TrackPlayers :
Begin tracking players
UntrackPlayers :
Stop tracking players
SeatPlayers :
Assign tracked players to seats
KickPlayers :
Unassign tracked players from seats
MoveButton :
Move button to next player
TrackButton :
Update button data
TrackedPlayers :
Get list of tracked players
AvailableSeats :
Get list of available seats
"""
def __init__(self, amount_seats : int = 5):
"""
Constructs all the necessary attributes for the seattracker object.
Parameters
----------
amount_seats : the maximum player capacity of the game of five card draw
"""
# initialise seat tracking
self.seats = ["" for _ in range(amount_seats)]
# initialise player tracking
self.players = {}
# initialise button tracking
self.button = {"seat" : -1, "player" : ""}
# store input parameters
self.L = amount_seats
def __iter__(self):
"""Converts the seatracker object to an iterator providing players in dealing order."""
b_seat = self.button["seat"]
return (player for player in self.seats[b_seat+1:] + self.seats[:b_seat+1] if player)
def __len__(self):
"""Provides the amount of seats being tracked by the tracker."""
return self.L
def OccupySeat(self, name : str, seat : int):
"""
Occupies a seat with a player.
Parameters
----------
name : player's name
seat : index of seat to occupy
Side effects
------------
The seats attribute has an item replaced.
"""
# assert name is unique
if name in self.seats:
raise Exception(f"{name} is already occupying a seat.")
# assert seat at table
if seat >= len(self) or seat < 0:
raise IndexError(f"No seat with index {seat}.")
# assert seat is empty
if self.seats[seat]:
raise Exception(f"The seat is already occupied by {self.seats[seat]}.")
# occupy seat
self.seats[seat] = name
def EmptySeat(self, seat : int):
"""
Empties a seat occupied by a player.
Parameters
----------
seat : index of seat to empty
Side effects
------------
The seats attribute has an item replaced.
"""
# assert seat at table
if seat >= len(self) or seat < 0:
raise IndexError(f"No seat with index {seat}.")
# assert seat is occupied
if not self.seats[seat]:
raise Exception(f"The seat {seat} wasn't occupied.")
# empty seat
self.seats[seat] = ""
def TrackPlayers(self, names : list[str]):
"""
Inserts some names into the tracker so the tracker can begin storing data about them.
Parameters
----------
names : players to track
Side effects
------------
The players attribute gets additional keys.
"""
for name in names:
# assert name is unique
if name in self.players:
raise Exception(f"{name} is already being tracked.")
# begin tracking
self.players.update({name : {}})
def UntrackPlayers(self, names : list[str]):
"""
Removes some names from the player tracker.
Parameters
----------
names : players to stop tracking
Side effects
------------
The players attribute has some keys removed.
"""
for name in names:
# assert each player was being tracked
try:
# stop tracking player
del self.players[name]
except KeyError:
raise KeyError(f"{names} is not being tracked.")
def SeatPlayers(self):
"""
Allocates seats to tracked players.
Side effects
------------
The seats attribute has items replaced. \n
The players attribute has some values updated.
"""
# select seats
seats = self.AvailableSeats()
shuffle(seats)
# get players names to be seated
players = [name for name in self.players if not self.players[name]]
# assert enough seats
if len(players) > len(seats):
raise Exception(f"There is not enough available seats for {players}.")
# allocate seats
for assignment in zip(players, seats):
name, empty_seat = assignment
# update seat tracker
self.OccupySeat(name, empty_seat)
# update player tracker
self.players[name] = empty_seat
def KickPlayers(self, players : list[str]):
"""
Removes players from the game.
Parameters
----------
players : players to kick from seats
Side effects
------------
The seats attribute has items replaced. \n
The players attribute has some keys deleted.
"""
# assert players are being tracked
for name in players:
if name not in self.players:
raise KeyError(f"{name} is not being tracked.")
# update seat tracker
seat = self.players[name]
self.EmptySeat(seat)
# update player tracker
self.UntrackPlayers(players)
def TrackButton(self):
"""
Stores information about the button seat.
Side effects
------------
The button attribute has a value updated.
"""
b_seat = self.button["seat"]
self.button["player"] = self.seats[b_seat]
def MoveButton(self):
"""
Moves the button to the next occupied seat if possible, otherwise the next empty one.
Side effects
------------
The button attribute has both values updated.
"""
# find player to give button to if possible
while True:
# check each seat for a player
seat = self.button["seat"]
seat += 1
seat %= len(self)
self.button["seat"] = seat
# stop if player is at seat or there are no seated players
if self.seats[seat] or not self.players:
break
# update button tracker
self.TrackButton()
def TrackedPlayers(self) -> list[str]:
"""
Provides the names of players being tracked.
"""
return [*self.players]
def AvailableSeats(self) -> list[int]:
"""
Provides the seats that are unoccupied.
"""
return [i for i, occupant in enumerate(self.seats) if not occupant]
def OccupiedSeats(self) -> list[int]:
"""
Provides the seats that are occupied.
"""
return [i for i, occupant in enumerate(self.seats) if occupant]
class ChipTracker(object):
def __init__(self):
# initialise player and rules trackers
self.gameinfo = {"ante" : 0}
self.players = {}
def __abs__(self):
return sum([self.Contribution(player) + self.Stack(player) for player in self.players])
def TrackPlayers(self, names):
# initialise player tracking
self.players = {name : {"stack" : 0, "contribution" : 0 } for name in names}
def UntrackPlayers(self, names):
for name in names:
# assert each player was being tracked
try:
# stop tracking player
del self.players[name]
except KeyError:
raise KeyError(f"{name} is not being tracked.")
def Reward(self, name, amount):
# assert player is being tracked
if name not in self.players:
raise KeyError(f"{name} is not being tracked.")
# add chips to players stack
self.players[name]["stack"] += amount
def Spend(self, name, amount):
# assert player has enough chips
if not self.HasEnough(name, amount):
raise ValueError(f"{name} doesn't have enough chips to pay {amount} chips.")
# remove chips from players stack
self.players[name]["stack"] -= amount
def HasEnough(self, name, amount):
# check if player has enough chips
return True if amount <= self.players[name]["stack"] else False
def Bet(self, name, amount):
# remove chips from player
self.Spend(name, amount)
# add chips to pot
self.players[name]["contribution"] += amount
def CallAmount(self, name):
# calculate how many chips a player needs to contribute, to minimum call
return self.MaxContribution() - self.Contribution(name)
def BetDetails(self, name, amount):
# check if bet is players full stack
has_allin = True if amount == self.Stack(name) else False
# check if bet is atleast the min call amount
min_to_call = self.CallAmount(name)
has_mincalled = True if amount >= min_to_call else False
if has_mincalled:
# check if bet is more than the min call amount
has_raised = True if amount > min_to_call else False
has_folded = False
else:
# check if player didn't bet anything
has_folded = True if not amount else False
has_raised = False
return {"has_raised" : has_raised, "has_allin" : has_allin, "has_mincalled" : has_mincalled, "has_folded" : has_folded}
def GatherContributions(self, cap):
contributions = 0
# check contribution of each player
for contributor in self.players:
# take capped contributions
if not self.Contribution(contributor):
continue
if self.Contribution(contributor) > cap:
contributions += cap
self.players[contributor]["contribution"] -= cap