Python Black Jack Game – Experience the Thrills of Black Jack

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

Welcome to our tutorial on creating a Python Black Jack game using the Pygame library. In this tutorial, we will walk you through the steps of creating a simple BlackJack game, including importing libraries, setting up the game screen, creating the deck of cards, and implementing the game logic. By the end of this tutorial, you will have a working BlackJack game that you can further customize and improve.

Python Black Jack Game

This project aims to teach you how to create a BlackJack game using Python and Pygame. By the end of this tutorial, you will have a working BlackJack game that you can use as a starting point for your own projects.

Project Prerequisites:

  • Basic understanding of Python programming
  • Basic understanding of Pygame library

Download Python Black Jack Game Project

Please download the source code for the python blackjack game project: Black Jack Game Project

Python BlackJack Game Project File Structure

Steps for building the python blackjack game:

Step 1: Importing Libraries

The first step in creating our BlackJack game is to import the necessary libraries. In this case, we will use the Pygame library, a set of Python modules designed for creating games. We also import the random module, which will randomly select cards from the deck.

# Importing the required modules
import pygame
from random import randint

Step 2: Initializing Pygame

Once we have imported the necessary libraries, we need to initialize the Pygame modules. This is done using the pygame.init() function.

# Initializing the pygame modules
pygame.init()
pygame.font.init()

Step 3: Setting the Screen and Caption

Next, we need to set the screen’s size and the game’s caption. This is done using the pygame.display.set_mode() and pygame.display.set_caption() functions, respectively. In this case, we set the screen size to 1000×800 and the caption to “ProjectGurukul – BlackJack”.

# Setting the screen size and caption
screen = pygame.display.set_mode((1000, 800))
pygame.display.set_caption('ProjectGurukul - BlackJack')

Step 4: Setting the Variables

Next, we need to set the variables for the game. We will be using the following variables:

  • money: This variable will be used to store the player’s money.
  • bet: This variable will be used to store the amount of money the player bets.
  • deck: This variable will be used to store the current deck of cards.
  • dealer: This variable will be used to store the dealer’s cards.
  • hand: This variable will be used to store the player’s cards.
  • turn: This variable will be used to store the current turn of the game.
  • start: This variable will be used to store whether the game has started or not.
  • running: This variable will be used to store whether the game is running or not.
  • background: This variable will be used to store the background image.
  • myFont: This variable will be used to store the font.
  • fullDeck: This variable will be used to store the full deck of cards.
# Setting the deck
fullDeck = ['7_of_diamonds', 'queen_of_spades', 'jack_of_spades', '8_of_diamonds', '6_of_clubs', '9_of_hearts', 'ace_of_hearts', '8_of_spades', 'king_of_clubs', '7_of_clubs', '10_of_diamonds', '10_of_spades', 'jack_of_clubs', '6_of_spades', '4_of_hearts', '2_of_spades', 'queen_of_clubs', '3_of_hearts', '5_of_spades', '6_of_diamonds', 'queen_of_diamonds', '7_of_hearts', 'king_of_hearts', 'ace_of_clubs', '9_of_diamonds', '6_of_hearts', '9_of_clubs', 'king_of_diamonds', '4_of_spades', '2_of_hearts', '3_of_diamonds', '10_of_hearts', 'king_of_spades','8_of_clubs', '4_of_diamonds', 'jack_of_diamonds', '3_of_spades', '5_of_hearts','7_of_spades', 'ace_of_spades', '5_of_diamonds', '9_of_spades', 'queen_of_hearts','ace_of_diamonds', '5_of_clubs', '2_of_clubs', 'jack_of_hearts', '10_of_clubs''2_of_diamonds', '8_of_hearts', '3_of_clubs', '4_of_clubs']


# Setting the variables for the game
money = 100000
bet = 5000


deck = fullDeck
dealer = []
hand = []
turn = 2
start = True
running = True


# Loading the background image
background = pygame.image.load('PlayingCards/back6.jpeg')


# Setting the font
myFont = pygame.font.SysFont('ComicsansMS', 30)

Step 5: Setting the Functions

Next, we need to set the functions for the game. We will be using the following functions:

  • resetDeck(): This function will be used to reset the deck of cards.
  • drawTxt(txt, x, y): This function will be used to draw text on the screen.
  • playCard(card, x, y): This function will be used to draw the cards on the screen.
  • deal(): This function will be used to deal the cards.
  • drawHitStandButton(): This function will be used to draw the buttons “Hit” and “Stand”.
  • drawPlayerTurn(): This function will be used to draw the player’s turn screen that will be used to draw the buttons “Hit” and “Stand”.
  • drawDeck(): This function will be used to draw the deck of cards.
  • betting(): This function will be used to draw the buttons for the money and the bet.
  • hit(): This function will be used to draw a card from the deck and add it to the player’s hand.
  • value(card): This function will be used to calculate the value of the cards in the player’s hand.
  • drawDealerTurn(): This function will be used to draw the dealer’s turn screen that makes the dealer draw cards until the value of the cards in the dealer’s hand is less than 17.
  • drawPlayAgain(): This function will be used to draw the screen that will be used to ask the player if they want to play again.
# This function resets the 'deck' variable
# to the original 'fullDeck' list.
def resetDeck():
    deck = fullDeck


# function to draw text
def drawTxt(txt, x, y):
    drawtxt = myFont.render(txt, False, (255,255,255))
    screen.blit(drawtxt, (x, y))


# function to draw the cards on the screen
def playCard(card, x, y):
    pic = pygame.image.load('PlayingCards/' + str(card) + '.png')
    pic = pygame.transform.scale(pic, (160, 220))
    screen.blit(pic, (x, y))


# Function to deal the cards
# This function deals cards to both the dealer and the
# player,randomly selecting cards from the current deck
# and removing them from the deck.
def deal():


   # Deal dealer cards
    while len(dealer) != 0:
        dealer.pop(0)
    delt = randint(0, len(deck) - 1)
    dealer.append(deck[delt])
    deck.pop(delt)
    delt = randint(0, len(deck) - 1)
    dealer.append(deck[delt])
    deck.pop(delt)


   # Deal player cards
    while len(hand) != 0:
        hand.pop(0)
    delt = randint(1, len(deck)) - 1
    hand.append(deck[delt])
    deck.pop(delt)
    delt = randint(1, len(deck)) - 1
    hand.append(deck[delt])
    deck.pop(delt)


    # Draw cards on screen
    playCard(dealer[0], 300, 100)
    playCard('back', 330, 100)
    playCard(hand[0], 300, 560)
    playCard(hand[1], 330, 560)


# function to draw the buttons "Hit" and "Stand"
def drawHitStandButton():
    pygame.draw.rect(screen, ("#FF4500"), (100, 650, 100, 50))
    pygame.draw.rect(screen, ("#228B22"), (800, 650, 100, 50))
    drawTxt('Hit', 128, 650)
    drawTxt('Stand', 808, 650)


# function to draw the player's turn screen
def drawPlayerTurn():
    screen.blit(pygame.transform.scale(background, (1000, 800)), (0, 0))
    drawDeck()
    deal()
    drawHitStandButton()


# function to draw the deck
def drawDeck():
    screen.blit(pygame.transform.scale(pygame.image.load('PlayingCards/back.png'), (160, 220)), (50, 330))
    drawTxt("Money = Rs. " + str(money), 10, 10)


# function to draw the betting screen
def betting():
    # Setting background image to the betting screen
    screen.blit(pygame.transform.scale(background, (1000, 800)), (0, 0))


    # Draw the deck
    drawDeck()


    # Creating bet add button
    pygame.draw.rect(screen, ("#14D514"), (850, 325, 50, 50))
    pygame.draw.rect(screen, (255,255,255), (870, 335, 10, 30))
    pygame.draw.rect(screen, (255,255,255), (860, 345, 30, 10))


    # Creating bet subtract button
    pygame.draw.rect(screen, ("#d51414"), (850, 425, 50, 50))
    pygame.draw.rect(screen, (255,255,255), (860, 445, 30, 10))


    # Creating button to place bet
    pygame.draw.rect(screen, ("#874efc"), (720, 500, 170, 50))
    drawTxt('Place Bet', 740, 500)
    drawTxt('Rs. ' + str(bet), 750, 375)




# function to draw the cards on the screen
# when the player hits the "Hit" button
def hit():
    if len(hand) >= 10:
        drawTxt('That\'s enough cards', 400, 385)
        return
    delt = randint(0, len(deck) - 1)
    hand.append(deck[delt])
    deck.pop(delt)
    playCard(hand[len(hand) - 1], 275 + len(hand) * 30, 560)



# function to return the value of a card
def value(card):
    values = {  'ace': 11, '2': 2, '3': 3, '4': 4, '5': 5,
               '6': 6, '7': 7, '8': 8, '9': 9, '10': 10,
               'jack': 10, 'queen': 10, 'king': 10
               }
    return values[card.split('_')[0]]


# function to draw the dealer's turn screen
def drawDealerTurn():


    playCard(dealer[1], 330, 100)


    # Calculate the total value of the player's hand
    total = 0
    for card in hand:
        if value(card) == 11 and total > 10:
            total += 1
        else:
            total += value(card)


    # Calculate the total value of the dealer's hand
    dealerTotal = 0
    dealer.sort(key=value)
    for card in dealer:
        if value(card) == 11 and dealerTotal > 10:
            dealerTotal += 1
        else:
            dealerTotal += value(card)


    # If the dealer's hand is less than 17, the dealer hits
    # until the hand is greater than or equal to 17
    while dealerTotal < 17:
        delt = randint(0, len(deck) - 1)
        dealer.append(deck[delt])
        playCard(deck[delt], 275 + len(dealer) * 30, 100)
        deck.pop(delt)


        dealerTotal = 0
        dealer.sort(key=value)

 
        # Calculate the total value of the dealer's hand
        for card in dealer:
            if value(card) == 11 and dealerTotal > 10:
                dealerTotal += 1
            else:
                dealerTotal += value(card)
 



    # If the player's hand is greater than 21, the player busts
    if total == 21 and len(hand) == 2:
        drawTxt('BlackJack', 400, 375)
        return 2
 

    # If the player's hand is greater than 21, the player busts
    elif total > 21:
        drawTxt('Bust', 400, 375)
        return 0


    # If the dealer's hand is greater than 21, the dealer busts
    elif dealerTotal > 21:
        drawTxt('Dealer Busted', 400, 375)
        return 1


    # If the player's hand is greater than the dealer's hand, the player wins
    elif total > dealerTotal:
        drawTxt('You Win', 400, 375)
        return 1


    # If the player's hand is less than the dealer's hand, the player loses
    elif total < dealerTotal:
        drawTxt('You Lose', 400, 375)
        return 0


    # If the player's hand is equal to the dealer's hand, it's a tie
    else:
        drawTxt('Tie', 400, 375)
        return 3




# function display the "Play Again" button
def drawPlayAgain():
    pygame.draw.rect(screen, ("#A93226"), (715, 100, 185, 50))
    drawTxt('Play Again', 735, 100)

Step 6: Create the main loop of the game

In this step, we will create the main loop of the game. In this loop, we will update the screen, handle user inputs, and manage the flow of the game. We will also create the game state variable that will keep track of the game state.

The game state variable will be used to determine which screen to draw. The game state variable will be set to 2 when the player is betting, 1 when the player is playing, and 0 when the dealer is playing. The game state variable will be set to 3 when the game is over.

If the player has no money left, the game will end. If the player clicks on the “Play Again” button, the game state variable will be set to 2 and the player will be able to bet again. If the player clicks on the “Hit” button, the player will be dealt a card.

The dealer will play if the player clicks on the “Stand” button. If the player clicks on the “+” button, the player will increase the bet by $5,000. If the player clicks on the “-” button, the player will decrease the bet by $5,000. If the player clicks on the “Place Bet” button, the player will start playing. The game will restart if the player clicks on the “Play Again” button.

# This is the main loop of the game that updates the screen,
# handles user inputs, and manages the flow of the game.
while running:
    pygame.display.update()


   # This loop handles all of the user inputs
   # like mouse clicks and key presses
   # and updates the game state accordingly
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


       #here turn = 1 means the player is playing
       #here turn = 2 means the player is betting
       #here turn = 0 means the dealer is playing




       # If the player is betting
        if turn == 2:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse = pygame.mouse.get_pos()


               # If the player clicks on the "+" button
                if 850 < mouse[0] < 900 and 325 < mouse[1] < 375:
                    bet += 5000
                    if bet > money:
                        bet = money


               # If the player clicks on the "-" button
                elif 850 < mouse[0] < 900 and 425 < mouse[1] < 475:
                    bet -= 5000
                    if bet < 0:
                        bet = 0


               # If the player clicks on the "Place Bet" button
                if 720 < mouse[0] < 890 and 500 < mouse[1] < 550:
                    turn = 1
                    start = True


       # If the player is playing
        elif turn == 1:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse = pygame.mouse.get_pos()


                # If the player clicks on the "Hit" button
                if 100 < mouse[0] < 200 and 650 < mouse[1] < 700:
                    hit()


                # If the player clicks on the "Stand" button
                elif 800 < mouse[0] < 900 and 650 < mouse[1] < 700:
                    hand.sort(key=value)
                    turn = 0
                    start = True


       # If the dealer is playing
        elif turn == 0:
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse = pygame.mouse.get_pos()


               # If the player clicks on the "Play Again" button
                if 715 < mouse[0] < 900 and 100 < mouse[1] < 150:
                    bet = 5000
                    turn = 2




   # If the player has no money left, the game ends
    if bet == 0 and turn == 1:
        break


   # It will check the turn and draw the appropriate screen
   # here turn is the variable that keeps track of the game state
    if turn == 2:
        betting()
    if turn == 1 and start == True:
        drawPlayerTurn()
        start = False
    if turn == 0 and start == True:
        #here result is the return value of the function drawDealerTurn()
        #result = 0 means player lost
        #result = 1 means player won
        #result = 2 means player won with blackjack
        result = drawDealerTurn()


       # Update the player's money based on the result
        if result == 0:
            money -= bet
        elif result == 1:
            money += bet
        elif result == 2:
            money += bet * 1.5
        start = False


    # If the player lost the game
    # prompt the player to play again
    if turn == 0:
        drawPlayAgain()
        resetDeck()

Step 7: End the game

In this step, we will end the game by exiting the game loop and quitting the game if the player has no money left or if the player clicks on the exit button.

 

# Exit the game
pygame.quit()

Python Black Jack Game Output

python blackjack game output

Summary

Hooray! With Pygame, you have successfully developed a blackjack game in Python. We learned how to handle events, load images, and draw text on the screen. Now you can modify this code to your liking to develop a more sophisticated version of this game.

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

Leave a Reply

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