Advertisement
Guest User

Python Udemy Milestone Project 2 Code

a guest
Oct 7th, 2019
620
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.98 KB | None | 0 0
  1. # IMPORT STATEMENTS AND VARIABLE DECLARATIONS:
  2.  
  3. import random
  4.  
  5. suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
  6. ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
  7. values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8,
  8.             'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11}
  9.  
  10. playing = True
  11.  
  12. # CLASS DEFINTIONS:
  13.  
  14. class Card:
  15.    
  16.     def __init__(self,suit,rank):
  17.         self.suit = suit
  18.         self.rank = rank
  19.        
  20.     def __str__(self):
  21.         return self.rank + ' of ' + self.suit
  22.    
  23.  
  24. class Deck:
  25.    
  26.     def __init__(self):
  27.         self.deck = []  # start with an empty list
  28.         for suit in suits:
  29.             for rank in ranks:
  30.                 self.deck.append(Card(suit,rank))
  31.                
  32.     def __str__(self):
  33.         deck_comp = ''  # start with an empty string
  34.         for card in self.deck:
  35.             deck_comp += '\n '+card.__str__() # add each Card object's print string
  36.         return 'The deck has:' + deck_comp
  37.                
  38.     def shuffle(self):
  39.         random.shuffle(self.deck)
  40.        
  41.     def deal(self):
  42.         single_card = self.deck.pop()
  43.         return single_card
  44.    
  45.  
  46. class Hand:
  47.    
  48.     def __init__(self):
  49.         self.cards = []  # start with an empty list as we did in the Deck class
  50.         self.value = 0   # start with zero value
  51.         self.aces = 0    # add an attribute to keep track of aces
  52.    
  53.     def add_card(self,card):
  54.         self.cards.append(card)
  55.         self.value += values[card.rank]
  56.         if card.rank == 'Ace':
  57.             self.aces += 1  # add to self.aces
  58.    
  59.     def adjust_for_ace(self):
  60.         while self.value > 21 and self.aces:
  61.             self.value -= 10
  62.             self.aces -= 1
  63.            
  64.  
  65. class Chips:
  66.    
  67.     def __init__(self):
  68.         self.total = 100
  69.         self.bet = 0
  70.        
  71.     def win_bet(self):
  72.         self.total += self.bet
  73.    
  74.     def lose_bet(self):
  75.         self.total -= self.bet
  76.        
  77.  
  78. # FUNCTION DEFINITIONS:
  79.  
  80. def take_bet(chips):
  81.  
  82.     while True:
  83.         try:
  84.             chips.bet = int(input('How many chips would you like to bet? '))
  85.         except ValueError:
  86.             print('Sorry, a bet must be an integer!')
  87.         else:
  88.             if chips.bet > chips.total:
  89.                 print("Sorry, your bet can't exceed",chips.total)
  90.             else:
  91.                 break
  92.  
  93. def hit(deck,hand):
  94.     hand.add_card(deck.deal())
  95.     hand.adjust_for_ace()
  96.    
  97. def hit_or_stand(deck,hand):
  98.     global playing
  99.    
  100.     while True:
  101.         x = input("Would you like to Hit or Stand? Enter 'h' or 's' ")
  102.        
  103.         if x[0].lower() == 'h':
  104.             hit(deck,hand)  # hit() function defined above
  105.  
  106.         elif x[0].lower() == 's':
  107.             print("Player stands. Dealer is playing.")
  108.             playing = False
  109.  
  110.         else:
  111.             print("Sorry, please try again.")
  112.             continue
  113.         break
  114.  
  115.    
  116. def show_some(player,dealer):
  117.     print("\nDealer's Hand:")
  118.     print(" <card hidden>")
  119.     print('',dealer.cards[1])  
  120.     print("\nPlayer's Hand:", *player.cards, sep='\n ')
  121.    
  122. def show_all(player,dealer):
  123.     print("\nDealer's Hand:", *dealer.cards, sep='\n ')
  124.     print("Dealer's Hand =",dealer.value)
  125.     print("\nPlayer's Hand:", *player.cards, sep='\n ')
  126.     print("Player's Hand =",player.value)
  127.    
  128. def player_busts(player,dealer,chips):
  129.     print("Player busts!")
  130.     chips.lose_bet()
  131.  
  132. def player_wins(player,dealer,chips):
  133.     print("Player wins!")
  134.     chips.win_bet()
  135.  
  136. def dealer_busts(player,dealer,chips):
  137.     print("Dealer busts!")
  138.     chips.win_bet()
  139.    
  140. def dealer_wins(player,dealer,chips):
  141.     print("Dealer wins!")
  142.     chips.lose_bet()
  143.    
  144. def push(player,dealer):
  145.     print("Dealer and Player tie! It's a push.")
  146.    
  147. # GAMEPLAY!
  148.  
  149. while True:
  150.     print('Welcome to BlackJack! Get as close to 21 as you can without going over!\n\
  151.    Dealer hits until she reaches 17. Aces count as 1 or 11.')
  152.    
  153.     # Create & shuffle the deck, deal two cards to each player
  154.     deck = Deck()
  155.     deck.shuffle()
  156.    
  157.     player_hand = Hand()
  158.     player_hand.add_card(deck.deal())
  159.     player_hand.add_card(deck.deal())
  160.    
  161.     dealer_hand = Hand()
  162.     dealer_hand.add_card(deck.deal())
  163.     dealer_hand.add_card(deck.deal())
  164.    
  165.     # Set up the Player's chips
  166.     player_chips = Chips()  # remember the default value is 100
  167.    
  168.     # Prompt the Player for their bet:
  169.     take_bet(player_chips)
  170.    
  171.     # Show the cards:
  172.     show_some(player_hand,dealer_hand)
  173.    
  174.     while playing:  # recall this variable from our hit_or_stand function
  175.        
  176.         # Prompt for Player to Hit or Stand
  177.         hit_or_stand(deck,player_hand)
  178.         show_some(player_hand,dealer_hand)
  179.        
  180.         if player_hand.value > 21:
  181.             player_busts(player_hand,dealer_hand,player_chips)
  182.             break
  183.    
  184.     # If Player hasn't busted, play Dealer's hand        
  185.     if player_hand.value <= 21:
  186.        
  187.         while dealer_hand.value < 17:
  188.             hit(deck,dealer_hand)
  189.            
  190.         # Show all cards
  191.         show_all(player_hand,dealer_hand)
  192.        
  193.         # Test different winning scenarios
  194.         if dealer_hand.value > 21:
  195.             dealer_busts(player_hand,dealer_hand,player_chips)
  196.  
  197.         elif dealer_hand.value > player_hand.value:
  198.             dealer_wins(player_hand,dealer_hand,player_chips)
  199.  
  200.         elif dealer_hand.value < player_hand.value:
  201.             player_wins(player_hand,dealer_hand,player_chips)
  202.  
  203.         else:
  204.             push(player_hand,dealer_hand)
  205.  
  206.     # Inform Player of their chips total    
  207.     print("\nPlayer's winnings stand at",player_chips.total)
  208.    
  209.     # Ask to play again
  210.     new_game = input("Would you like to play another hand? Enter 'y' or 'n' ")
  211.     if new_game[0].lower()=='y':
  212.         playing=True
  213.         continue
  214.     else:
  215.         print("Thanks for playing!")
  216.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement