Advertisement
Alekal

Untitled

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