bots/hole_bot.py should not be executable.
[poker.git] / deck.py
1 """Define a deck of cards, single-player scoring rules, and pretty-printing.
2 """
3
4 from combinations import xunique_combinations
5
6
7 SUITS = ['spades', 'hearts', 'diamonds', 'clubs']
8 """Ordered list of suits.
9 """
10
11 FACE_CARDS = ['ten', 'jack', 'queen', 'king', 'ace']
12 """Ordered list of face cards.
13 """
14
15 DECK = [(c/4, c%4) for c in range(52)]
16 """Cards in the deck are stored as (n,m), where `n` is the rank number
17 `n=[0,12]`, and `m` is the suit `m=[0,3]`.
18
19 Examples: 
20  (0,1)  is a two of hearts, 
21  (11,0) is a king of spades,
22  (12,3) is an ace of clubs
23
24 >>> DECK[:5]
25 """
26
27
28 def pp_card(card):
29     """Pretty-print a card.
30
31     >>> pp_card((0, 1))
32     '2h'
33     >>> pp_card((8, 3))
34     'Tc'
35     >>> pp_card((11, 0))
36     'Ks'
37     """
38     s = []
39     rank_num = card[0] + 2
40     if rank_num >= 10:
41         rank = FACE_CARDS[rank_num-10].capitalize()[0]
42     else:
43         rank = str(rank_num)
44     
45     suit = SUITS[card[1]]
46     return '%s%s' % (rank, suit[0])
47
48 def unpp_card(card):
49     """Un-pretty-print a card.
50
51     >>> unpp_card('2h')
52     (0, 1)
53     >>> unpp_card('Tc')
54     (8, 3)
55     >>> unpp_card('Ks')
56     (11, 0)
57     """
58     rank,suit = card
59     try:
60         rank = int(rank)
61     except ValueError:
62         rank = rank.lower()
63         rank = [i for i,r in enumerate(FACE_CARDS) if r.startswith(rank)][0]
64         rank += 10
65     rank -= 2
66     suit = [i for i,s in enumerate(SUITS) if s[0] == suit][0]
67     return (rank, suit)
68
69 def pp_hand(hand):
70     """Return a hand in a human readable format (pretty-print)
71
72     >>> pp_hand([(0, 1), (11, 0), (12, 3)])
73     '2h Ks Ac'
74     """
75     return ' '.join([pp_card(c) for c in hand])
76
77
78 class FiveCardHand (object):
79     """Poker hand with five cards.
80
81     To determine which five card hand is stronger according to
82     standard poker rules, each hand is given a score and a pair
83     rank. The score cooresponds to the poker hand (Straight Flush=8,
84     Four of a Kind=7, etc...). The pair score is used to break ties.
85     The pair score creates a set of pairs then rank sorts within each
86     set.
87
88     >>> h = FiveCardHand([unpp_card(c) for c in ['7h','5h','7s','5s','Ks']])
89     >>> h.score()
90     (2, [(2, [3, 5]), (1, [11])])
91     >>> h = FiveCardHand([unpp_card(c) for c in ['8h','8d','5s','As','5c']])
92     >>> h.score()
93     (2, [(2, [3, 6]), (1, [12])])
94     >>> h = FiveCardHand([unpp_card(c) for c in ['Ah','Kd','Qs','Ks','2c']])
95     >>> h.score()
96     (1, [(2, [11]), (1, [0, 10, 12])])
97     >>> h = FiveCardHand([unpp_card(c) for c in ['Ah','5d','4s','3s','2c']])
98     >>> h.score()
99     (4, [(1, [0, 1, 2, 3, 12])])
100     >>> h.pp_score()
101     'straight - Ah 5d 4s 3s 2c'
102     """
103     types = ['x high', 'pair 2', 'double pair 2', 'pair 3', 'straight',
104              'flush', 'full house', 'pair 4', 'straight flush']
105
106     def __init__(self, hand=None):
107         self.hand = hand
108
109     def __str__(self):
110         return pp_hand(self.hand)
111
112     def __cmp__(self, other):
113         return cmp(self.score(), other.score())
114
115     def _pair_score(self, ranks):
116         """Returns the pair scores from a list of card ranks in a hand.
117
118         For the sake of clarity, name the pairscore tuple elements
119         `(paircount,ranks)`.
120
121         >>> h = FiveCardHand()
122         >>> h._pair_score([5, 3, 5, 3, 11])
123         [(2, [3, 5]), (1, [11])]
124         >>> h._pair_score([8, 8, 5, 8, 5])
125         [(3, [8]), (2, [5])]
126         """
127         rank_counts = [(ranks.count(r), r) for r in set(ranks)]
128         counts = sorted(set([rc[0] for rc in rank_counts]), reverse=True)
129         return [(c, [rc[1] for rc in rank_counts if rc[0] == c])
130                 for c in counts]
131
132     def _is_full_house(self, pair_score, **kwargs):
133         """
134         >>> FiveCardHand()._is_full_house([(3, [8]), (2, [5])])
135         True
136         """
137         return [p[0] for p in pair_score] == [3, 2]
138
139     def _is_pair_4(self, pair_score, **kwargs):
140         return [p[0] for p in pair_score] == [4, 1]
141
142     def _is_pair_3(self, pair_score, **kwargs):
143         return [p[0] for p in pair_score] == [3, 1]
144
145     def _is_double_pair_2(self, pair_score, **kwargs):
146         return ([p[0] for p in pair_score] == [2, 1]
147                 and len(pair_score[0][1]) == 2)
148
149     def _is_pair_2(self, pair_score, **kwargs):
150         return ([p[0] for p in pair_score] == [2, 1]
151                 and len(pair_score[0][1]) == 1)
152
153     def _is_flush(self, suits, **kwargs):
154         return len(set(suits)) == 1
155
156     def _is_straight(self, ranks, **kwargs):  # Handles the low Ace as well
157         ranks = sorted(ranks)
158         diff  = [(x2-x1) for x1,x2 in zip(ranks, ranks[1:])]
159         return set(diff) == set([1]) or ranks == [0,1,2,3,12]
160
161     def _is_straight_flush(self, **kwargs):
162         return self._is_straight(**kwargs) and self._is_flush(**kwargs)
163
164     def _type_index(self, ranks, suits, pair_score):
165         for i,type in enumerate(reversed(self.types)):
166             if type == 'x high': continue
167             is_type = getattr(self, '_is_%s' % type.replace(' ', '_'))
168             if is_type(ranks=ranks, suits=suits, pair_score=pair_score):
169                 return len(self.types) - i - 1
170         return 0
171
172     def score(self):
173         if hasattr(self, '_score'): return self._score # return cached
174         ranks,suits = zip(*self.hand)
175         pair_score = self._pair_score(ranks)
176         type_index = self._type_index(ranks, suits, pair_score)
177         self._score = (type_index, pair_score) # cache
178         return self._score
179
180     def pp_score(self):
181         score = self.score()
182         type = self.types[score[0]]
183         return '%s - %s' % (type, str(self))
184
185
186 class SevenChooseFiveHand (FiveCardHand):
187     """Poker hand with seven cards.
188
189     To determine who wins a poker hand each player determines the best
190     hand they can make within their (7 choose 5) = 21 possible five card
191     combinations.
192
193     >>> h = SevenChooseFiveHand([unpp_card(c) for c in
194     ...     ['7h','5h','7s','5s','Ks', '7d', 'Jh']])
195     >>> h.full_hand
196     [(5, 1), (3, 1), (5, 0), (3, 0), (11, 0), (5, 2), (9, 1)]
197     >>> h.hand
198     [(5, 1), (3, 1), (5, 0), (3, 0), (5, 2)]
199     >>> h.score()
200     (6, [(3, [5]), (2, [3])])
201     >>> h.pp_score()
202     'full house - 7h 5h 7s 5s 7d Ks Jh'
203     """
204     # Prevent a bajillion calls to xunqiue_combinations
205     _hand_indices = list(xunique_combinations(range(7), 5))
206     """List of unique indices selecting 5 cards from a hand of 7.
207     """
208
209     def __init__(self, hand):
210         self.full_hand = hand
211         self.hand,self.residual = self.high_hand()
212
213     def __str__(self):
214         return pp_hand(self.hand + self.residual)
215
216     def high_hand(self):
217         score = hand = residual = None
218         for indices in self._hand_indices:
219             h = FiveCardHand([self.full_hand[i] for i in indices])
220             if h.score() > score:
221                 residual = [self.full_hand[i]
222                             for i in range(len(self.full_hand))
223                             if i not in indices]
224                 score = h.score()
225                 hand = h.hand
226         return (hand, residual)