Python学习Milestone2

Milestone Project 2 - Blackjack Game

In this milestone project you will be creating a Complete BlackJack Card Game in Python.

Here are the requirements:

  • You need to create a simple text-based BlackJack game
  • The game needs to have one player versus an automated dealer.
  • The player can stand or hit.
  • The player must be able to pick their betting amount.
  • You need to keep track of the player's total money.
  • You need to alert the player of wins, losses, or busts, etc...

And most importantly:

  • You must use OOP and classes in some portion of your game. You can not just use functions in your game. Use classes to help you define the Deck and the Player's hand. There are many right ways to do this, so explore it well!

Feel free to expand this game. Try including multiple players. Try adding in Double-Down and card splits! Remember to you are free to use any resources you want and as always:

HAVE FUN!

'''
You need to create a simple text-based [BlackJack](https://en.wikipedia.org/wiki/Blackjack) game
The game needs to have one player versus an automated dealer.
The player can stand or hit.
The player must be able to pick their betting amount.
You need to keep track of the player's total money.
You need to alert the player of wins, losses, or busts, etc...

Ways of ending the game:
1. Player has cards over 21, then bust and lose. dealer hasn't go yet. 
2. Human stays, dealer hits and have sum closer to 21, dealer wins
3. Dealer keeps hitting, bust and lose. Double winner's money
10,J,K,Q = 10
A = 1 or 11
'''
import random

suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
             'Queen':10, 'King':10, 'Ace':11}

playing = True



class Card:
    
    def __init__(self,suit,rank):
        self.suit = suit
        self.rank = rank
    
    def __str__(self):
        return f'{self.rank} of {self.suit}'


class Deck:

    def __init__(self):
        self.deck = []  # start with an empty list
        for suit in suits:
            for rank in ranks:
                self.deck.append(Card(suit,rank))
    
    def __str__(self):
        s = ''
        for card in self.deck:
            s += str(card) + '\n'
        return "The deck has: " + s
            
    def shuffle(self):
        random.shuffle(self.deck)
        
    def deal(self):
        single_card = self.deck.pop()
        return single_card

class Hand:
    def __init__(self):
        self.cards = []  
        self.value = 0   
        self.aces = 0   
    
    def add_card(self,card):
        self.cards.append(card)
        self.value += values[card.rank]

        if card.rank == 'Ace':
            self.aces += 1
    
    def adjust_for_ace(self):
         while self.value > 21 and self.aces:
            self.value -= 10
            self.aces -= 1


class Chips:
    
    def __init__(self):
        self.total = 100  
        self.bet = 0
        
    def win_bet(self):
        self.total += self.bet
    
    def lose_bet(self):
        self.total -= self.bet


def take_bet(chips):
    while True:
        try:
            chips.bet = int(input("How much would you like to bet? "))
            if chips.bet <= chips.total:
                break
            else:
                print("There's no enough chips, please enter a bet that is smaller than: {} ".format(chips.total))
                continue
        except:
            print("Please enter an invalid integer: ")
            continue
    return chips.bet


#Either player can take hits until they bust. 
#This function will be called during gameplay anytime a Player requests a hit, 
#or a Dealer's hand is less than 17. It should take in Deck and Hand objects as arguments, 
#and deal one card off the deck and add it to the Hand. 
#You may want it to check for aces in the event that a player's hand exceeds 21.

def hit(deck,hand):
    hand.add_card(deck.deal())
    hand.adjust_for_ace()


def hit_or_stand(deck,hand):
    global playing  # to control an upcoming while loop
    while True:
        x = input("Hit or Stand? Enter h or s ")
        if x[0].lower() == 'h':
            hit(deck,hand)
        elif x[0].lower() == 's':
            print("Player stands dealer's turn\n")
            playing = False
        else:
            print("Sorry I don't understand that, please enter h or s: ")
            continue
        break


def show_some(player,dealer):
    print("Player's hand:\n")
    for card in player.cards:
        print(card)
    print('\n')
    print("Dealer's hand:")   
    print("One card is hidden:\n")  
    for i in range(1,len(dealer.cards)):
        print(dealer.cards[i])
    
def show_all(player,dealer):
    print("Player's hand:\n")
    for card in player.cards:
        print(card)
    print('\n')
    print("Dealer's hand:\n")
    for card in dealer.cards:
        print(card)

def player_busts(player_chip,dealer_chip):
    print('Player has busted!')
    player_chip.lose_bet()
    dealer_chip.win_bet()
    
def player_wins(player_chip,dealer_chip):
    print('Player has won!')
    player_chip.win_bet()
    dealer_chip.lose_bet()

def dealer_busts(player_chip,dealer_chip):
    print("Dealer has busted!")
    player_chip.win_bet()
    dealer_chip.lose_bet()

def dealer_wins(player_chip,dealer_chip):
    print("Dealer has won!")
    player_chip.lose_bet()
    dealer_chip.win_bet()
    
def push():
    print("Dealer and Player tie! It's a push.")

def continue_play():
    continue_play = input("Do you want to play again? ")
    if continue_play[0].lower() == 'y':
        playing = True
        game_run()
    # break
    else:
        print("Thanks for playing!")   
        

def check_for_21(player_hand,dealer_hand):
    if player_hand.value == 21:
        player_wins(player_chip,dealer_chip)
        continue_play()
    elif dealer_hand.value == 21:
        dealer_wins(player_chip,dealer_chip)
        continue_play()


def game_run():
    print("Welcome to play the BlackJack game!")
    deck = Deck()
    deck.shuffle()
    player_hand = Hand()
    dealer_hand = Hand()
    player_hand.add_card(deck.deal())
    player_hand.add_card(deck.deal())
    dealer_hand.add_card(deck.deal())
    dealer_hand.add_card(deck.deal())
    
    player_chip = Chips()
    dealer_chip = Chips()
    
    player_bet = take_bet(player_chip)
    dealer_bet = player_bet
    show_some(player_hand,dealer_hand)
    check_for_21(player_hand,dealer_hand)


    while playing:  
        hit_or_stand(deck,player_hand)
        print('\n')
        show_some(player_hand,dealer_hand)
        check_for_21(player_hand,dealer_hand)
        if player_hand.value > 21:
            player_busts(player_chip,dealer_chip)
            break

    if player_hand.value <= 21:
        while dealer_hand.value < 17:
            hit(deck,dealer_hand)
            check_for_21(player_hand,dealer_hand)
        show_all(player_hand,dealer_hand)
    
    # Run different winning scenarios
    # 1. Player has cards over 21, then bust and lose. dealer hasn't go yet. 
    # 2. Human stays, dealer hits and have sum closer to 21, dealer wins
    # 3. Dealer keeps hitting, bust and lose. Double winner's money
        if dealer_hand.value > 21:
            dealer_busts(player_chip,dealer_chip)
        elif dealer_hand.value < player_hand.value:
            player_wins(player_chip,dealer_chip)
        elif dealer_hand.value > player_hand.value:
            dealer_wins(player_chip,dealer_chip)
        else:
            push()
    
    print(f'The total chips for Player is {player_chip.total}')
    print(f'The total chips for Dealer is {dealer_chip.total}')
    continue_play()

if __name__ == '__main__':
    game_run()
        

    







你可能感兴趣的:(Python学习Milestone2)