Guest User

Untitled

a guest
May 22nd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.05 KB | None | 0 0
  1. import random # Random library is imported to enable us choose a random card
  2.  
  3. class Deck():
  4. """This is an abstract class. Player and Dealer
  5. are meant to inherit its pick function for picking
  6. a random card from the deck """
  7.  
  8. deck_cards = ['A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2'] * 4
  9. #represents all the cards in the deck
  10.  
  11. def pick(self, num):
  12. '''
  13. Picks the specified number of cards from the existing
  14. desk and returns it in a form of a list.
  15. '''
  16.  
  17. picked = []
  18. for _ in range(num):
  19.  
  20. choosen = random.randint(0, len(self.deck_cards) - 1)
  21. picked.append(self.deck_cards[choosen])
  22.  
  23. #Removes the card that is picked up
  24. self.deck_cards.pop(choosen)
  25.  
  26. return picked
  27.  
  28.  
  29. class Player(Deck):
  30. """An object of this class keeps the track of players
  31. progress in the game including its cards, money, burst
  32. situation. It also initiates the player with 500 units"""
  33.  
  34. cards = []
  35. burst = False
  36.  
  37. def __init__(self):
  38. self.money = 500
  39.  
  40.  
  41. class Dealer(Deck):
  42. """An object of this class keeps the track of dealers
  43. progress in the game including its cards, and burst
  44. situation."""
  45.  
  46. cards = []
  47. burst = False
  48.  
  49. #FUNCTIONS
  50.  
  51. def print_cards(cards):
  52. """prints the card value inside a box """
  53.  
  54. for i in range(len(cards)):
  55. print("{0:^4}-----".format(''))
  56. print("{0:^4}|{1:^3}|".format('', cards[i]))
  57. print("{0:^4}-----".format(''))
  58.  
  59.  
  60. def print_board(cards1, cards2):
  61. """Prints the complete board situation including both
  62. the players as well as the dealers cards"""
  63.  
  64. print("n"*50)
  65. print("*************")
  66. print("Player cards:")
  67. print("*************")
  68. print_cards(cards1)
  69. print("*************")
  70. print("Dealer cards:")
  71. print("*************")
  72. print_cards(cards2)
  73. print("*************")
  74.  
  75.  
  76. def find_value(cards):
  77. """It finds the total value of the cards"""
  78.  
  79. card_value = []
  80. total = 0
  81. ace = False
  82. value_dict = {'A': 11, 'K': 10, 'Q': 10, 'J': 10, '10': 10,
  83. '9': 9, '8': 8, '7': 7, '6': 6, '5': 5, '4': 4, '3': 3, '2': 2, }
  84.  
  85. #makes a corrosponding car_value list
  86. for i in range(len(cards)):
  87. card_value.append(value_dict[cards[i]])
  88. if cards[i] == 'A':
  89. ace = True
  90.  
  91. for i in range(len(card_value)):
  92. total += card_value[i]
  93.  
  94. #Ace value can be 11 or 1 depending on the situation
  95. #makes sure that the 'Ace' value is taken in player's favour
  96. if total > 21 and ace:
  97. total -= 10
  98.  
  99. return total
  100.  
  101.  
  102. #GAMEPLAY
  103.  
  104. p1 = Player()
  105. d1 = Dealer()
  106.  
  107. #Game stops only if the player wants to quit
  108. #Or if he runs out of cash
  109. while True:
  110. p1.cards = p1.pick(2)
  111. d1.cards = d1.pick(1)
  112.  
  113. dealer_won = False
  114.  
  115. print_board(p1.cards, d1.cards)
  116.  
  117. #Asks for the bet amount till the player enter a valid amount
  118. while True:
  119. try:
  120. bet = int(input("Enter the amount of money you want to bet: "))
  121. if bet > p1.money:
  122. print("You dont have sufficient funds!")
  123. print("Your account balance is: {}".format(p1.money))
  124. raise Exception
  125. break
  126. except Exception as e:
  127. print("Please enter a valid amount!")
  128.  
  129. p1.money -= bet
  130.  
  131. #Player turns continues till he passes or bursts
  132. while True:
  133.  
  134. #Asks player choice for action till a valid choice is put
  135. while True:
  136. try:
  137. choice = input("Do you want to hit or pass? [h/p]: ")
  138. if choice.lower() not in ['h', 'p']:
  139. raise Exception
  140. break
  141. except Exception as e:
  142. print("Oops! Please enter a valid choice")
  143.  
  144. if choice.lower() == 'h':
  145. p1.cards += p1.pick(1)
  146. print_board(p1.cards, d1.cards)
  147. else:
  148. break
  149.  
  150. if find_value(p1.cards) > 21:
  151. p1.burst = True
  152. dealer_won = True
  153. break
  154.  
  155. #Dealer only plays if the player is not bursted yet
  156. if not dealer_won:
  157. while True:
  158. d1.cards += d1.pick(1)
  159. if find_value(d1.cards) > 21:
  160. d1.burst = True
  161. break
  162.  
  163. if find_value(d1.cards) > find_value(p1.cards):
  164. dealer_won = True
  165. break
  166.  
  167. print("n" *50)
  168. print_board(p1.cards, d1.cards)
  169.  
  170. #Winner determination and result printing
  171. if dealer_won:
  172. print("_"*50)
  173. print("Sorry you lost the game and the money.")
  174. if p1.burst:
  175. print("Your cards value exceeded 21. Be careful next time!")
  176. print("_"*50)
  177. else:
  178. print("Dealer got very lucky! Better luck next time! :)")
  179. print("_"*50)
  180. else:
  181. p1.money += 3*bet
  182. print("_"*67)
  183. print("Bingo! You won the game! Twice the bet is credited to your account.")
  184. if d1.burst:
  185. print("Dealer's total card value exceeded 21. You got lucky, well played!")
  186. print("_"*67)
  187.  
  188. print("Your account balance is: {}".format(p1.money))
  189.  
  190. #Asks if the player wants to play again
  191. while True:
  192. try:
  193. play_again = input("Do you want to play again? [y/n]: ")
  194. if play_again.lower() not in ['y', 'n']:
  195. raise Exception
  196. break
  197. except Exception as e:
  198. print("Oops! Please enter a valid choice")
  199.  
  200. if play_again == 'n':
  201. break
  202. elif p1.money == 0:
  203. print("You did not have sufficient to continue playing!")
  204. break
  205.  
  206. if find_value(d1.cards) > find_value(p1.cards):
  207. dealer_won = True
  208.  
  209. class BadInputException(Exception):
  210. pass
  211.  
  212. while True:
  213. try:
  214. choice = input("Do you want to hit or pass? [h/p]: ")
  215. if choice.lower() not in ['h', 'p']:
  216. raise BadInputException
  217. break
  218. except BadInputException:
  219. print("Oops! Please enter a valid choice")
  220.  
  221. while True:
  222. play_game()
  223. if not play_again():
  224. break
  225.  
  226. p1 = Player()
  227. d1 = Dealer()
Add Comment
Please, Sign In to add comment