SHARE
TWEET

Untitled

a guest Dec 3rd, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """Blackjack game."""
  2. import requests
  3.  
  4.  
  5. class Card:
  6.     """Class for card."""
  7.  
  8.     def __init__(self, value: str, suit: str, code: str):
  9.         """
  10.         Konstruktor teeb kaardi objekti, võttes sisendparameetriteks kaardi väärtuse, masti ja koodi.
  11.  
  12.         Väärtused peab salvestama sama nimega isendiväljadele (card, suit, code).
  13.  
  14.         values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'JACK', 'QUEEN', 'KING', 'ACE']
  15.  
  16.         suits = ['SPADES', 'DIAMONDS', 'HEARTS', 'CLUBS']
  17.  
  18.         codes = {'AS', '2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S', '0S', 'JS', 'QS', 'KS',
  19.         'AD', '2D', '3D', '4D', '5D', '6D', '7D', '8D', '9D', '0D', 'JD', 'QD', 'KD',
  20.         'AC', '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', '0C', 'JC', 'QC', 'KC',
  21.         'AH', '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H', '0H', 'JH', 'QH', 'KH'}.
  22.         """
  23.         print("aaaa")
  24.         values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'JACK', 'QUEEN', 'KING', 'ACE']
  25.  
  26.         suits = ['SPADES', 'DIAMONDS', 'HEARTS', 'CLUBS']
  27.  
  28.         codes = {'AS', '2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S', '0S', 'JS', 'QS', 'KS',
  29.                  'AD', '2D', '3D', '4D', '5D', '6D', '7D', '8D', '9D', '0D', 'JD', 'QD', 'KD',
  30.                  'AC', '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', '0C', 'JC', 'QC', 'KC',
  31.                  'AH', '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H', '0H', 'JH', 'QH', 'KH'}
  32.         self.top_down = False
  33.         if value in values:
  34.             self.value = value
  35.         if suit in suits:
  36.             self.suit = suit
  37.         if code in codes:
  38.             self.code = code
  39.         print(self.value, self.suit)
  40.  
  41.     def __str__(self):
  42.         """Prindib kaardi koodi juhul, kui top_down == False, vastasel juhul prindib ??."""
  43.         return self.code if self.top_down is False else "??"
  44.  
  45.     def __repr__(self) -> str:
  46.         """Tagastab code-väljal oleva väärtuse."""
  47.         return self.code
  48.  
  49.     def __eq__(self, other) -> bool:
  50.         """
  51.         Võrdleb Card objekti teise objektiga. Tagastab True, kui teine object on Card tüüpi.
  52.  
  53.         ja sama masti ning väärtusega.
  54.         """
  55.         return isinstance(other, Card) and self.suit == other.suit and self.value == other.value
  56.  
  57.  
  58. class Deck:
  59.     """Class for deck."""
  60.  
  61.     DECK_BASE_API = "https://deckofcardsapi.com/api/deck/"
  62.  
  63.     def __init__(self, deck_count: int = 1, shuffle: bool = False):
  64.         """
  65.         Konstruktor teeb Deck objekti. Saab sisendiks pakkide arvu (mitu 52 kaardist pakki on) ja boolean muutuja.
  66.  
  67.         mis määrab, kas kaardipakid peavad olema segatud või ei. Salvestada tuleb deck_count ning ka shuffeled
  68.         väärtused. Viimase salvestamiseks kasutada isendimuutujat nimega is_shuffled. Lisaks peab isendimuutujas nimega
  69.         remaining hoidma kaardipakis olevate kaartide arvu (võib kasutada ka property'd) Kaardipaki genereerimiseks
  70.         kasutada
  71.  
  72.         Kuna klass peab toimima ka ilma interneti ühenduseta, siis on tuleb valmis genereerida ka n-ö tagavara
  73.         kaardipakk, mida saaks kasutada, kui api lõpetab töötamise. Tagavara kaardipakk salvestada muutujasse
  74.         _backup_deck. Seda tagavara pakki on mõistlik sünkroniseerida API-st tuleneva pakiga. Ehk siis kui API ütleb,
  75.         et järgmine kaart on S3, siis tuleks see ka tagavara pakist eemaldada jne.
  76.         """
  77.         try:
  78.             self.deck_count = deck_count
  79.             self.is_shuffled = shuffle
  80.             self._backup_deck = Deck._generate_backup_pile(self.deck_count)
  81.             self.remaining = 52 * self.deck_count
  82.             if self.is_shuffled:
  83.                 self.result = self._request(f"new/shuffle/?deck_count={self.deck_count}")
  84.             else:
  85.                 self.result = self._request(f"new/?deck_count={self.deck_count}")
  86.             self.top_down = False
  87.             if self.is_shuffled is True:
  88.                 self.shuffle()
  89.             if self.result is None or ('success' in self.result and self.result['success'] is True):
  90.                 pass
  91.             if self.result and "deck_id" in self.result:
  92.                 self.remaining = self.result["remaining"]
  93.                 self.is_shuffled = self.result['shuffled']
  94.                 self.deck_id = self.result['deck_id']
  95.             else:
  96.                 self.remaining = len(self._backup_deck)
  97.                 self.is_shuffled = False
  98.                 self.deck_id = None
  99.         except AttributeError:
  100.             pass
  101.  
  102.     def shuffle(self) -> None:
  103.         """Segab kaardipaki, kasutada https://deckofcardsapi.com/api/deck/<deck_id>/shuffle/."""
  104.         try:
  105.             result = self._request(f"{self.deck_id}/shuffle/")
  106.             if result is None or ('success' in result and result['success'] is True):
  107.                 pass
  108.         except AttributeError:
  109.             pass
  110.  
  111.     def draw_card(self, top_down: bool = False):  # -> Optional[Card]
  112.         """
  113.         Draw card from the deck.
  114.  
  115.         :return: card instance.
  116.         """
  117.         try:
  118.             result = []
  119.             if self.remaining == 0:
  120.                 return None
  121.             if self.deck_id is not None:
  122.                 result = self._request(str(self.deck_id) + "/draw/?count=1")
  123.             if result and result["success"]:
  124.                 card = result['cards'][0]
  125.                 new_card = Card(card['value'], card['suit'], card['code'])
  126.                 self._backup_deck.remove(new_card)
  127.                 self.remaining -= 1
  128.                 new_card.top_down = top_down
  129.                 return new_card
  130.             else:
  131.                 new_card = self._backup_deck.pop(0)
  132.                 self.remaining -= 1
  133.                 new_card.top_down = top_down
  134.                 return new_card
  135.         except AttributeError:
  136.             return None
  137.  
  138.     def _request(self, url: str) -> dict:
  139.         """
  140.         Update deck.
  141.  
  142.         :param url:
  143.         :return:
  144.         """
  145.         try:
  146.             url = Deck.DECK_BASE_API + url
  147.             try:
  148.                 response = requests.get(url)
  149.             except requests.exceptions.RequestException:
  150.                 response = None
  151.             if response is None:
  152.                 pass
  153.             if response is not None and response.status_code == requests.codes.ok:
  154.                 thing = response.json()
  155.                 return thing
  156.             else:
  157.                 pass
  158.         except AttributeError:
  159.             pass
  160.  
  161.     @staticmethod
  162.     def _generate_backup_pile(deck_count=1):  # -> List[Card]:
  163.         """Generate backup pile."""
  164.         card_list = []
  165.         cards = ['2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S', '10S', 'JACKS', 'QUEENS', 'KINGS', 'ACES',
  166.                  '2D', '3D', '4D', '5D', '6D', '7D', '8D', '9D', '10D', 'JACKD', 'QUEEND', 'KINGD', 'ACED',
  167.                  '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', '10C', 'JACKC', 'QUEENC', 'KINGC', 'ACEC',
  168.                  '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H', '10H', 'JACKH', 'QUEENH', 'KINGH', 'ACEH']
  169.         codes = ['2S', '3S', '4S', '5S', '6S', '7S', '8S', '9S', '0S', 'JS', 'QS', 'KS', 'AS',
  170.                  '2D', '3D', '4D', '5D', '6D', '7D', '8D', '9D', '0D', 'JD', 'QD', 'KD', 'AD',
  171.                  '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C', '0C', 'JC', 'QC', 'KC', 'AC',
  172.                  '2H', '3H', '4H', '5H', '6H', '7H', '8H', '9H', '0H', 'JH', 'QH', 'KH', 'AH']
  173.         for c in range(len(cards)):
  174.             if cards[c][-1] == "S":
  175.                 card_list.append(Card(cards[c][:-1], 'SPADES', codes[c]))
  176.             elif cards[c][-1] == "D":
  177.                 card_list.append(Card(cards[c][:-1], 'DIAMONDS', codes[c]))
  178.             elif cards[c][-1] == "C":
  179.                 card_list.append(Card(cards[c][:-1], 'HEARTS', codes[c]))
  180.             elif cards[c][-1] == "H":
  181.                 card_list.append(Card(cards[c][:-1], 'CLUBS', codes[c]))
  182.         return card_list * deck_count
  183.  
  184.  
  185. if __name__ == '__main__':
  186.     d = Deck(shuffle=True)
  187.     print(d.remaining)  # 52
  188.     card1 = d.draw_card()  # Random card
  189.     print(d.draw_card())
  190.     print(card1 in d._backup_deck)  # False
  191.     print(d._backup_deck)  # 51 shuffled cards
  192.     d2 = Deck(deck_count=2)
  193.     print(d2._backup_deck)  # 104 ordered cards (deck after deck)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top