Advertisement
Guest User

Untitled

a guest
May 20th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.07 KB | None | 0 0
  1. """
  2.    Black Jack Game
  3. """
  4.  
  5. import random
  6.  
  7.  
  8. CHECK = 21
  9. BREAKER = "--------------------------------------"
  10.  
  11.  
  12. def create_deck(shuffle=True):
  13.     """
  14.    Creates a deck
  15.    :param shuffle: True or False to shuffle
  16.    :type shuffle: bool
  17.    :return: deck of cards
  18.    """
  19.     cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
  20.     faces = ['♣', '♥', '♠', '♦']
  21.     deck = [face + card for face in faces for card in cards]
  22.  
  23.     if shuffle:
  24.         random.shuffle(deck)
  25.     return deck
  26.  
  27.  
  28. class Player:
  29.     """
  30.    Create a PLAYER object
  31.    """
  32.  
  33.     def __init__(self, name, deck):
  34.         """
  35.        Create a PLAYER with a name
  36.        :type name: str
  37.        """
  38.         # Deck.__init__(self)
  39.         self.name = name
  40.         self.chips = 100
  41.         self.cards = []
  42.         self.amountbet = 0
  43.         self.a_value = 11
  44.         self.betstate = False
  45.         self.deck = deck
  46.  
  47.     def bet(self, amount):
  48.         """
  49.        :param amount: Amount of chips to bet
  50.        :type amount: int
  51.        """
  52.         self.amountbet = amount
  53.         if self.chips >= amount:
  54.             self.chips -= amount
  55.             print(
  56.                 f"{self.name} has successfully placed a bet of {amount} chips"
  57.             )
  58.             print(f"Chip balance: {self.chips}")
  59.             self.betstate = True
  60.         else:
  61.             print(f"{self.name} has insufficient amount of chips!")
  62.             print(f"Your balance: {self.chips}")
  63.             print(f"Bet amount: {amount}")
  64.             self.betstate = False
  65.  
  66.     def show(self, hidden=False):
  67.         """
  68.        :param hidden: True if you want to hide player's first card
  69.        :type hidden: bool
  70.        """
  71.         if self.name == "DEALER":
  72.             if hidden:
  73.                 cardl = self.cards.copy()
  74.                 cardl[0] = ""
  75.                 multi_line_print(cardl, hidden=True)
  76.             else:
  77.                 multi_line_print(self.cards)
  78.         else:
  79.             print(BREAKER)
  80.             print("Player's Cards: ")
  81.             multi_line_print(self.cards)
  82.  
  83.     def add_cards(self, number_of_cards=1):
  84.         """
  85.        PLAYER hits and asks for a card
  86.        :param number_of_cards: number of cards to add to player's hand
  87.        :type number_of_cards: int
  88.        """
  89.         # noinspection PyUnusedLocal
  90.         self.cards += [random.choice(self.deck) for i in range(number_of_cards)]
  91.         for card in self.cards:
  92.             if card in self.deck:
  93.                 self.deck.remove(card)
  94.  
  95.     def won(self):
  96.         """
  97.        doubles the amount of chips that player bet
  98.        won state to true
  99.        :return: nothing
  100.        """
  101.         self.chips += self.amountbet * 2
  102.  
  103.     @property
  104.     def sumofcards(self):
  105.         """
  106.        calculates sum of cards
  107.        :return: sum of cards
  108.        """
  109.         sum_cards = 0
  110.         for i in self.cards:
  111.             card_value = list(i)[1]
  112.             if card_value in ["J", "Q", "K", "1"]:
  113.                 card_value = 10
  114.             elif card_value == "A":
  115.                 card_value = self.a_value
  116.             sum_cards += int(card_value)
  117.         return sum_cards
  118.  
  119.     def __len__(self):
  120.         return len(self.cards)
  121.  
  122.     def reset(self):
  123.         """
  124.        reset
  125.            cards
  126.            betstate
  127.            bet amount
  128.        :return: nothing
  129.        """
  130.         self.cards = []
  131.         self.betstate = False
  132.         self.amountbet = 0
  133.  
  134.     def buy_chips(self, cash_to_chips):
  135.         """
  136.  
  137.        :param cash_to_chips: cash amount to chips
  138.        :return: nothing
  139.        """
  140.         self.chips += cash_to_chips * 2
  141.  
  142.     def a_value_change(self):
  143.         """
  144.        Changes the A card value if needed
  145.        :return: bool if value was changed or not
  146.        """
  147.         for i in self.cards:
  148.             card_value = list(i)[1]
  149.             if card_value == "A":
  150.                 self.a_value = 1
  151.         return self.a_value == 1
  152.  
  153.  
  154. def multi_line_print(list_to, hidden=False):
  155.     """
  156.    :param list_to: list of PLAYER's cards
  157.    :param hidden: True or False if PLAYER's first card is hidden
  158.    :type list_to: list
  159.    :type hidden: bool
  160.    """
  161.     cards = []
  162.     for i, card_to_print in enumerate(list_to):
  163.         if hidden and i == 0:
  164.             cards += [f"""
  165.                ----------
  166.                |  .••.  |
  167.                |  .••.  |
  168.                |  .••.  |
  169.                ----------
  170.            """]
  171.         elif card_to_print in ['♣10', '♥10', '♠10', '♦10']:
  172.             cards += [f"""
  173.                ----------
  174.                |{card_to_print}     |
  175.                |        |
  176.                |     {card_to_print}|
  177.                ----------
  178.            """]
  179.         else:
  180.             cards += [f"""
  181.                ----------
  182.                |{card_to_print}      |
  183.                |        |
  184.                |      {card_to_print}|
  185.                ----------
  186.            """]
  187.     strings_by_column = [s.split('\n') for s in cards]
  188.     strings_by_line = zip(*strings_by_column)
  189.     max_length_by_column = [
  190.         max([len(s) for s in col_strings])
  191.         for col_strings in strings_by_column
  192.     ]
  193.     for parts in strings_by_line:
  194.         # Pad strings in each column so they are the same length
  195.         padded_strings = [
  196.             parts[i].ljust(max_length_by_column[i])
  197.             for i in range(len(parts))
  198.         ]
  199.         print(''.join(padded_strings))
  200.  
  201.  
  202. def won(who="PLAYER"):
  203.     """
  204.    :param who: if DEALER pass "DEALER" for DEALER's settings
  205.    :type who: str
  206.    """
  207.  
  208.     def display():
  209.         DEALER.show()
  210.         PLAYER.show()
  211.         print(f"Dealer's score: {DEALER.sumofcards}")
  212.         print(f"Player's score: {PLAYER.sumofcards}")
  213.  
  214.     if who == "PLAYER":
  215.         print(BREAKER)
  216.         PLAYER.won()
  217.         print(f"Congratulations! {PLAYER.name}")
  218.         print(f"You have gained {PLAYER.amountbet * 2} chips")
  219.         print("Dealer's Cards: ")
  220.         display()
  221.     elif who == "tie":
  222.         print(BREAKER)
  223.         print(f"Tie!")
  224.         print("Dealer's Cards: ")
  225.         display()
  226.     else:
  227.         print(BREAKER)
  228.         print(f"Dealer won!")
  229.         print("Dealer's Cards: ")
  230.         display()
  231.  
  232.  
  233. print("Welcome to BlackJack")
  234. print("Please enter the following information")
  235. print(BREAKER)
  236. DECK = create_deck()
  237. NAME = input("Name: ")
  238. print(f"Thank you for playing and enjoy {NAME}")
  239. PLAYER = Player(NAME, DECK)
  240. DEALER = Player("DEALER", DECK)
  241.  
  242.  
  243. def player_hit_loop():
  244.     """
  245.    Player loop for hitting
  246.    :return: nothing
  247.    """
  248.     hit = input("Would you like to stand or hit? (stand/hit): ")
  249.     if PLAYER.sumofcards == CHECK:
  250.         hit = "stand"
  251.     while hit != "stand":
  252.         if hit == "hit":
  253.             PLAYER.add_cards()
  254.             PLAYER.show()
  255.         if PLAYER.sumofcards > CHECK:
  256.             change = PLAYER.a_value_change()
  257.             if change is False:
  258.                 break
  259.         if PLAYER.sumofcards == CHECK:
  260.             break
  261.         print(BREAKER)
  262.         hit = input("Would you like to stand or hit? (stand/hit): ")
  263.  
  264.  
  265. def dealer_hit_loop():
  266.     """
  267.    Dealer loop for hitting
  268.    :return: nothing
  269.    """
  270.     hitbycomp = True
  271.     if DEALER.sumofcards >= 17:
  272.         hitbycomp = False
  273.     elif DEALER.sumofcards > CHECK:
  274.         DEALER.a_value_change()
  275.         hitbycomp = False
  276.     elif DEALER.sumofcards == CHECK:
  277.         hitbycomp = False
  278.  
  279.     while hitbycomp:
  280.         print("Dealer Hits")
  281.         DEALER.add_cards()
  282.         print(BREAKER)
  283.         print("Dealer's Cards: ")
  284.         DEALER.show(hidden=True)
  285.  
  286.         if DEALER.sumofcards == CHECK:
  287.             break
  288.         elif DEALER.sumofcards > CHECK:
  289.             change = DEALER.a_value_change()
  290.             if change is False:
  291.                 break
  292.         if DEALER.sumofcards >= 17:
  293.             break
  294.  
  295.  
  296. def main():
  297.     """
  298.    game setup loop
  299.    :return: nothing
  300.    """
  301.     run = True
  302.     while run:
  303.         print(BREAKER)
  304.         print("Chips Counter: ")
  305.         print(f"{PLAYER.name} has {PLAYER.chips} chip\\s")
  306.         print(BREAKER)
  307.         bet = int(input("Bet(Amount of chips): "))
  308.         PLAYER.bet(bet)
  309.         if PLAYER.betstate is False:
  310.             print(BREAKER)
  311.             buy_chips = input("Would you like to buy chips? (yes/no) ")
  312.             if buy_chips == "yes":
  313.                 print("To play:")
  314.                 print(
  315.                     f"\tconvert ${int((bet - PLAYER.chips) / 2)}"
  316.                 )
  317.                 print(BREAKER)
  318.                 cash_amount = int(input("Cash to Chips converter ($1 - 2 chips): $"))
  319.                 PLAYER.buy_chips(cash_amount)
  320.                 print(f"{PLAYER.name} now has {PLAYER.chips} chip\\s")
  321.                 if PLAYER.chips >= PLAYER.amountbet:
  322.                     PLAYER.bet(bet)
  323.                 else:
  324.                     PLAYER.amountbet = 0
  325.                     break
  326.             else:
  327.                 PLAYER.amountbet = 0
  328.                 break
  329.  
  330.         PLAYER.add_cards(2)
  331.         DEALER.add_cards(2)
  332.         game()
  333.         PLAYER.reset()
  334.         DEALER.reset()
  335.         run = False
  336.  
  337.     print(BREAKER)
  338.     play_again = input("Would you like to continue playing? (yes/no): ")
  339.     if play_again == "yes":
  340.         main()
  341.  
  342.  
  343. def game():
  344.     """
  345.    game loop
  346.    :return: nothin
  347.    """
  348.     PLAYER.show()
  349.     print(BREAKER)
  350.     print("Dealer's Cards: ")
  351.     DEALER.show(hidden=True)
  352.     print(BREAKER)
  353.     player_hit_loop()
  354.     dealer_hit_loop()
  355.  
  356.     player_cs = PLAYER.sumofcards
  357.     dealer_cs = DEALER.sumofcards
  358.     if dealer_cs == player_cs or DEALER.sumofcards > CHECK and PLAYER.sumofcards > CHECK:
  359.         won("tie")
  360.     elif player_cs == CHECK:
  361.         won()
  362.     elif dealer_cs == CHECK:
  363.         won("DEALER")
  364.     elif player_cs < dealer_cs <= CHECK:
  365.         won("DEALER")
  366.     elif dealer_cs > player_cs <= CHECK:
  367.         won()
  368.     else:
  369.         won()
  370.  
  371.  
  372. if __name__ == "__main__":
  373.     main()
  374.  
  375. print(BREAKER)
  376. print(f"Thank you for playing {PLAYER.name}!")
  377. print("Black Jack")
  378. print("--------------By JakeAus--------------")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement