GITHUB REPO | FOLLOW ME ON -> TWITTER | LINKEDIN

Draw or Pass: A Fun Blackjack Game in Python from Scratch

Do you like to play a fun and interesting game in your free time? If yes, then you must check out this exciting Blackjack game coded in Python. In the following article, we will go over the code, features, and techniques used to develop the program step by step.

Al-Junaed Islam

--

Photo by Sam Goh on Unsplash

Step-by-Step Code Explanation

The first thing we need to do is set up our Python Blackjack Game. Open up your preferred code editor, create a new file, and save it with a descriptive name such as “blackjack.py”. Also, create another file which will be used as modules and let's name itblackjack_art.py

blackjack_art.py

logo = """
_ _ _ _ _
| | | | | | (_) | |
| |__ | | __ _ ___| | ___ __ _ ___| | __
| '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ /
| |_) | | (_| | (__| <| | (_| | (__| <
|_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\
_/ |
|__/
"""

win = """
__ __ __ ___ _
\ \ / /__ _ _ \ \ / (_)_ __ | |
\ V / _ \| | | | \ \ /\ / /| | '_ \| |
| | (_) | |_| | \ V V / | | | | |_|
|_|\___/ \__,_| \_/\_/ |_|_| |_(_)
"""

lose = """
__ __ _ _
\ \ / /__ _ _ | | ___ ___ ___| |
\ V / _ \| | | | | | / _ \/ __|/ _ \ |
| | (_) | |_| | | |__| (_) \__ \ __/_|
|_|\___/ \__,_| |_____\___/|___/\___(_)
"""

draw = """
____ ____ ___ ___ _
| _ \| _ \ / \ \ / / | |
| | | | |_) | / _ \ \ /\ / /| | |
| |_| | _ < / ___ \ V V / |_|_|
|____/|_| \_\/_/ \_\_/\_/ (_|_)
"""

blackjack.py

First, the required libraries, i.e., random and os, and the ASCII art are imported. Then, we initialize a dictionary containing all the cards with their values. After initializing all the functions, we define clear() to clear the console when needed and call the blackjack() function to start the code.

import random, os, art

cards = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "A": [1, 11], "K": 10, "Q": 10, "J": 10}

#######################
# card_distribution()
# print_cards()
# blackjack()
#######################

clear = lambda: os.system('cls')

blackjack()

In the card_distribution() function, we randomly select a card and add its value to the score. This function takes user or pc’s score as argument and returns the card and total score. If the selected card is ‘A,’ then we check if adding its value is going to make the score less than or equal to 21 or not. If yes, we add 11; otherwise, we add 1.

def card_distribution(score):
random_card = random.choice(list(cards.keys()))
if score < 11 and random_card == "A":
score += cards[random_card][1]
elif score >= 11 and random_card == "A":
score += cards[random_card][0]
else:
score += cards[random_card]

return random_card, score

The print_cards() function is used to display the user’s and PC’s cards and scores. We pass in the parameters whether it’s the final round or not, the user’s and PC’s scores, and the cards in the user’s and PC’s hands.

def print_cards(final, user_score, pc_score, user_inhand, pc_inhand):
print()
if final:
print(f"Your Final Cards: {user_inhand}, Current Score: {user_score}")
print(f"PC's Final Cards: {pc_inhand}, PC's Score: {pc_score}")
else:
print(f"Your Cards: {user_inhand}, Current Score: {user_score}")
print(f"PC's Card: {pc_inhand[0]}")

The compare_score() function compares the user’s and PC’s score and decides who wins based on the predefined conditions. This function takes the user’s score and pc’s score as parameter and display the respective art as message corresponding to the results.

def compare_score(user, pc):
if user == 21 and pc == 21 or user == pc:
print(art.draw)
elif pc == 21:
print("PC got the Blackjack")
print(art.lose)
elif user == 21:
print("You got the Blackjack")
print(art.win)
elif user > 21:
print("You went over. PC Win")
print(art.lose)
elif pc > 21:
print("PC went over")
print(art.win)
elif user > pc:
print(art.win)
else:
print("PC Win")
print(art.lose)

The blackjack() function starts by displaying the game’s logo and initializing the user’s and PC’s score and their hands. We start the game by dealing two cards to user and pc and display them using the print_cards() function.

def blackjack():
print(art.logo)
user_inhand = []
user_score = 0
pc_inhand = []
pc_score = 0

should_play = True
while should_play:
for _ in range(2):
user_card, user_score = card_distribution(user_score)
user_inhand.append(user_card)

pc_card, pc_score = card_distribution(pc_score)
pc_inhand.append(pc_card)

print_cards(False, user_score, pc_score, user_inhand, pc_inhand)

We then ask the user whether they want to hit or pass, and we deal the cards to them based on their decision. The while loop is used to determine whether the user’s score is less than 21 and whether the user wishes to hit or pass. If the user hits, we deal another card to them; if they pass, we go to the PC’s turn. We deal cards to the PC till their score exceeds 16. Then print the updated card of user along with score.

        while user_score < 21:
choice = input("Type 'Y' to HIT another card or 'N' to PASS - ").lower()
if choice == 'y':
user_card, user_score = card_distribution(user_score)
user_inhand.append(user_card)
else:
while pc_score <= 16:
pc_card, pc_score = card_distribution(pc_score)
pc_inhand.append(pc_card)
break
print_cards(False, user_score, pc_score, user_inhand, pc_inhand)

When the user selects pass, we use the print_cards() method to display the final cards on user’s and pc’s hand and scores of both, and the compare_score() function to compare their scores and print the result.

        print_cards(True, user_score, pc_score, user_inhand, pc_inhand)

compare_score(user_score, pc_score)

After that, we ask the user whether they want to play another round or not. If yes, we clear the console and start another round. If not, we terminate the game by setting a False flag.

        round_choice = input("Type 'Y' to play another round or type 'N' to exit - ").lower()        
if round_choice == 'y':
clear()
blackjack()
else:
should_play = False
print("Thank you for playing the game. Hope you liked it. Goodbye!")

Full code

Sample Run

blackjack game sample run
Sample Run

Features:

Program’s Features

  • The game’s code is easy to understand and has detailed explanations of each function and code snippet.
  • The game uses the Art library to display different messages related to the game.
  • The game is engaging and is an excellent source of entertainment.
  • User can hit (draw a card) or pass (end their turn)

Python Concepts and Techniques Used

  • Dictionaries: We used a dictionary to store all the cards and their respective values.
  • Functions: We used multiple functions to perform specific tasks like dealing the cards, comparing the scores, and displaying the cards.
  • Loops: We used while loops to check the user’s choice and deal cards accordingly and to deal cards to the PC until their score is greater than 16.
  • Conditional Statements: We used conditional statements to check whether the user’s score is less than 21 and whether the user wants to hit or pass.
  • Recursion: We used a recursion so that user can play unlimited round of this game.

In this project, we learnt how to use Python to develop a command-line-based Blackjack game. For building a functional game, we used Python concepts like dictionaries, conditional statements, loops, and functions.

Ready to Level Up? Complete These Challenges

Now that you’ve learned how to create a blackjack game, it’s time to put your skills to the test! Here are some fun challenges to help you take your Python knowledge to the next level. Are you ready to level up? Let’s go!

  1. Modify the game to add more players and keep track of their scores.
  2. Implement a betting system where players can bet before starting a game and the winner gets the pot.
  3. Modify the game to use a deck of cards instead of a single deck.

Please let me know if you complete these tasks. I’d would like to see them.

This article is a part of my Python Project Journal. To learn more about my journey in learning Python and to see my other projects, check out this project journal. Thank you!

--

--