import random
# Function to calculate the total value of a hand
def calculate_hand_value(hand):
value = 0
ace_count = 0
for card in hand:
if card.isdigit():
value += int(card)
elif card in ['J', 'Q', 'K']:
value += 10
elif card == 'A':
value += 11
ace_count += 1
# Adjust the value if there are aces and the total value exceeds 21
while value > 21 and ace_count > 0:
value -= 10
ace_count -= 1
return value
# Function to deal a new card
def deal_card():
cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
return random.choice(cards)
# Function to display the current hands
def display_hands(player_hand, dealer_hand, show_dealer_card):
print("Your hand:", ', '.join(player_hand))
if show_dealer_card:
print("Dealer's hand:", ', '.join(dealer_hand[:1]), "XX")
else:
print("Dealer's hand:", ', '.join(dealer_hand))
# Function to play the game
def play_game():
print("Welcome to Blackjack!")
print("Try to get as close to 21 as possible without going over.")
print("Aces count as 1 or 11.")
player_hand = []
dealer_hand = []
# Deal initial cards
for _ in range(2):
player_hand.append(deal_card())
dealer_hand.append(deal_card())
# Game loop
game_over = False
while not game_over:
player_score = calculate_hand_value(player_hand)
dealer_score = calculate_hand_value(dealer_hand)
display_hands(player_hand, dealer_hand, False)
# Check for blackjack or bust
if player_score == 21 or dealer_score == 21 or player_score > 21:
game_over = True
else:
# Ask the player to hit or stand
choice = input("Type 'h' to hit or 's' to stand: ").lower()
if choice == 'h':
player_hand.append(deal_card())
elif choice == 's':
game_over = True
# Reveal the dealer's hand
display_hands(player_hand, dealer_hand, True)
# Play the dealer's hand
while dealer_score < 17:
dealer_hand.append(deal_card())
dealer_score = calculate_hand_value(dealer_hand)
# Determine the winner
player_score = calculate_hand_value(player_hand)
dealer_score = calculate_hand_value(dealer_hand)
print("Your hand:", ', '.join(player_hand))
print("Dealer's hand:", ', '.join(dealer_hand))
print("Your score:", player_score)
print("Dealer's score:", dealer_score)
if player_score > 21:
print("You went over 21. You lose!")
elif dealer_score > 21:
print("Dealer went over 21. You win!")
elif player_score > dealer_score:
print("You win!")
elif player_score < dealer_score:
print("You lose!")
else:
print("It's a tie!")
# Ask to play again
play_again = input("Do you want to play again? (y/n): ").lower()
if play_again ==