fork download
  1. import random
  2.  
  3. class Card(object):
  4. """ card from a deck of 52:
  5. Attributes:
  6. Suit,
  7. Rank.
  8. """
  9. suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
  10. rank_names = [None, None, '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
  11.  
  12. def __init__(self, suit = 0, rank = 2):
  13. self.suit = suit
  14. self.rank = rank
  15.  
  16. def __str__(self):
  17. if isinstance(self, Card):
  18. return '%s of %s' % (self.rank_names[self.rank], self.suit_names[self.suit])
  19.  
  20. def __cmp__(self, other):
  21. t1 = self.suit, self.rank
  22. t2 = other.suit, other.rank
  23. return cmp(t1, t2)
  24.  
  25. class Deck(object):
  26. """ standard deck of 52 cards """
  27.  
  28. def __init__(self):
  29. self.cards = []
  30. for suit in range(4):
  31. for rank in range(2, 15):
  32. card = Card(suit, rank)
  33. self.cards.append(card)
  34.  
  35. def __str__(self):
  36. deck_list = []
  37. for card in self.cards:
  38. deck_list.append(str(card))
  39. return '\n'.join(deck_list)
  40.  
  41. def pop_card(self):
  42. return self.cards.pop()
  43.  
  44. def shuffle_deck(self):
  45. random.shuffle(self.cards)
  46.  
  47. class Hand(object):
  48. """ single poker hand,
  49. attributes:
  50. from Deck deck,
  51. number of cards.
  52. """
  53.  
  54. def __init__(self,deck,n_cards):
  55. self.cards = []
  56. j_card = 0
  57. while j_card < n_cards:
  58. dealt_card = deck.pop_card()
  59. self.cards.append(dealt_card)
  60. j_card = j_card + 1
  61.  
  62. def __str__(self):
  63. hand_list = []
  64. for card in self.cards:
  65. hand_list.append(str(card))
  66. return '\n'.join(hand_list)
  67.  
  68. def score(self):
  69. str_hand = str(self)
  70. print 'Evaluate hand: \n',
  71. B_flush = self.flush()
  72.  
  73. def flush(self):
  74. suit_0 = self.cards[0].suit_names[self.cards[0].suit]
  75. print '\nsuit of card 0 is', suit_0
  76. return
  77. n_cards = len(self.cards)
  78. j_card = 1
  79. while j_card < n_cards:
  80. if self.cards[j_card].suit_names[self.cards[j_card].suit] != suit_0:
  81. print self, 'is not a flush.'
  82. return False
  83. j_card = j_card + 1
  84. print self, 'is a flush.'
  85. return True
  86.  
  87. #my_card1= Card(2,12)
  88. #my_card2 = Card(0,12)
  89. #print my_card1, ' ' * 4, my_card2, ' ' * 4,'Comparison result: ', cmp(my_card1, my_card2)
  90.  
  91. deck = Deck()
  92. # print deck
  93. # print deck.cards[10]
  94. deck.shuffle_deck()
  95. # n_players = 4
  96. n_cards = 5
  97. hand1 = Hand(deck,n_cards)
  98. # print hand1
  99. hand1.score()
  100.  
  101. # dealt_card = deck.pop_card()
  102. # print type(dealt_card)
  103. # print dealt_card
  104. # print len(deck.cards)
Success #stdin #stdout 0.1s 10976KB
stdin
Standard input is empty
stdout
Evaluate hand: 

suit of card 0 is Diamonds