Blackjack is a popular two-player card game that is played with a deck of standard playing cards around the world in casinos. The main criteria for winning this game are chance and strategy. The challenge of this game is to get as close to 21 points as possible without exceeding them. That is why it is also known as Twenty-One.
In this article, we will learn how to create a simple console-based blackjack game using the if-else statements in Python.
Rules of Blackjack game
Let’s first understand the game’s rules before writing the blackjack console game code.
- In blackjack, each player and dealer receives two cards.
- The player can then choose to “play” (request another card) or “stop” (keep on hold until a new request is made). The goal in this game is to keep the sum of all card points equal to 21 without exceeding it.
- Face cards (i.e. Jack, Queen, and King) are worth 10 points, and Aces can be worth 11 points. If a player has more than 21 points then the player automatically loses the game.
Blackjack Console Game using Python
Now that we have a basic understanding of the rules of the game, let’s start building the game using Python. We will use the following steps to build the game:
- Set up the deck of cards
- Shuffle the deck
- Deal the initial cards
- Allow the player to hit or stand
- Deal the dealer’s cards
- Determine the winner
Implementation of Blackjack Console Game
Here is a detailed step-by-step explanation of the implementation of the blackjack game:
Step 1:
Firstly we import the Python Random module in our code for shuffling.
import random
Step 2:
After successfully importing the random module, we set up the deck by creating two lists: card_categories and cards_list. The deck is then constructed as a list of tuples, each representing a card (i.e. the first element of the tuple is a card, and the second element is categories of cards).
card_categories = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] cards_list = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] deck = [(card, category) for category in card_categories for card in cards_list]
Step 3:
In this step, we create a function called card_values() which takes cards as input and returns the corresponding point of the card. Cards numbered from 2 to 10 have the same points as their number. Face cards like Jack, Queen, and King have 10 points, and Aces have 11 points.
def card_value(card): if card[0] in ['Jack', 'Queen', 'King']: return 10 elif card[0] == 'Ace': return 11 else: return int(card[0])
Step 4:
After creating the function, we will use the random.shuffle() method to shuffle the cards and also after using random.shuffle() method we will need to deal the initial card so that Two hands of cards are distributed: one for the player and one for the dealer. Each hand starts with two cards.
random.shuffle(deck) player_card = [deck.pop(), deck.pop()] dealer_card = [deck.pop(), deck.pop()]
Step 5:
Next, with everything done, let’s write code that allows a player to “play” (i.e., take another card) or “stop” (i.e., stop the game), this code runs until the player’s score reaches 21 or the player chooses to stop.
while True: player_score = sum(card_value(card) for card in player_card) dealer_score = sum(card_value(card) for card in dealer_card) print("Cards Player Has:", player_card) print("Score Of The Player:", player_score) print("\n") choice = input('What do you want? ["play" to request another card, "stop" to stop]: ').lower() if choice == "play": new_card = deck.pop() player_card.append(new_card) elif choice == "stop": break else: print("Invalid choice. Please try again.") continue if player_score > 21: print("Cards Dealer Has:", dealer_card) print("Score Of The Dealer:", dealer_score) print("Cards Player Has:", player_card) print("Score Of The Player:", player_score) print("Dealer wins (Player Loss Because Player Score is exceeding 21)") break
Step 6:
After a player has completed his turn, it is the dealer’s turn to draw cards until he has at least 17 points.
while dealer_score < 17: new_card = deck.pop() dealer_card.append(new_card) dealer_score += card_value(new_card) print("Cards Dealer Has:", dealer_card) print("Score Of The Dealer:", dealer_score) print("\n")
Step 7:
This is the final step in which we have to determine the winner by comparing the player and dealer scores.
- If the player has scored greater than 21 then the player loses the game and the dealer wins the game.
- If the dealer has a score greater than 21 then the dealer loses the game and the player wins the game.
- If the player has scored higher than the dealer then the player wins the game.
- If the dealer has scored higher than the player’s score then the dealer wins the game.
- If both player and dealer have the same score then the game is considered a tie.
if dealer_score > 21: print("Cards Dealer Has:", dealer_card) print("Score Of The Dealer:", dealer_score) print("Cards Player Has:", player_card) print("Score Of The Player:", player_score) print("Player wins (Dealer Loss Because Dealer Score is exceeding 21)") elif player_score > dealer_score: print("Cards Dealer Has:", dealer_card) print("Score Of The Dealer:", dealer_score) print("Cards Player Has:", player_card) print("Score Of The Player:", player_score) print("Player wins (Player Has High Score than Dealer)") elif dealer_score > player_score: print("Cards Dealer Has:", dealer_card) print("Score Of The Dealer:", dealer_score) print("Cards Player Has:", player_card) print("Score Of The Player:", player_score) print("Dealer wins (Dealer Has High Score than Player)") else: print("Cards Dealer Has:", dealer_card) print("Score Of The Dealer:", dealer_score) print("Cards Player Has:", player_card) print("Score Of The Player:", player_score) print("It's a tie.")
Complete Implementation of Code
Here is the complete implementation of the Blackjack Console Game:
import random
card_categories = [ 'Hearts' , 'Diamonds' , 'Clubs' , 'Spades' ]
cards_list = [ 'Ace' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , 'Jack' , 'Queen' , 'King' ]
deck = [(card, category) for category in card_categories for card in cards_list]
def card_value(card):
if card[ 0 ] in [ 'Jack' , 'Queen' , 'King' ]:
return 10
elif card[ 0 ] = = 'Ace' :
return 11
else :
return int (card[ 0 ])
random.shuffle(deck) player_card = [deck.pop(), deck.pop()]
dealer_card = [deck.pop(), deck.pop()]
while True :
player_score = sum (card_value(card) for card in player_card)
dealer_score = sum (card_value(card) for card in dealer_card)
print ( "Cards Player Has:" , player_card)
print ( "Score Of The Player:" , player_score)
print ( "\n" )
choice = input ( 'What do you want? ["play" to request another card, "stop" to stop]: ' ).lower()
if choice = = "play" :
new_card = deck.pop()
player_card.append(new_card)
elif choice = = "stop" :
break
else :
print ( "Invalid choice. Please try again." )
continue
if player_score > 21 :
print ( "Cards Dealer Has:" , dealer_card)
print ( "Score Of The Dealer:" , dealer_score)
print ( "Cards Player Has:" , player_card)
print ( "Score Of The Player:" , player_score)
print ( "Dealer wins (Player Loss Because Player Score is exceeding 21)" )
break
while dealer_score < 17 :
new_card = deck.pop()
dealer_card.append(new_card)
dealer_score + = card_value(new_card)
print ( "Cards Dealer Has:" , dealer_card)
print ( "Score Of The Dealer:" , dealer_score)
print ( "\n" )
if dealer_score > 21 :
print ( "Cards Dealer Has:" , dealer_card)
print ( "Score Of The Dealer:" , dealer_score)
print ( "Cards Player Has:" , player_card)
print ( "Score Of The Player:" , player_score)
print ( "Player wins (Dealer Loss Because Dealer Score is exceeding 21)" )
elif player_score > dealer_score:
print ( "Cards Dealer Has:" , dealer_card)
print ( "Score Of The Dealer:" , dealer_score)
print ( "Cards Player Has:" , player_card)
print ( "Score Of The Player:" , player_score)
print ( "Player wins (Player Has High Score than Dealer)" )
elif dealer_score > player_score:
print ( "Cards Dealer Has:" , dealer_card)
print ( "Score Of The Dealer:" , dealer_score)
print ( "Cards Player Has:" , player_card)
print ( "Score Of The Player:" , player_score)
print ( "Dealer wins (Dealer Has High Score than Player)" )
else :
print ( "Cards Dealer Has:" , dealer_card)
print ( "Score Of The Dealer:" , dealer_score)
print ( "Cards Player Has:" , player_card)
print ( "Score Of The Player:" , player_score)
print ( "It's a tie." )
|
Output: