2024-07-22 : BlackJack Project

YonnyYonny
2 min read
############### Blackjack Project #####################

from art import logo
import random

def deal_card():
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    return(random.choice(cards))

def calculate_score(cards):
    if sum(cards) > 21:
        if 11 in cards:
            for i in range(len(cards)):
                if cards[i] == 11:
                    cards[i] = 1
            score = sum(cards)
        else:
            score = 22
    else:
        score = sum(cards)
    return score

def compare(host_score, user_score):
    if user_score == 22:
        winner = "Host"
    elif host_score == 22:
        winner = "You"
    elif host_score >= user_score:
        winner = "Host"
    elif user_score > host_score:
        winner = "You"
    else:
        winner = "Host"
    return winner

more_game = True
while more_game == True:

    user_cards = []
    user_cards.append(deal_card())
    user_cards.append(deal_card())

    host_cards = []
    host_cards.append(deal_card())
    host_cards.append(deal_card())

    user_score = calculate_score(user_cards)
    host_score = calculate_score(host_cards)

    user_end = False
    host_end = False

    print(logo)

    while user_end == False:
        more_card = input(f"Computer's 1st card is {host_cards[0]}, and your cards are {user_cards}. Your current score is {user_score}.\nDo you want another card? Please type 'y' for yes or 'n' for no. \n")
        if more_card == "y":
            user_cards.append(deal_card())
            user_score = calculate_score(user_cards)

            if user_score > 21:
                user_end = True        
            else:
                user_end = False        
        else:
            user_end = True

    print(f"Your final cards are {user_cards} and your final score is {user_score}.")

    while host_end == False:
       if host_score < 17:
           host_cards.append(deal_card())
           host_score = calculate_score(host_cards)
       else:
           host_end = True

    print(f"The Host's final cards are {host_cards} and its final score is {host_score}.")

    winner = compare(host_score, user_score)

    print(f"The winner is {winner}!")

    play_again = input("Do you want to play again? Please type 'y' for yes or 'n' for no. \n")

    if play_again == "y":
        more_game = True
    else:
        more_game = False
0
Subscribe to my newsletter

Read articles from Yonny directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yonny
Yonny