Building a Blackjack Game in Python

Hands-on Mentor
4 min readMar 22, 2023

--

In this tutorial, we will be building a simple Blackjack game using Python. Blackjack is a popular card game that involves trying to get a hand of cards that is as close to 21 as possible without going over.

Step 1: Understanding the Rules of Blackjack

Before we start building the game, let’s first understand the rules of Blackjack. Here are the basic rules:

  • The goal of the game is to get a hand of cards that is as close to 21 as possible without going over.
  • Each player is dealt two cards. The dealer also receives two cards, but one of them is face down.
  • Cards 2 through 10 are worth their face value. Face cards (Jack, Queen, King) are worth 10, and an Ace can be worth 1 or 11.
  • Players can choose to “hit” (receive another card) or “stand” (keep their current hand).
  • If a player’s hand exceeds 21, they “bust” and lose the game.
  • Once all players have finished their turn, the dealer reveals their face-down card and hits until their hand is worth at least 17.
  • If the dealer’s hand exceeds 21, all remaining players win. Otherwise, players with a higher hand than the dealer win.

Step 2: Setting Up the Game

Now that we understand the rules, let’s start building the game. The first thing we need to do is set up the game by creating a deck of cards and shuffling them.

import random
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = ['Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace']
deck = []for suit in suits:
for rank in ranks:
deck.append(f'{rank} of {suit}')
random.shuffle(deck)

In this code, we define two lists: suits and ranks. We then create an empty list called deck and use two nested for loops to create a deck of cards by combining each suit with each rank. We then shuffle the deck using the random.shuffle() function.

Step 3: Dealing Cards

Now that we have a shuffled deck of cards, we need to be able to deal them to the players. We will create a function called deal_cards() that will take a deck and a hand as arguments and add two cards from the deck to the hand.

def deal_cards(deck, hand):
for i in range(2):
card = deck.pop()
hand.append(card)

In this code, we use a for loop to draw two cards from the deck and add them to the hand list. We also remove these cards from the deck using the deck.pop() function.

Step 4: Calculating Hand Value

Now that we can deal cards, we need to be able to calculate the value of a player’s hand. We will create a function called calculate_hand_value() that will take a hand as an argument and return its value.

def calculate_hand_value(hand):
value = 0
has_ace = False
    for card in hand:
rank = card.split()[0]
if rank.isdigit():
value += int(rank)
elif rank in ['Jack', 'Queen', 'King']:
value += 10
elif rank == 'Ace':
has_ace = True
value += 11
if has_ace and value > 21:
value -= 10
return value

In this code, we first initialize a variable called value to 0 and a boolean called has_ace to False. We then loop through each card in the hand and determine its value based on its rank. If the rank is a digit, we add its integer value to value. If the rank is a face card, we add 10 to value. If the rank is an Ace, we set has_ace to True and add 11 to value.

Finally, we check if the hand has an Ace and the value is over 21. If this is the case, we subtract 10 from the value to make the Ace worth 1 instead of 11.

Step 5: Playing the Game

Now that we have all the necessary functions, we can start playing the game. We will create a loop that will continue until the player chooses to “stand” or their hand exceeds 21.

player_hand = []
dealer_hand = []
deal_cards(deck, player_hand)
deal_cards(deck, dealer_hand)
while True:
print(f'Player hand: {player_hand} ({calculate_hand_value(player_hand)})')
print(f'Dealer hand: [{dealer_hand[0]}, <face down>]')
if calculate_hand_value(player_hand) > 21:
print('Player busts!')
break
action = input('Do you want to hit or stand? ') if action.lower() == 'hit':
deal_cards(deck, player_hand)
else:
break
print(f'Player hand: {player_hand} ({calculate_hand_value(player_hand)})')
print(f'Dealer hand: {dealer_hand} ({calculate_hand_value(dealer_hand)})')
if calculate_hand_value(player_hand) > 21:
print('Player busts!')
elif calculate_hand_value(dealer_hand) > 21:
print('Dealer busts! Player wins!')
elif calculate_hand_value(player_hand) > calculate_hand_value(dealer_hand):
print('Player wins!')
elif calculate_hand_value(player_hand) < calculate_hand_value(dealer_hand):
print('Dealer wins!')
else:
print('Push!')

In this code, we first create empty lists for the player and dealer hands, and deal two cards to each. We then start a loop that will continue until the player chooses to “stand” or their hand exceeds 21.

Inside the loop, we print the current hands and ask the player if they want to “hit” or “stand”. If they choose to hit, we deal them another card. If they choose to stand, we break out of the loop.

After the loop ends, we print the final hands and determine the winner based on the hand values.

Step 6: Conclusion

Congratulations, you have now built a simple Blackjack game in Python! This game can be expanded upon by adding more players, allowing for splits, and implementing more complex strategies.

--

--