Advertisement
Alekal

Untitled

Dec 4th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.74 KB | None | 0 0
  1. """Simple game of blackjack."""
  2. from textwrap import dedent
  3.  
  4. import requests
  5.  
  6.  
  7. class Card:
  8. """Simple dataclass for holding card information."""
  9. def __init__(self, value: str, suit: str, code: str):
  10. """
  11. Unit.
  12.  
  13. :param value:
  14. :param suit:
  15. :param code:
  16. """
  17.  
  18. self.value = value
  19. self.suit = suit
  20. self.code = code
  21.  
  22. def __repr__(self) -> str:
  23. """
  24. Repr.
  25.  
  26. :return:
  27. """
  28. return self.code
  29.  
  30.  
  31. class Hand:
  32. """Simple class for holding hand information."""
  33. def __init__(self):
  34. self.score = 0
  35. self.cards = []
  36. self.aces_counter = 0
  37.  
  38. def add_card(self, card: Card):
  39. self.score = 0
  40. self.cards.append(card)
  41. for card in self.cards:
  42. if card.value == "ACE":
  43. if self.score > 21:
  44. self.score -= 10
  45. else:
  46. self.score += 11
  47. self.aces_counter += 1
  48. elif len(card.value) < 3:
  49. self.score += int(card.value)
  50. elif card.value == "JACK":
  51. self.score += 10
  52. elif card.value == "QUEEN":
  53. self.score += 10
  54. elif card.value == "KING":
  55. self.score += 10
  56.  
  57.  
  58. # def add_card(self, card: Card):
  59. # """Funktsioon, millega saab listile cards lisada lõppu uue kaardi."""
  60. # self.score = 0
  61. # self.cards.append(card)
  62. # for card in self.cards:
  63. # if self.score < 21:
  64. # if card.value == "JACK":
  65. # self.score += 10
  66. # elif card.value == "QUEEN":
  67. # self.score += 10
  68. # elif card.value == "KING":
  69. # self.score += 10
  70. # elif card.value == "ACE":
  71. # self.score += 11
  72. # elif 0 < len(card.value) <= 2:
  73. # self.score += int(card.value)
  74. # elif self.score > 21:
  75. # if 'ACE' in self.cards:
  76. # self.score -= 10
  77.  
  78. # if self.score < 21:
  79. # if card.value in ['JACK', 'QUEEN', 'KING']:
  80. # self.score += 10
  81. # self.cards.append(card.value)
  82. # elif card.value is 'ACE':
  83. # self.score += 11
  84. # self.cards.append(card.value)
  85. # elif card.value in ['2', '3', '4', '5', '6', '7', '8', '9', '10']:
  86. # self.score += int(card.value)
  87. # self.cards.append(card.value)
  88. # elif self.score > 21:
  89. # if card.value is 'ACE':
  90. # self.score -= 10
  91.  
  92. class Deck:
  93.  
  94. """Deck of cards. Provided via api over the network."""
  95.  
  96. def __init__(self, shuffle=False):
  97. """
  98. Tell api to create a new deck.
  99.  
  100. :param shuffle: if shuffle option is true, make new shuffled deck.
  101. """
  102. self.is_shuffled = shuffle
  103. self.shuffle = shuffle
  104. # self.deck_id = requests.get("https://deckofcardsapi.com/api/deck/new/shuffle").json()['deck_id']
  105. if self.is_shuffled is False:
  106. shuffle = requests.get('https://deckofcardsapi.com/api/deck/new').json()
  107. elif self.is_shuffled is True:
  108. shuffle = requests.get('https://deckofcardsapi.com/api/deck/new/shuffle').json()
  109. self.deck_id = shuffle['deck_id']
  110.  
  111. def shuffle(self):
  112. """
  113. Shuffle the deck.
  114. """
  115. if self.is_shuffled is False:
  116. requests.get('https://deckofcardsapi.com/api/deck/' + self.deck_id + '/shuffle')
  117. self.shuffle = True
  118. elif self.is_shuffled is True:
  119. pass
  120.  
  121.  
  122. def draw(self) -> Card:
  123. """
  124. Draw card from the deck.
  125.  
  126. :return: card instance.
  127. """
  128. card = requests.get('https://deckofcardsapi.com/api/deck/' + self.deck_id + '/draw').json()
  129. card_as_object = Card(card['cards'][0]["value"], card['cards'][0]["suit"], card['cards'][0]["code"])
  130. return card_as_object
  131.  
  132.  
  133. class BlackjackController:
  134. """Blackjack controller. For controlling the game and data flow between view and database."""
  135.  
  136. def __init__(self, deck: Deck, view: 'BlackjackView'):
  137. """
  138. Start new blackjack game.
  139.  
  140. :param deck: deck to draw cards from.
  141. :param view: view to communicate with.
  142. """
  143. pass
  144.  
  145.  
  146. class BlackjackView:
  147. """Minimalistic UI/view for the blackjack game."""
  148.  
  149. def ask_next_move(self, state: dict) -> str:
  150. """
  151. Get next move from the player.
  152.  
  153. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object}
  154. :return: parsed command that user has choses. String "H" for hit and "S" for stand
  155. """
  156. self.display_state(state)
  157. while True:
  158. action = input("Choose your next move hit(H) or stand(S) > ")
  159. if action.upper() in ["H", "S"]:
  160. return action.upper()
  161. print("Invalid command!")
  162.  
  163. def player_lost(self, state):
  164. """
  165. Display player lost dialog to the user.
  166.  
  167. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object}
  168. """
  169. self.display_state(state, final=True)
  170. print("You lost")
  171.  
  172. def player_won(self, state):
  173. """
  174. Display player won dialog to the user.
  175.  
  176. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object}
  177. """
  178. self.display_state(state, final=True)
  179. print("You won")
  180.  
  181. def display_state(self, state, final=False):
  182. """
  183. Display state of the game for the user.
  184.  
  185. :param state: dict with given structure: {"dealer": dealer_hand_object, "player": player_hand_object}
  186. :param final: boolean if the given state is final state. True if game has been lost or won.
  187. """
  188. dealer_score = state["dealer"].score if final else "??"
  189. dealer_cards = state["dealer"].cards
  190. if not final:
  191. dealer_cards_hidden_last = [c.__repr__() for c in dealer_cards[:-1]] + ["??"]
  192. dealer_cards = f"[{','.join(dealer_cards_hidden_last)}]"
  193.  
  194. player_score = state["player"].score
  195. player_cards = state["player"].cards
  196. print(dedent(
  197. f"""
  198. {"Dealer score":<15}: {dealer_score}
  199. {"Dealer hand":<15}: {dealer_cards}
  200.  
  201. {"Your score":<15}: {player_score}
  202. {"Your hand":<15}: {player_cards}
  203. """
  204. ))
  205.  
  206.  
  207. if __name__ == '__main__':
  208. BlackjackController(Deck(), BlackjackView()) # start the game.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement