Skip to Content
Course content

425: Building a Simple Blackjack Card Game

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of building a Blackjack game like organizing a small dinner party where you're the host and the referee. You've got a deck of cards on the table (your data source), a set of rules everyone agreed to (your game logic), and a sequence of events: you deal the cards, the guest decides if they want more, and finally, you compare who got closer to the target without going over. If you mess up the order of these events—like asking the guest if they want another card after you've already declared a winner—the whole night is a disaster.

In Python, we map this party directly to our code. The deck is a list we shuffle; the "dealing" is just popping elements off that list; and the guest's decision-making process is a while loop that only breaks when they "stand" or bust.

Managing the Deck as a Stack

I usually start by defining the deck using a list. Since we don't need to track the physical suit for a basic game, we can just focus on the ranks. Using random.shuffle() is the easiest way to ensure the game isn't predictable. I prefer using a list and pop() because it mimics the real-world action of taking a card off the top of the pile.

import random

def create_deck():
    ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
    # We multiply by 4 to get a full deck of 52 cards
    deck = ranks * 4
    random.shuffle(deck)
    return deck

The Ace Dilemma

Here is where most people trip up: the Ace. In Blackjack, an Ace is worth 11 unless that pushes the player over 21, in which case it becomes a 1. I've found the cleanest way to handle this is to calculate the score assuming all Aces are 11, and then subtract 10 for every Ace we have if the total is too high.

def calculate_score(hand):
    score = 0
    aces = 0
    
    # Mapping face cards to 10 and Ace to 11
    values = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':10, 'Q':10, 'K':10, 'A':11}
    
    for card in hand:
        score += values[card]
        if card == 'A':
            aces += 1
            
    # Adjust for Aces if we're busting
    while score > 21 and aces > 0:
        score -= 10
        aces -= 1
        
    return score

The Player's Decision Loop

The core of the game is a loop. You aren't just asking once; you're asking repeatedly until a specific condition is met. I use a while loop here. It's important to check the score inside the loop so that if the player hits and busts, the game ends immediately without asking them if they want another card.

def play_game():
    deck = create_deck()
    player_hand = [deck.pop(), deck.pop()]
    dealer_hand = [deck.pop(), deck.pop()]
    
    while True:
        player_score = calculate_score(player_hand)
        print(f"Your hand: {player_hand}, score: {player_score}")
        
        if player_score > 21:
            print("Bust! You lose.")
            return
        
        choice = input("Do you want to 'hit' or 'stand'? ").lower()
        if choice == 'hit':
            player_hand.append(deck.pop())
        else:
            break
            
    # Now we handle the dealer's turn...
    print(f"Dealer's hand: {dealer_hand}, score: {calculate_score(dealer_hand)}")

One detail I noticed when building this is that the dealer's logic is actually simpler than the player's. The dealer doesn't get to "choose"—they follow a hard rule: they must keep hitting until their score is at least 17. This removes the need for input() and makes it a simple while loop based on the score.




📋 Practical Task

Implementing the Dealer's Automated Hit Logic

Your current game stops right after the player stands. To make this a functional game, you need to implement the dealer's turn. In Blackjack, the dealer must continue to draw cards (hit) until their total score is 17 or higher.

Modify the play_game function (or create a new function called dealer_turn) to implement the following logic:

  • While the dealer's score is less than 17, they must pop() a card from the deck and add it to their hand.
  • After the dealer finishes hitting, compare the dealer's final score to the player's final score.
  • Print the final result: "Player Wins", "Dealer Wins", or "Push" (a tie).
  • Remember to account for the possibility that the dealer might bust (go over 21), which would result in an automatic player win.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.