How to Code a Simple Blackjack Game in Python

cards-166440_960_720

One of the best things about programming is you get to create your own games. Game development can be extremely profitable these days, especially when you make titles for Android or iPhone. Even with a $0.99 sale per download, game developers with good products can make sizable returns. Apart from the revenues from downloads, games also get profits from brands that are willing to pay via advertisement partnerships.

If you already have the “framework” for a particular game, you can often reuse it and make revisions that fit a company’s requirements. Take for example casino games. These games aren’t very difficult to develop given the fact that most of them function in similar ways. There are thousands of different slot titles available online but for the most part they only differ by design – all slot games are usually controlled by using one button.

The same goes for card games such as Blackjack. No matter what the brand or type, all variations of Blackjack use a deck of cards and a dealer. Even Live Blackjack, which was popularized by digital portal Betfair uses a code similar to the ones offered by other online games. The only addition that is present in Live Blackjack is that players get to interact with actual live dealers during games. Once you know how to code a simple Blackjack game, you’ll be able to make hundreds of variations of the game depending on what you want to create.

That being said, coding a Blackjack game is quite simple.

In this article, let’s build a text-based Blackjack engine that allows players to play with a dealer. The logic behind the coding will be a bit complex but you’ll be able to gain valuable experience on how to design card-based casino games once you get the hang of it.

Coding the Blackjack Game

The player and the dealer will receive two cards from a shuffled deck each round. In this case, let’s use a single deck although real casinos use 6 decks at a time.

———————–
from random import shuffle
# define the card ranks, and suits
ranks = [_ for _ in range(2, 11)] + [‘JACK’, ‘QUEEN’, ‘KING’, ‘ACE’]
suits = [‘SPADE’, ‘HEART ‘, ‘DIAMOND’, ‘CLUB’]

def get_deck():
“””Return a new deck of cards.”””

return [[rank, suit] for rank in ranks for suit in suits]

# get a deck of cards, and randomly shuffle it
deck = get_deck()
shuffle(deck)
—————–

What we did was lay out the suits and ranks of the cards with lists, and then declared get_deck(), which constructs the deck using a list comprehension. Then, we utilized Python’s random library, which has a lot of functions used in generating randomness. In this case, we used shuffle, which randomizes the order of the deck.

With these in place, we can now deal the player and dealer’s first two cards.

——————
# boolean variable that indicates whether player has gone bust yet
player_in = True

# issue the player and dealer their first two cards
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
——————

Next, you need to write a code in order to proceed with dealing a hand.

—————–

from random import shuffle
# define the card ranks, and suits
ranks = [_ for _ in range(2, 11)] + [‘JACK’, ‘QUEEN’, ‘KING’, ‘ACE’]
suits = [‘SPADE’, ‘HEART ‘, ‘DIAMOND’, ‘CLUB’]
def get_deck():
“””Return a new deck of cards.”””
return [[rank, suit] for rank in ranks for suit in suits]

# get a deck of cards, and randomly shuffle it
deck = get_deck()
shuffle(deck)
# issue the player and dealer their first two cards
player_hand = [deck.pop(), deck.pop()]
——————

Next, we need to write code that accepts a list containing the cards of the hand. First, we write a helper function that takes a card and then returns its value to the scheme of the code we wrote above. Let’s count Aces as 11. We then plot this function over the hand and store the values as tmp_value.

Then, we need to count up the total number of aces in the hand and check if the value is less than or equal to 21. If there’s a second ace in the hand, we subtract 11 and then check again.

——————
def card_value(card):
“””Returns the integer value of a single card.”””

rank = card[0]
if rank in ranks[0:-4]:
return int(rank)
elif rank is ‘ACE’:
return 11
else:
return 10

def hand_value(hand):
“””Returns the integer value of a set of cards.”””

# Naively sum up the cards in the deck.
tmp_value = sum(card_value(_) for _ in hand)
# Count the number of Aces in the hand.
num_aces = len([_ for _ in hand if _[0] is ‘ACE’])

# Aces can count for 1, or 11. If it is possible to bring the value of
#the hand under 21 by making 11 -> 1 substitutions, do so.
while num_aces > 0:

if tmp_value > 21 and ‘ACE’ in ranks:
tmp_value -= 10
num_aces -= 1
else:
break
# Return a string and an integer representing the value of the hand. If
# the hand is bust, return 100.
if tmp_value < 21:
return [str(tmp_value), tmp_value]
elif tmp_value == 21:
return [‘Blackjack!’, 21]
else:
return [‘Bust!’, 100]
——————

Next, we tap into the gameplay logic. We need to take into account whether or not the player stays or hits. The game also needs to determine if the hand is a bust. As long as the player’s hand is not a bust, the player can keep hitting. If the player stays, the value of player_in must change to false so the game can move on to the dealer.

——————
while player_in:
# Display the player’s current hand, as well as its value.
current_score_str = ”’\nYou are currently at %s\nwith the hand %s\n”’
print current_score_str % (hand_value(player_hand)[0], player_hand)
# If the player’s hand is bust, don’t ask them for a decision.
if hand_value(player_hand)[1] == 100:
break

if player_in:
response = int(raw_input(‘Hit or stay? (Hit = 1, Stay = 0)’))
# If the player asks to be hit, take the first card from the top of
# deck and add it to their hand. If they ask to stay, change
# player_in to false, and move on to the dealer’s hand.
if response:
player_in = True
new_player_card = deck.pop()
player_hand.append(new_player_card)
print ‘You draw %s’ % new_player_card
else:
player_in = False
——————

At this point, we have to calculate the score of both dealer and player. If the player’s hand is not a bust, the screen must show the dealer’s current hand. If the dealer’s hand is less than 17, the dealer can hit.

——————
player_score_label, player_score = hand_value(player_hand)
dealer_score_label, dealer_score = hand_value(dealer_hand)

if player_score <= 21:
dealer_hand_string = ”’\nDealer is at %s\nwith the hand %s\n”’
print dealer_hand_string % (dealer_score_label, dealer_hand)
else:
print “Dealer wins.”

while hand_value(dealer_hand)[1] < 17:
new_dealer_card = deck.pop()
dealer_hand.append(new_dealer_card)
print ‘Dealer draws %s’ % new_dealer_card
——————

The round is almost finished. What only needs to be checked is the final score of both the player and dealer. To do that, we have to get the label and number for the scores. Then, we lay out the possible end scenarios and ask which of them satisfies the results.

——————
dealer_score_label, dealer_score = hand_value(dealer_hand)

if player_score < 100 and dealer_score == 100:
print ‘You beat the dealer!’
elif player_score > dealer_score:
print ‘You beat the dealer!’
elif player_score == dealer_score:
print ‘You tied the dealer, nobody wins.’
elif player_score < dealer_score:
print “Dealer wins!”
——————

That’s it! With this basic Blackjack code, you can create different variations of the game.

Leave a Reply

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