Skip to content

Instantly share code, notes, and snippets.

@beaucarnes
Created July 26, 2021 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beaucarnes/c42904ba7a7bf0e8688791f6e0e97716 to your computer and use it in GitHub Desktop.
Save beaucarnes/c42904ba7a7bf0e8688791f6e0e97716 to your computer and use it in GitHub Desktop.
python-blackjack-game.md

It's time to make the final (and longest) class that runs the game. Create a class called game. Inside that class create a method called play. Inside that method create a variable called game_number and set it to zero.


class Game:
    def play(self):
        game_number = 0

Besides keeping track of the game number we also have to keep track of the number of games_to_play. Create that variable and start it at zero.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

A program can request a user's input in the terminal with the input() function. For example, the code name = input("What's your name? "), will prompt the user with "What's your name? " and store the inputted text in a variable called name. Ask the user for input to the question "How many games do you want to play?" The result should be stored in the games_to_play variable. (Note: Keep the games_to_play = 0 line of code.)


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        games_to_play = input("How many games do you want to play? ")

Put the input function inside an int function to make sure the result is an integer.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        games_to_play = int(input("How many games do you want to play? "))

Add the following lines at the end of your program (not indented):

g = Game()
g.play()

Now you can test your program by running python blackjack.py in the terminal.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        games_to_play = int(input("How many games do you want to play? "))

g = Game()
g.play()

There will be an error if int() is called with something that is not a number. In this case, there will be an error that stops the program if a user enters something that is not a number. You can specify how to handle an exception (an error) with a "try-except" block. In this type of block, the program will try some code. If there is an error in that code, the program will run the code inside the except part of the block instead of stopping the program. Switch the last line in the play method with the following "try-except" block:

try:
    games_to_play = int(input("How many games do you want to play?: "))
except:
    print("You must enter a number.")

class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        try:
            games_to_play = int(input("How many games do you want to play?: "))
        except:
            print("You must enter a number.")

g = Game()
g.play()

Currently, the user gets one chance to input a correct value. Let's make the program keep asking the user for a value until the user enters a number. This can be done with a while loop. This type of loop keeps looping "while" something is true. Keep looping until the user enters a number by putting the entire "try-catch" block into a while loop that starts like this: while games_to_play <= 0:.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

g = Game()
g.play()

Now you will create the main game loop. This will loop one time per game played. It should loop while game_number is less than games_to_play. The first line in the loop should increment the game_number by one.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

g = Game()
g.play()

Inside that loop create a Deck object in a deck variable. Then shuffle the deck.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

g = Game()
g.play()

Create a variable called player_hand and set it to a Hand object.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()

g = Game()
g.play()

Create a variable called dealer_hand and set it to a Hand object. When creating the object, make sure to specify that dealer=True.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

g = Game()
g.play()

Create a for loop that loops 2 times. Each iteration should add a card to the player's hand that is delt from the deck and add a card to the dealer's hand that is delt from the deck.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal(1))
                dealer_hand.add_card(deck.deal(1))

g = Game()
g.play()

Information will be printed to the console for each game. Start by printing an empty line.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()

g = Game()
g.play()

Now print * 30 times to make a divder. You can do that with print("*" * 30).


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)

g = Game()
g.play()

Print the current game number out of the total number of games. For instance, if the loop is on the 4th game of 10 total games to play, it should print: "Game 4 of 10".


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")

g = Game()
g.play()

Print 30 more *.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)

g = Game()
g.play()

Display the player's hand.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()

g = Game()
g.play()

Display the dealer's hand.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

g = Game()
g.play()

At this point in the game, someone could already have won if they got a blackjack. The code should check if there is a winner. Let's put the code to check if there is a winner in a seperate method of the Game class. Create a method called check_winner. For now the method should just return False.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self):
        return False

g = Game()
g.play()

The check_winner should take player_hand and dealer_hand as arguments.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dealer_hand):
        return False

g = Game()
g.play()

Before return False, check if player_hand.get_value() > 21. If so, print "You busted. Dealer wins! 😭" and return True. Once the program gets to a return statement, none of the following statements in the block are run.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand):
        if player_hand.get_value() > 21:
            print("You busted. Dealer wins! 😭")
            return True

        return False

g = Game()
g.play()

We'll use a few elif statements to check for various other conditions. Add an elif statment to check if dealer_hand.get_value() > 21. If so, print "Dealer busted. You win! 😄" and return True.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand):
        if player_hand.get_value() > 21:
            print("You busted. Dealer wins! 😭")
            return True
        elif dealer_hand.get_value() > 21:
            print("Dealer busted. You win! 😄")
            return True

        return False

g = Game()
g.play()

Add an elif statement to check if both players have a blackjack. If so, print "Both players have blackjack! Tie! 🤨" and return True.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand):
        if player_hand.get_value() > 21:
            print("You busted. Dealer wins! 😭")
            return True
        elif dealer_hand.get_value() > 21:
            print("Dealer busted. You win! 😄")
            return True
        elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
            print("Both players have blackjack! Tie! 🤨")
            return True

        return False

g = Game()
g.play()

Add an elif statement to check if player_hand has a blackjack. If so, print "You have blackjack! You win! 😄" and return True.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand):
        if player_hand.get_value() > 21:
            print("You busted. Dealer wins! 😭")
            return True
        elif dealer_hand.get_value() > 21:
            print("Dealer busted. You win! 😄")
            return True
        elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
            print("Both players have blackjack! Tie! 🤨")
            return True
        elif player_hand.is_blackjack():
            print("You have blackjack! You win! 😄")
            return True

        return False

g = Game()
g.play()

Add an elif statement to check if dealer_hand has a blackjack. If so, print "Dealer has blackjack! Dealer wins! 😭" and return True.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand):
        if player_hand.get_value() > 21:
            print("You busted. Dealer wins! 😭")
            return True
        elif dealer_hand.get_value() > 21:
            print("Dealer busted. You win! 😄")
            return True
        elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
            print("Both players have blackjack! Tie! 🤨")
            return True
        elif player_hand.is_blackjack():
            print("You have blackjack! You win! 😄")
            return True
        elif dealer_hand.is_blackjack():
            print("Dealer has blackjack! Dealer wins! 😭")
            return True

        return False

g = Game()
g.play()

The game can also end if both players choose not to get more cards. Add this argument to the check_winner method with a default value: game_over=False.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if player_hand.get_value() > 21:
            print("You busted. Dealer wins! 😭")
            return True
        elif dealer_hand.get_value() > 21:
            print("Dealer busted. You win! 😄")
            return True
        elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
            print("Both players have blackjack! Tie! 🤨")
            return True
        elif player_hand.is_blackjack():
            print("You have blackjack! You win! 😄")
            return True
        elif dealer_hand.is_blackjack():
            print("Dealer has blackjack! Dealer wins! 😭")
            return True

        return False

g = Game()
g.play()

Use the new argument. The string of if and elif statements should only be run if not game_over. Make sure the line return False is not in the if statment.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if not game_over:
            if player_hand.get_value() > 21:
                print("You busted. Dealer wins! 😭")
                return True
            elif dealer_hand.get_value() > 21:
                print("Dealer busted. You win! 😄")
                return True
            elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
                print("Both players have blackjack! Tie! 🤨")
                return True
            elif player_hand.is_blackjack():
                print("You have blackjack! You win! 😄")
                return True
            elif dealer_hand.is_blackjack():
                print("Dealer has blackjack! Dealer wins! 😭")
                return True

        return False

g = Game()
g.play()

If game_over is True, check if the player hand's value is more than the dearler hand's value. If so, print "You win! 😄".


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if not game_over:
            if player_hand.get_value() > 21:
                print("You busted. Dealer wins! 😭")
                return True
            elif dealer_hand.get_value() > 21:
                print("Dealer busted. You win! 😄")
                return True
            elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
                print("Both players have blackjack! Tie! 🤨")
                return True
            elif player_hand.is_blackjack():
                print("You have blackjack! You win! 😄")
                return True
            elif dealer_hand.is_blackjack():
                print("Dealer has blackjack! Dealer wins! 😭")
                return True
        else:
            if player_hand.get_value() > dealer_hand.get_value():
                print("You win! 😄")

        return False

g = Game()
g.play()

Add an elif statement to check if both player's hands equal the same value. If so, print "Tie! 🤨".


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if not game_over:
            if player_hand.get_value() > 21:
                print("You busted. Dealer wins! 😭")
                return True
            elif dealer_hand.get_value() > 21:
                print("Dealer busted. You win! 😄")
                return True
            elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
                print("Both players have blackjack! Tie! 🤨")
                return True
            elif player_hand.is_blackjack():
                print("You have blackjack! You win! 😄")
                return True
            elif dealer_hand.is_blackjack():
                print("Dealer has blackjack! Dealer wins! 😭")
                return True
        else:
            if player_hand.get_value() > dealer_hand.get_value():
                print("You win! 😄")
            elif player_hand.get_value() == dealer_hand.get_value():
                print("Tie! 🤨")

        return False

g = Game()
g.play()

After the elif statement, add an else statment that prints "Dealer wins! 😭"


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if not game_over:
            if player_hand.get_value() > 21:
                print("You busted. Dealer wins! 😭")
                return True
            elif dealer_hand.get_value() > 21:
                print("Dealer busted. You win! 😄")
                return True
            elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
                print("Both players have blackjack! Tie! 🤨")
                return True
            elif player_hand.is_blackjack():
                print("You have blackjack! You win! 😄")
                return True
            elif dealer_hand.is_blackjack():
                print("Dealer has blackjack! Dealer wins! 😭")
                return True
        else:
            if player_hand.get_value() > dealer_hand.get_value():
                print("You win! 😄")
            elif player_hand.get_value() == dealer_hand.get_value():
                print("Tie! 🤨")
            else:
                print("Dealer wins! 😭")

        return False

g = Game()
g.play()

At the exact same level of indentation as the else: line you just added, add the line return True. This will make the method return True if game_over equals True.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if not game_over:
            if player_hand.get_value() > 21:
                print("You busted. Dealer wins! 😭")
                return True
            elif dealer_hand.get_value() > 21:
                print("Dealer busted. You win! 😄")
                return True
            elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
                print("Both players have blackjack! Tie! 🤨")
                return True
            elif player_hand.is_blackjack():
                print("You have blackjack! You win! 😄")
                return True
            elif dealer_hand.is_blackjack():
                print("Dealer has blackjack! Dealer wins! 😭")
                return True
        else:
            if player_hand.get_value() > dealer_hand.get_value():
                print("You win! 😄")
            elif player_hand.get_value() == dealer_hand.get_value():
                print("Tie! 🤨")
            else:
                print("Dealer wins! 😭")

            return True

        return False

g = Game()
g.play()

Now back to the end of the play method inside the while loop. Add this code:

if self.check_winner(player_hand, dealer_hand):
    continue

The check_winner method will return True if there is a winner. The continue line will continue to the next iteration of the while loop. Each iteration is a new game.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
              

            if self.check_winner(player_hand, dealer_hand):
                continue

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if not game_over:
            if player_hand.get_value() > 21:
                print("You busted. Dealer wins! 😭")
                return True
            elif dealer_hand.get_value() > 21:
                print("Dealer busted. You win! 😄")
                return True
            elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
                print("Both players have blackjack! Tie! 🤨")
                return True
            elif player_hand.is_blackjack():
                print("You have blackjack! You win! 😄")
                return True
            elif dealer_hand.is_blackjack():
                print("Dealer has blackjack! Dealer wins! 😭")
                return True
        else:
            if player_hand.get_value() > dealer_hand.get_value():
                print("You win! 😄")
            elif player_hand.get_value() == dealer_hand.get_value():
                print("Tie! 🤨")
            else:
                print("Dealer wins! 😭")

            return True

        return False

g = Game()
g.play()

The player will be able to choose to hit or stand. Inside the while loop (but not inside the if statment you just added), create a variable called "choice" and set it to an empty string ("").


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            choice = ""

The player should be able to keep choosing until the value of their hand is over 21. Right under the choice variable, add a while loop that loops while player_hands value is less than 21. Inside the loop add the following line: choice = input("Please choose 'Hit' or 'Stand': ").lower(). That line will get a choice as input from the user and convert the input to lowercase letters.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            choice = ""
            while player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()

The while loop you just added should also stop if the user's choice is "Stand" or "S". Update the line that starts the while loop to while choice not in ["s", "stand"] and player_hand.get_value() < 21:.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            choice = ""
            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()

After the input, print an empty line.


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            choice = ""
            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()

The program should keep asking the user for a choice until the user enter's a valid choice. The valid choices are "h", "s", "hit", and "stand". Right after the last print statement (same indentation), add a while loop that will keep looping until the user enters a valid choice. Use the previous while loop as an example. Inside the loop, ask for input again with the line choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower().


class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            choice = ""
            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()

Print an empty line.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()

In the last while loop you checked if choice was not in a list. Outside of your recently added while loop but inside the loop added just before that one, add an if statement to check if choice is in the list ["hit", "h"]. If true, add a card to the player's hand that is delt from the deck.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())

Also inside the if statement, display the player's hand.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

Outside of all the while loops about the player making a choice, check for a winner. Use the same if statement and continue statement that you used the last time you checked for a winner.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue                    

Store the value of the player's hand in a variable named player_hand_value.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()        

Store the value of the dealer's hand in a variable named dealer_hand_value.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()      

The dealer should keep drawing cards until dealer_hand_value is more than 17. Make this happen with a while loop. Inside the loop, make sure the dealer is delt a card from the deck and dealer_hand_value is updated.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()      

Outside of that last while loop, display the dealer's hand. When you call the display mehtod, make sure to set show_all_dealer_cards to True.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()

            dealer_hand.display(show_all_dealer_cards=True)    

Check for a winner again, just like before.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()

            dealer_hand.display(show_all_dealer_cards=True)

            if self.check_winner(player_hand, dealer_hand):
                continue 

Print "Final Results".


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()

            dealer_hand.display(show_all_dealer_cards=True)

            if self.check_winner(player_hand, dealer_hand):
                continue 

            print("Final Results")

Now print "Your hand:" with player_hand_value after the string.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()

            dealer_hand.display(show_all_dealer_cards=True)

            if self.check_winner(player_hand, dealer_hand):
                continue 

            print("Final Results")
            print("Your hand:", player_hand_value)

Print "Dealer's hand:" with the dealer_hand_value after the string.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()

            dealer_hand.display(show_all_dealer_cards=True)

            if self.check_winner(player_hand, dealer_hand):
                continue 

            print("Final Results")
            print("Your hand:", player_hand_value)
            print("Dealer's hand:", dealer_hand_value)

Call self.check_winner one final time. This time it should not be in an if statement. Pass in the hands like before but this time add a third argument of True to indicate that the game is over.


            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()

            dealer_hand.display(show_all_dealer_cards=True)

            if self.check_winner(player_hand, dealer_hand):
                continue 

            print("Final Results")
            print("Your hand:", player_hand_value)
            print("Dealer's hand:", dealer_hand_value)

            self.check_winner(player_hand, dealer_hand, True)

At this point in the code, the game is over. Outside of the outer while loop in the play method, add this final line: print("\nThanks for playing!"). Note the \n in the string. That will add a new line.

import random

class Card:
    def __init__(self, suit, rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return f"{self.rank['rank']} of {self.suit}"

class Deck:
    def __init__(self):
        self.cards = []
        suits = ["spades", "clubs", "hearts", "diamonds"]
        ranks = [
                {"rank": "A", "value": 11},
                {"rank": "2", "value": 2},
                {"rank": "3", "value": 3},
                {"rank": "4", "value": 4},
                {"rank": "5", "value": 5},
                {"rank": "6", "value": 6},
                {"rank": "7", "value": 7},
                {"rank": "8", "value": 8},
                {"rank": "9", "value": 9},
                {"rank": "10", "value": 10},
                {"rank": "J", "value": 10},
                {"rank": "Q", "value": 10},
                {"rank": "K", "value": 10},
            ]
        for suit in suits:
            for rank in ranks:
                self.cards.append(Card(suit, rank))

    def shuffle(self):
        if len(self.cards) > 1:
            random.shuffle(self.cards)

    def deal(self, number):
        if len(self.cards) > 0:
            cards_delt = []
            for x in range(number):
                card = cards.pop()
                cards_delt.append(card)
            return cards_delt

class Hand:
    def __init__(self, dealer=False):
        self.cards = []
        self.value = 0
        self.dealer = dealer

    def add_card(self, card_list):
        self.cards.extend(card_list)

    def calculate_value(self):
        self.value = 0
        has_ace = False

        for card in self.cards:
            card_value = int(card.rank["value"])
            self.value += card_value

        if has_ace and self.value > 21:
            self.value -= 10

    def get_value(self):
        self.calculate_value()
        return self.value

    def is_blackjack(self):
        return self.get_value() == 21

    def display(self, show_all_dealer_cards=False):
        print(f'''{"Dealer's" if self.dealer else "Your"} hand:''')
        for index, card in enumerate(self.cards):
            if index == 0 and self.dealer and not show_all_dealer_cards and not self.is_blackjack():
                print("hidden")
            else:
                print(card)

        if not self.dealer:
            print("Value:", self.get_value())
        print()

class Game:
    def play(self):
        game_number = 0
        games_to_play = 0

        while games_to_play <= 0:
            try:
                games_to_play = int(input("How many games do you want to play?: "))
            except:
                print("You must enter a number.")

        while game_number < games_to_play:
            game_number += 1

            deck = Deck()
            deck.shuffle()

            player_hand = Hand()
            dealer_hand = Hand(dealer=True)

            for i in range(2):
                player_hand.add_card(deck.deal())
                dealer_hand.add_card(deck.deal())

            print()
            print("*" * 30)
            print(f"Game {game_number} of {games_to_play}")
            print("*" * 30)
            player_hand.display()
            dealer_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            choice = ""
            while choice not in ["s", "stand"] and player_hand.get_value() < 21:
                choice = input("Please choose 'Hit' or 'Stand': ").lower()
                print()
                while choice not in ["h", "s", "hit", "stand"]:
                    choice = input("Please enter 'Hit' or 'Stand' (or H/S) ").lower()
                    print()
                if choice in ["hit", "h"]:
                    player_hand.add_card(deck.deal())
                    player_hand.display()

            if self.check_winner(player_hand, dealer_hand):
                continue

            player_hand_value = player_hand.get_value()
            dealer_hand_value = dealer_hand.get_value()


            while dealer_hand_value < 17:
                dealer_hand.add_card(deck.deal())
                dealer_hand_value = dealer_hand.get_value()

            dealer_hand.display(show_all_dealer_cards=True)

            if self.check_winner(player_hand, dealer_hand):
                continue 

            print("Final Results")
            print("Your hand:", player_hand_value)
            print("Dealer's hand:", dealer_hand_value)

            self.check_winner(player_hand, dealer_hand, True)
            
        print("\nThanks for playing!")

    def check_winner(self, player_hand, dearler_hand, game_over=False):
        if not game_over:
            if player_hand.get_value() > 21:
                print("You busted. Dealer wins! 😭")
                return True
            elif dealer_hand.get_value() > 21:
                print("Dealer busted. You win! 😄")
                return True
            elif player_hand.is_blackjack() and dealer_hand.is_blackjack():
                print("Both players have blackjack! Tie! 🤨")
                return True
            elif player_hand.is_blackjack():
                print("You have blackjack! You win! 😄")
                return True
            elif dealer_hand.is_blackjack():
                print("Dealer has blackjack! Dealer wins! 😭")
                return True
        else:
            if player_hand.get_value() > dealer_hand.get_value():
                print("You win! 😄")
            elif player_hand.get_value() == dealer_hand.get_value():
                print("Tie! 🤨")
            else:
                print("Dealer wins! 😭")

            return True

        return False

g = Game()
g.play()

You are done! Run the program to try it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment