from Cards import Hand, Deck
class PokerHand(Hand):
"""Represents a poker hand."""
def suit_hist(self):
"""Builds a histogram of the suits that appear in the hand.
Stores the result in attribute suits.
"""
self.suits = {}
for card in self.cards:
self.suits[card.suit] = self.suits.get(card.suit, 0) + 1
def rank_hist(self):
self.ranks = {}
for card in self.cards:
self.ranks[card.rank] = self.ranks.get(card.rank, 0) + 1
def has_flush(self):
"""Returns True if the hand has a flush, False otherwise.
Note that this works correctly for hands with more than 5 cards.
"""
self.suit_hist()
for val in self.suits.values():
if val >= 5:
return True
return False
def has_pair(self):
self.rank_hist()
for val in self.ranks.values():
if val == 2: return True
return False
def has_twopair(self):
m = 0
self.rank_hist()
for val in self.ranks.values():
if val == 2: m += 1
if m == 2:
return True
else:
return False
def has_three(self):
self.rank_hist()
for val in self.ranks.values():
if val == 3: return True
return False
def has_straight(self):
#straight is a seuence of 5 cards or 4 cards + Ace
#how to chek if it is a sequence?
#ebaniy straight!
chek = 0
hand_ranks = []
for card in self.cards:
hand_ranks.append(card.rank)
h_ranks = sorted(set(hand_ranks))
for i in range(len(h_ranks)-1):
if h_ranks[i]+1 == h_ranks[i+1]:
chek += 1
if chek == 5 and 1 in hand_ranks:
return True
if chek == 5:
return True
else:
chek = 0
return False
def has_four(self):
self.suit_hist()
for suit in self.suits.values():
if suit == 4: return True
return False
def has_straight_flush(self):
return self.has_straight() and self.has_flush()
def has_fullhouse(self):
return self.has_pair() and self.has_three()
def classify(self):
d = {"straight flush": self.has_straight_flush(), "four": self.has_four(), "fullhouse": self.has_fullhouse(),
"flush": self.has_flush(), "straight": self.has_straight(), "three": self.has_three(), "two pairs": self.has_twopair(),
"pair": self.has_pair()}
for key in d.keys():
if d[key] == True:
self.label = str(key)
break
if __name__ == '__main__':
# make a deck
deck = Deck()
deck.shuffle()
# deal the cards and classify the hands
for i in range(7):
hand = PokerHand()
deck.move_cards(hand, 7)
hand.sort()
print(hand)
print("Has a flush:", hand.has_flush())
print("Has a pair:", hand.has_pair())
print("Has a pair of pairs:", hand.has_twopair())
print("Has three of a kind:", hand.has_three())
print("Has a full house:", hand.has_fullhouse())
print("Has straight:", hand.has_straight())
hand.classify()
print(hand.label)
print('')
# your code goes here