top of page

25% Discount For All Pricing Plans "welcome"

Blackjack Game


What is Blackjack?


Blackjack is a game of chance played with one or more decks of cards. The aim of the game is to beat the dealer by having a total card value of 21 or as close to 21 as possible. Blackjack is often one of the indispensable games of casinos and is known as both a fun and strategic game. The origin of the game dates back to 18th-century France and has spread worldwide from there.


Project Goals and Student Benefits


With this project, students will reinforce their ability to develop simple and functional programs using basic Python knowledge. Additionally, by understanding how popular applications like card games are coded, they will gain experience in game simulation and algorithm development.


Project Target Outcomes

  • Creating a game simulation using basic Python structures and control flows.

  • Receiving data from the user and managing the game flow by processing this data.

  • Writing more modular and readable code with the help of functions.


Step-by-Step Tasks of the Project

  1. Creating a deck of cards and defining their values.

  2. Distributing initial cards to the player and the dealer.

  3. Managing the player's card drawing actions.

  4. Managing the dealer's card drawing actions.

  5. Determining and displaying the game results.

  6. Making the code more modular using functions.


Step 1: Creating a Deck of Cards and Initial Settings

As a first step, a deck of cards will be created, and the initial settings of the game will be done.

import random

# Creating a deck of cards
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4  # Ace: 11, King/Queen/Jack: 10

# Game start state
game_over = False
player_hand = []
dealer_hand = []

This piece of code creates the deck of cards needed for the game and sets the initial state of the game. The random module is used to randomly select cards.


Step 2: Distributing Initial Cards

In the second step, the initial cards will be distributed to the player and the dealer.

# Distributing the initial cards
player_hand.append(random.choice(cards))  # Select and add a card for the player
player_hand.append(random.choice(cards))  # Select and add a second card for the player
dealer_hand.append(random.choice(cards))  # Select and add a card for the dealer
dealer_hand.append(random.choice(cards))  # Select and add a second card for the dealer

print(f"Player's cards: {player_hand}, total: {sum(player_hand)}")  # Print the player's cards and total
print(f"Dealer's cards: [{dealer_hand[0]}, ?]")  # Print one of the dealer's cards and the hidden one

# If the total of the first two cards of the player or dealer is 21, they win the game
if sum(player_hand) == 21:
    print("Blackjack! Player wins!")
    game_over = True
elif sum(dealer_hand) == 21:
    print("Blackjack! Dealer wins!")
    game_over = True

This piece of code distributes the starting cards to the player and dealer and prints the initial state on the screen. It also indicates if the player or dealer wins the game if the total of their first two cards is 21.


Step 3: Player's Card Drawing Actions

In the third step, the player's card drawing actions will be performed.

# Player continues to draw cards
while not game_over and sum(player_hand) < 21:  # Continue if the player's total is less than 21 and the game is not over
    decision = input("Do you want to draw a card? (y/n): ")  # Ask the player if they want to draw a card
    if decision == 'y':  # If yes
        player_hand.append(random.choice(cards))  # Draw a new card and add it to the player's hand
        print(f"Player's new card: {player_hand[-1]}")  # Print the player's new card
        print(f"Player's cards: {player_hand}, total: {sum(player_hand)}")  # Print all of the player's cards and total
        if sum(player_hand) == 21:  # If the player's total is 21
            print("Player made 21! Player wins!")
            game_over = True
        elif sum(player_hand) > 21:  # If the player's total exceeds 21
            print("Player busted! Dealer wins.")
            game_over = True
    else:
        break  # Exit the loop if no

This piece of code manages the player's card drawing actions. As long as the player's total card value does not exceed 21, the player can continue to draw cards. If the player makes 21, they win the game, and if they exceed 21, they lose.


Step 4: Dealer's Card Drawing Actions

In the fourth step, the dealer's card drawing actions will be performed.

# Dealer draws cards
while not game_over and sum(dealer_hand) < 17:  # Continue if the dealer's total is less than 17 and the game is not over
    dealer_hand.append(random.choice(cards))  # Draw a new card and add it to the dealer's hand

print(f"Dealer's cards: {dealer_hand}, total: {sum(dealer_hand)}")  # Print all of the dealer's cards and total

This piece of code manages the dealer's card drawing actions. If the dealer's total card value is less than 17, the dealer continues to draw cards.


Step 5: Determining the Results

In the fifth step, the game results will be determined and displayed on the screen.

# Determine results
if not game_over:
    if sum(dealer_hand) > 21:
        print("Dealer busted! Player wins.")
    elif sum(dealer_hand) == 21:
        print("Dealer made 21! Dealer wins.")
    elif sum(dealer_hand) > sum(player_hand):
        print("Dealer wins!")
    elif sum(dealer_hand) < sum(player_hand):
        print("Player wins!")
    else:
        print("It's a tie!")

This piece of code determines the game results and displays them on the screen. If the dealer's total card value exceeds 21, they lose; if it is 21, they win; if it is greater than the player's, they win; if it is less than the player's, they lose; if it is equal, it is a tie.


Step 6: Solution with Functions


Card Drawing Function

This function allows drawing a random card from the deck.

def draw_card(deck):
    """Draws a random card from the deck."""
    return random.choice(deck)

The card drawing process selects and returns a random card from the deck. This function is used to ensure that the cards in the deck are selected randomly.


Card Distribution Function

This function distributes two cards to the player and the dealer.

def distribute_cards():
    """Distributes two cards to the player and the dealer."""
    return [draw_card(cards), draw_card(cards)]

Gives two initial cards to the player and dealer. This function is used to distribute cards to both sides at the start of the game.


Displaying Cards Function

This function displays the cards in hand. One of the dealer's cards may be hidden.

def show_cards(hand, hidden=False):
    """Displays the cards in hand. One of the dealer's cards may be hidden."""
    if hidden:
        return f"[{hand[0]}, ?]"
    return f"{hand}, total: {sum(hand)}"

Displays the given hand of cards. Since one of the dealer's cards may be hidden, it shows the hidden card as "?". This function is used to print the game state to the screen.


Hand Total Calculation Function

This function calculates the total of the cards in hand.

def hand_total(hand):
    """Calculates the total of the cards in hand."""
    return sum(hand)

Calculates and returns the total of the given hand of cards. This function is used to determine the total card values of the player and dealer.


Player Card Drawing Function

This function allows the player to draw a new card.

def player_draw_card(hand, deck):
    """Allows the player to draw a new card."""
    hand.append(draw_card(deck))
    print(f"Player's new card: {hand[-1]}")
    print(f"Player's cards: {show_cards(hand)}")

Allows the player to draw a new card and adds the new card to the player's hand. This function is used to manage the player's card drawing actions.


Dealer Card Drawing Function

This function performs the dealer's card drawing actions.

def dealer_draw_card(hand, deck):
    """Performs the dealer's card drawing actions."""
    while hand_total(hand) < 17:
        hand.append(draw_card(deck))
    print(f"Dealer's cards: {show_cards(hand)}")

Manages the dealer's card drawing actions. If the dealer's total card value is less than 17, the dealer continues to draw cards. This function ensures that the dealer draws cards according to the game rules.


Starting the Game Function

This function starts the Blackjack game and manages the game flow.

def start_game():
    """Starts the Blackjack game."""
    player_hand = distribute_cards()
    dealer_hand = distribute_cards()

    print(f"Player's cards: {show_cards(player_hand)}")
    print(f"Dealer's cards: {show_cards(dealer_hand, hidden=True)}")

    # If the total of the first two cards of the player or dealer is 21, they win the game
    if hand_total(player_hand) == 21:
        print("Blackjack! Player wins!")
        return
    elif hand_total(dealer_hand) == 21:
        print("Blackjack! Dealer wins!")
        return

    while hand_total(player_hand) < 21:
        decision = input("Do you want to draw a card? (y/n): ")
        if decision == 'y':
            player_draw_card(player_hand, cards)
            if hand_total(player_hand) == 21:
                print("Player made 21! Player wins!")
                return
            elif hand_total(player_hand) > 21:
                print("Player busted! Dealer wins.")
                return
        else:
            break

    dealer_draw_card(dealer_hand, cards)

    if hand_total(dealer_hand) > 21:
        print("Dealer busted! Player wins.")
    elif hand_total(dealer_hand) == 21:
        print("Dealer made 21! Dealer wins.")
    elif hand_total(dealer_hand) > hand_total(player_hand):
        print("Dealer wins!")
    elif hand_total(dealer_hand) < hand_total(player_hand):
        print("Player wins!")
    else:
        print("It's a tie!")

# Creating a deck of cards
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11] * 4  # Ace: 11, King/Queen/Jack: 10

start_game()

Topics Covered

  • Data Types: In this project, integers (card values) and lists (deck of cards, hand cards) were used.

  • Lists: The deck of cards and player/dealer hand cards are held as lists.

  • Conditional Statements: if-else structures were used to determine the game results and process the player's/dealer's card drawing decisions.

  • Functions: Functions ensured that the code was modular and reusable.

  • Loops: while loops were used to manage the card drawing actions of the player and dealer.

  • Random Module: The random.choice() function ensured that the cards were selected randomly.

Opmerkingen


Opmerkingen zijn uitgezet.
bottom of page