Create Blackjack Game using Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

If you are one of the deck cards players, then you would be familiar with the blackjack game. If not, don’t worry we will get to know and build one to play. So, let’s create Blackjack Game using Python.

What is a Blackjack Game?

Blackjack is one of the casino games of luck and strategy, also known as 21. In this, the player tries to keep the amount of all the cards sum up to 21 without exceeding it.

In this A will be treated as 1/11, and Jacks, Queens, and Kings will be 10. And the game goes like this:

1. The dealer and player get two cards that are not disclosed to the opponent.

2. Now the player gets to choose between hitting, staying.

3. If hitting is chosen, then another card will be given to the player.

4. If the choice is staying, allowed only when the count is greater than 11, then the result is shown based on the conditions:

a. If the player’s score is greater than 21 or when the dealer’s score is less than 21 but greater than that of the player, then the dealer wins

b. If the above case is with the dealer’s score then the Player wins

c. Or else it’s a tie.

5. And another choice is to shuffle where the cards are mixed randomly.

6. The last choice is to start the game again

Blackjack Game in Python

We will be using the Tkinter module to build the game. And the random module for shuffling. In this, we will be using the pre-downloaded card images named in the format ‘cardNumber_suitName’ to show on the window.

Download the Python Blackjack Game

Please download the source code for the blackjack game using the link: Python Blackjack Game Source Code

Project Prerequisites

The prior knowledge of Python and the Tkinter module would help you in developing this game. And you can install the Tkinter module, if not installed yet, using the command:

pip install tk

Steps to build Blackjack Game using Python

To build this game, we will be following steps:

1. First, we start by importing modules

2. We create a window and set properties

3. And we add the required components to window

4. We then create a function to load all the images from device

5. And then a function to pick a card

6. Then write a function to calculate the total of the cards

7. Then write functions to run on hitting and staying

8. After this, we write functions for shuffling and for new game

9. Then write code to create global variables, load images, and run game

1. Importing modules

First, we start by importing the Tkinter and the random modules that we discussed above. Here we also import the font from Tkinter to add some style to the text.

import random
import tkinter
from tkinter.font import BOLD

2. Creating a window

Now we create a new window with the title and the size set using the attributes title() and geometry().

gameWindow = tkinter.Tk()

# Set up the screen and frames for the dealer and player
gameWindow.title("DataFlair Black Jack")
gameWindow.geometry("640x480")

3. Adding the widgets

Now we add the following widgets:

a. Label

  • To show the title
  • Show the winner on calculating and comparing scores
  • Show the scores of player and dealer

b. Frames

  • To show the cards of player and dealer

c. Buttons for the following operations

  • Hit
  • Stay
  • Shuffling
  • Start a new game
tkinter.Label(gameWindow, text='DataFlair Black Jack',
      fg='black', font=('Courier', 20,BOLD)).place(x=150, y=10)

winner=tkinter.StringVar()
result = tkinter.Label(gameWindow, textvariable=winner,fg='black',font=('Courier', 15))
result.place(x=250,y=50)

dealerScore = tkinter.IntVar()
tkinter.Label(gameWindow, text="Dealer Score:", fg="black",bg="white").place(x=10,y=80)
tkinter.Label(gameWindow, textvariable=dealerScore, fg="black",bg="white").place(x=10,y=100)
# embedded frame to hold the card images
dealer_cardFrame = tkinter.Frame(gameWindow, bg="black")
dealer_cardFrame.place(x=100,y=80)

playerScore = tkinter.IntVar()

tkinter.Label(gameWindow, text="Player Score:", fg="black",bg="white").place(x=10,y=200)
tkinter.Label(gameWindow, textvariable=playerScore,fg="black",bg="white").place(x=10,y=220)
# embedded frame to hold the card images
player_card_frame = tkinter.Frame(gameWindow, bg="black")
player_card_frame.place(x=100,y=200)

player_button = tkinter.Button(gameWindow, text="Hit", command=hitting, padx=8)
player_button.place(x=50,y=350)

dealer_button = tkinter.Button(gameWindow, text="Stay", command=staying, padx=5)
dealer_button.place(x=150,y=350)

reset_button = tkinter.Button(gameWindow, text="New Game", command=new_game)
reset_button.place(x=250,y=350)

shuffle_button = tkinter.Button(gameWindow, text="Shuffle", command=shuffle, padx=2)
shuffle_button.place(x=380,y=350)

4. Creating a function to load images

Now we create a list of all suits and the face cards. And run a loop for all suits and an inner loop to get all the cards 1-10,J,Q,K from each suit, to get allcard images.

In the inner for loop, we run from 1-10 and for J,Q,K separately. And get the path of the cards and read the image and append it to the list ‘card_images’.

# function for retrieving the images of the cards from device
def getCardImages(card_images):
    suits = ['heart', 'club', 'diamond', 'spade']
    faceCards = ['jack', 'queen', 'king']

    ext= 'png'
    for suit in suits:
        # adding the number cards 1 to 10
        for card in range(1, 11):
            path= 'C:/Users/DELL/Downloads/cards/{}_{}.{}'.format(str(card), suit, ext)
            image = tkinter.PhotoImage(file=path)
            card_images.append((card, image, ))

        # adding the face cards
        for card in faceCards:
            path= 'C:/Users/DELL/Downloads/cards/{}_{}.{}'.format(str(card), suit, ext)
            image = tkinter.PhotoImage(file=path)
            card_images.append((10, image, ))

5. Creating a function to pick a card

In this, we get the first element of the deck, show it on the screen and add it to the deck at the end.

def getCard(frame):
    # pop the card on the top of the deck
    next_card = deck.pop(0)
    # and add it to the deck at the end
    deck.append(next_card)
    # show the image to a label
    tkinter.Label(frame, image=next_card[1], relief="raised").pack(side="left")
    # return the card
    return next_card

6. Creating a function to calculate score

Now, we calculate the score by running through all the cards of a player and add the score by following the conditions:

a. Ace is taken as 11 only once and the rest of the time it is considered as 1 while finding the sum of the values on cards

b. If the total score is greater than 21, and if there is an ace, reconsider it as 1 by subtracting the total by 10

# Function to calculate the total score of all cards in the list
def calcScore(hand):
    score = 0
    ace = False
    for next_card in hand:
        card_value = next_card[0]
        # Ace is considered as 11 only once and rest of the time it is taken as 1
        if card_value == 1 and not ace:
            ace = True
            card_value = 11
        score += card_value
        # if its a bust, check if there is an ace and subtract 10
        if score > 21 and ace:
            score -= 10
            ace = False
    return score

7. Functions for hit and stay options

The staying() function first gets a score and if it’s less than 17, adds another card to the dealer’s deck and gets the new score.Then the score of the player is calculated and the winner is decided based on the conditions we discussed initially.

In the function hitting, a new card is given to the player and the new score is calculated. Then, if the score is more than 21 the dealer is the winner.

#Show the winner when the player stays
def staying():
    dealer_score = calcScore(dealer_hand)
    while 0 < dealer_score < 17:
        dealer_hand.append(getCard(dealer_cardFrame))
        dealer_score = calcScore(dealer_hand)
        dealerScore.set(dealer_score)

    player_score = calcScore(player_hand)
    if player_score > 21 or dealer_score > player_score:
        winner.set("Dealer wins!")
    elif dealer_score > 21 or dealer_score < player_score:
        winner.set("Player wins!")
    else:
        winner.set("Draw!")

#Show the winner when the player hits
def hitting():
    player_hand.append(getCard(player_card_frame))
    player_score = calcScore(player_hand)

    playerScore.set(player_score)
    if player_score > 21:
        winner.set("Dealer Wins!")

8. Functions for shuffling and new game

The initial_deal() function gives two cards to the player and a card to the dealer. And also shows the dealer’s score.

The new_game() function resets the frames, lists, and the winner label. And the shuffle() function randomly shuffles the cards in the list deck.

def initial_deal():
    hitting()
    dealer_hand.append(getCard(dealer_cardFrame))
    dealerScore.set(calcScore(dealer_hand))
    hitting()


def new_game():
    global dealer_cardFrame
    global player_card_frame
    global dealer_hand
    global player_hand
    # embedded frame to hold the card images
    dealer_cardFrame.destroy()
    dealer_cardFrame = tkinter.Frame(gameWindow, bg="black")
    dealer_cardFrame.place(x=100,y=80)
   
    # embedded frame to hold the card images
    player_card_frame.destroy()
    player_card_frame = tkinter.Frame(gameWindow, bg="black")
    player_card_frame.place(x=100,y=200)

    winner.set("")

    # Create the list to store the dealer's and player's hands
    dealer_hand = []
    player_hand = []
    initial_deal()


def shuffle():
    random.shuffle(deck)

9. Creating global variables, loading images, and running the game

Finally, we create the lists to hold all the cards, players and dealers cards. And then load all the cards images and initialize the game.

# load cards
cards = []

deck = list(cards) + list(cards) + list(cards)
shuffle()

# Create the list to store the dealer's and player's hands
dealer_hand = []
player_hand = []

getCardImages(cards)
initial_deal()

gameWindow.mainloop()

Output of Python Blackjack Game

Blackjack game game window

output python blackjack game

Summary

Congratulations, you have successfully built the blackjack game! Hope you found it informative and interesting. Keep practicing!

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team is a group of passionate educators and industry experts dedicated to providing high-quality online learning resources on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. With years of experience in the field, the team aims to simplify complex topics and help learners advance their careers. At DataFlair, we believe in empowering students and professionals with the knowledge and skills needed to thrive in today’s fast-paced tech industry. Follow us for Free courses, expert insights, tutorials, and practical tips to boost your learning journey.

1 Response

  1. Brian says:

    Where do I get the card images from for this Blackjack game?

Leave a Reply

Your email address will not be published. Required fields are marked *