1 """Define a deck of cards, single-player scoring rules, and pretty-printing.
4 from combinations import xunique_combinations
7 SUITS = ['spades', 'hearts', 'diamonds', 'clubs']
8 """Ordered list of suits.
11 FACE_CARDS = ['ten', 'jack', 'queen', 'king', 'ace']
12 """Ordered list of face cards.
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]`.
20 (0,1) is a two of hearts,
21 (11,0) is a king of spades,
22 (12,3) is an ace of clubs
29 """Pretty-print a card.
39 rank_num = card[0] + 2
41 rank = FACE_CARDS[rank_num-10].capitalize()[0]
46 return '%s%s' % (rank, suit[0])
49 """Un-pretty-print a card.
63 rank = [i for i,r in enumerate(FACE_CARDS) if r.startswith(rank)][0]
66 suit = [i for i,s in enumerate(SUITS) if s[0] == suit][0]
70 """Return a hand in a human readable format (pretty-print)
72 >>> pp_hand([(0, 1), (11, 0), (12, 3)])
75 return ' '.join([pp_card(c) for c in hand])
78 class FiveCardHand (object):
79 """Poker hand with five cards.
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
88 >>> h = FiveCardHand([unpp_card(c) for c in ['7h','5h','7s','5s','Ks']])
90 (2, [(2, [3, 5]), (1, [11])])
91 >>> h = FiveCardHand([unpp_card(c) for c in ['8h','8d','5s','As','5c']])
93 (2, [(2, [3, 6]), (1, [12])])
94 >>> h = FiveCardHand([unpp_card(c) for c in ['Ah','Kd','Qs','Ks','2c']])
96 (1, [(2, [11]), (1, [0, 10, 12])])
97 >>> h = FiveCardHand([unpp_card(c) for c in ['Ah','5d','4s','3s','2c']])
99 (4, [(1, [0, 1, 2, 3, 12])])
101 'straight - Ah 5d 4s 3s 2c'
103 types = ['x high', 'pair 2', 'double pair 2', 'pair 3', 'straight',
104 'flush', 'full house', 'pair 4', 'straight flush']
106 def __init__(self, hand=None):
110 return pp_hand(self.hand)
112 def __cmp__(self, other):
113 return cmp(self.score(), other.score())
115 def _pair_score(self, ranks):
116 """Returns the pair scores from a list of card ranks in a hand.
118 For the sake of clarity, name the pairscore tuple elements
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])
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])
132 def _is_full_house(self, pair_score, **kwargs):
134 >>> FiveCardHand()._is_full_house([(3, [8]), (2, [5])])
137 return [p[0] for p in pair_score] == [3, 2]
139 def _is_pair_4(self, pair_score, **kwargs):
140 return [p[0] for p in pair_score] == [4, 1]
142 def _is_pair_3(self, pair_score, **kwargs):
143 return [p[0] for p in pair_score] == [3, 1]
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)
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)
153 def _is_flush(self, suits, **kwargs):
154 return len(set(suits)) == 1
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]
161 def _is_straight_flush(self, **kwargs):
162 return self._is_straight(**kwargs) and self._is_flush(**kwargs)
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
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
182 type = self.types[score[0]]
183 return '%s - %s' % (type, str(self))
186 class SevenChooseFiveHand (FiveCardHand):
187 """Poker hand with seven cards.
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
193 >>> h = SevenChooseFiveHand([unpp_card(c) for c in
194 ... ['7h','5h','7s','5s','Ks', '7d', 'Jh']])
196 [(5, 1), (3, 1), (5, 0), (3, 0), (11, 0), (5, 2), (9, 1)]
198 [(5, 1), (3, 1), (5, 0), (3, 0), (5, 2)]
200 (6, [(3, [5]), (2, [3])])
202 'full house - 7h 5h 7s 5s 7d Ks Jh'
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.
209 def __init__(self, hand):
210 self.full_hand = hand
211 self.hand,self.residual = self.high_hand()
214 return pp_hand(self.hand + self.residual)
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))
226 return (hand, residual)