Building a Blackjack Game in Python Project 12

Building a Blackjack Game in Python




Are you a fan of card games and looking to dive into the world of Python programming? Look no further! In this article, we'll explore how to build a simple yet engaging Blackjack game using Python.

Introduction:

Blackjack, also known as 21, is a popular casino game where the goal is to have a hand value that is closer to 21 than the dealer's hand, without exceeding 21. Let's take a closer look at the code you've written and how it brings this classic game to life.


The game starts with importing the necessary modules, including the random module for shuffling the deck of cards and the art module for displaying the game logo. The deck of cards is represented by a list called cards, which contains the values of each card. Ace is assigned a value of 11, and the face cards (King, Queen, Jack) are assigned a value of 10.


The deal_card() function selects a random card from the cards list and returns it. The calculate_score() function takes a list of cards as input and calculates the score by summing up the values of the cards. It also includes some additional logic to handle the special cases of a blackjack (an ace and a 10-value card) and the value of an ace when the score exceeds 21.


The compare() function compares the scores of the user and the computer and determines the winner based on various conditions, such as blackjack, exceeding 21, or having a higher score.


In the play_game() function, the game initializes by dealing two cards each to the user and the computer. The user's and computer's scores are calculated and displayed. The game then proceeds in a loop, where the user is prompted to draw another card or stop. If the user's score exceeds 21 or a blackjack is achieved, the loop ends.


Next, the computer starts playing by automatically drawing cards until its score reaches 17 or above. Finally, the user's and computer's final cards and scores are displayed, and the compare() function is called to determine the winner.


To enhance the user experience, the game allows for multiple rounds by asking the user if they want to restart the game. The console is cleared, and a new game begins with the familiar game logo displayed.


Overall, this Python Blackjack game provides an enjoyable and interactive experience. It demonstrates the use of functions, loops, conditional statements, and the random module to create a complete game flow. You can further expand the game by adding features like betting, multiple players, or a graphical user interface (GUI).

Source code:




import random
from replit import clear
import art

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
# Create a deal_card() function that uses the List below to *return* a random card.
#11 is the Ace.
def deal_card():
  for _ in range(1):
    new_card = random.choice(cards)
  return new_card
#Create a function called calculate_score() that takes a List of cards as input 
#and returns the score. 
#use sum() function.
def calculate_score(card_list):
  """Take a list of cards and return sum of cards"""
  # Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
  if sum(card_list) == 21 and len(card_list) == 2:
    return 0
  #Inside calculate_score() check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1. You might need to look up append() and remove().
  if sum(card_list) > 21 and 11 in card_list:
    card_list.remove(11)
    card_list.append(1)
  return sum(card_list)
# Create a function called compare() and pass in the user_score and computer_score. If the computer and user both have the same score, then it's a draw. If the computer has a blackjack (0), then the user loses. If the user has a blackjack (0), then the user wins. If the user_score is over 21, then the user loses. If the computer_score is over 21, then the computer loses. If none of the above, then the player with the highest score wins.
def compare(userScore,computerScore):
  #Bug fix. If you and the computer are both over, you lose.
  if userScore > 21 and computerScore > 21:
    return "You went over. You lose 😤"
  if userScore == computerScore:
    return "It's a draw 😊"
  elif computerScore == 0:
    return "You lose"
  elif userScore == 0:
    return "You wins with a blackJack"
  elif userScore > 21:
    return "You over 21 You lose 🥴"
  elif computerScore > 21:
    return "Computer score over 21, Computer lose : {computer_cards}"
  elif userScore > computerScore:
    return "Your score higher than opponent, You wins"
  else: 
    return "Computer score higher, Computer wins"

def play_game():
  print(art.logo)
  user_cards = []
  computer_cards = []
  #Deal the user and computer 2 cards each using deal_card()
  for _ in range(2):
    user_cards.append(deal_card())
    computer_cards.append(deal_card())
    
  should_end = False
  #The score will need to be rechecked with every new card drawn and the checks in Hint 9 need to be repeated until the game ends.
  while not should_end:
    # Call calculate_score(). If the computer or the user has a blackjack (0) or if the user's score is over 21, then the game ends.
    user_score = calculate_score(user_cards)
    computer_score = calculate_score(computer_cards)
    print(f"your cards are {user_cards} , Current score = {user_score}")
    print(f"Computer first card {computer_cards[0]} ")
    
    if user_score == 0 or computer_score == 0 or user_score > 21:
      should_end = True
    else:
      # If the game has not ended, ask the user if they want to draw another card. If yes, then use the deal_card() function to add another card to the user_cards List. If no, then the game has ended.
      draw_another_card = input("Type 'y' to draw another card or 'n' to handup:or type 'new' to start new game:  ").lower()
      if draw_another_card == "y":
        user_cards.append(deal_card())
      else:
        should_end = True
    
    
  #Once the user is done, it's time to let the computer play. The computer should keep drawing cards as long as it has a score less than 17.
  while computer_score != 0 and computer_score < 17:
    computer_cards.append(deal_card())
    computer_score=calculate_score(computer_cards)
  
  print(f"Your final cards: {user_cards} = {user_score}")  
  print(f"Computer final cards: {computer_cards} = {computer_score}")  
  print(compare(userScore=user_score,computerScore=computer_score))
# Ask the user if they want to restart the game. If they answer yes, clear the console and start a new game of blackjack and show the logo from art.py.
while input("Do you want to play a game Blackjack. type 'y' or 'n'") == 'y':
  clear()
  play_game()
#/////////// art.py file
logo = """
.------.            _     _            _    _            _    
|A_  _ |.          | |   | |          | |  (_)          | |   
|( \/ ).-----.     | |__ | | __ _  ___| | ___  __ _  ___| | __
| \  /|K /\  |     | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ /
|  \/ | /  \ |     | |_) | | (_| | (__|   <| | (_| | (__|   < 
`-----| \  / |     |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\
      |  \/ K|                            _/ |                
      `------'                           |__/           
"""

  


Next Post Previous Post