Card Game: Blackjack with Python

2023

In this project, we will explore how to create a Blackjack card game using Python. Blackjack is a popular card game where the goal is to have a hand value as close to 21 as possible without exceeding it. We'll explain each step of the code and provide the final working code at the end.


Setting Up the Game

To begin, we need to import the random module to generate random cards:

import random

This module allows us to select random cards from a deck.

Next, we define two functions that will help us in the game:

def deal_card():
    card_values = ([11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10])
    random_card = random.choice(card_values)
    return random_card

def calculate_score(cards):
    if sum(cards) == 21 and len(cards) == 2:
        return 0
    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        cards.append(1)
    return sum(cards)

The deal_card() function selects a random card from a predefined set of card values and returns it.

The calculate_score() function calculates the total score of a player's or dealer's hand. It accounts for the special case of an Ace card being counted as 1 or 11 based on the current hand value.

Playing the Game

We initialize the player's and dealer's hands as empty lists:

player_cards = []
dealer_cards = []
game_over = False

Next, we deal two cards to each player:

for _ in range(2):
    player_cards.append(deal_card())
    dealer_cards.append(deal_card())

The players receive two random cards each by appending the randomly dealt cards to their respective lists.

We calculate the initial scores for the player and the dealer:

player_score = calculate_score(player_cards)
dealer_score = calculate_score(dealer_cards)

The scores are calculated using the calculate_score() function.

Now, we enter a loop to play the game:

while not game_over:
    player_score = calculate_score(player_cards)
    dealer_score = calculate_score(dealer_cards)
    print(f"Your cards: {player_cards}, current score: {player_score}")
    print(f"Dealer's first card: {dealer_cards[0]}")

    if player_score == 0 or dealer_score == 0 or player_score > 21:
        game_over = True
    else:
        choice = input("Type 'Y' to get another card, 'N' to pass: ").upper()
        if choice == "Y":
            player_cards.append(deal_card())
        elif choice == "N":
            game_over = True
        else:
            game_over = True

Inside the loop, we display the player's current hand and the dealer's first card. Then, we check if the game is over due to a winning condition or a bust (score exceeding 21).

If the game is not over, the player is prompted to either get another card ('Y') or pass ('N'). Any other input results in ending the game.

After the player's turn, we let the dealer play:

while dealer_score != 0 and dealer_score < 17:
    dealer_cards.append(deal_card())
    dealer_score = calculate_score(dealer_cards)

The dealer continues to draw cards until they reach a score of 17 or more or they achieve a winning score of 21.

Finally, we determine the outcome of the game:

print(f"Dealer's cards: {dealer_cards}")
print(f"Dealer's score: {dealer_score}")
print(compare_scores(dealer_score, player_score))

We display the dealer's final hand and score, and then compare the scores to determine the winner or a tie.


Final Code

Here's the complete Python code for the Blackjack game:

import random

def deal_card():
    card_values = ([11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10])
    random_card = random.choice(card_values)
    return random_card

def calculate_score(cards):
    if sum(cards) == 21 and len(cards) == 2:
        return 0
    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        cards.append(1)
    return sum(cards)

player_cards = []
dealer_cards = []
game_over = False

for _ in range(2):
    player_cards.append(deal_card())
    dealer_cards.append(deal_card())

player_score = calculate_score(player_cards)
dealer_score = calculate_score(dealer_cards)

while not game_over:
    player_score = calculate_score(player_cards)
    dealer_score = calculate_score(dealer_cards)
    print(f"Your cards: {player_cards}, current score: {player_score}")
    print(f"Dealer's first card: {dealer_cards[0]}")

    if player_score == 0 or dealer_score == 0 or player_score > 21:
        game_over = True
    else:
        choice = input("Type 'Y' to get another card, 'N' to pass: ").upper()
        if choice == "Y":
            player_cards.append(deal_card())
        elif choice == "N":
            game_over = True
        else:
            game_over = True

while dealer_score != 0 and dealer_score < 17:
    dealer_cards.append(deal_card())
    dealer_score = calculate_score(dealer_cards)

print(f"Dealer's cards: {dealer_cards}")
print(f"Dealer's score: {dealer_score}")
print(compare_scores(dealer_score, player_score))

That's it! You now have a Python code snippet that allows you to play the Blackjack card game. Feel free to modify the code or use it as a starting point for your own projects. Enjoy playing the game!

Back