import random # Card values card_values = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 11 } # Function to create a deck`` def create_deck(): deck = [] for suit in ['Hearts', 'Diamonds', 'Clubs', 'Spades']: for rank in card_values: deck.append(f'{rank} of {suit}') random.shuffle(deck) return deck # Function to calculate hand value def calculate_hand_value(hand): value = sum(card_values[card.split()[0]] for card in hand) # Adjust for Ace being 1 or 11 num_aces = sum(1 for card in hand if card.split()[0] == 'A') while value > 21 and num_aces: value -= 10 num_aces -= 1 return value # Function to deal a hand def deal_hand(deck): return [deck.pop(), deck.pop()] # Function to display a hand def display_hand(hand, is_dealer=False): if is_dealer: print(f"Dealer's hand: [Hidden] {hand[1]}") else: print(f"Your hand: {', '.join(hand)}") # Function to play the game def play_blackjack(): print("Welcome to Blackjack!") deck = create_deck() # Deal hands player_hand = deal_hand(deck) dealer_hand = deal_hand(deck) # Display hands display_hand(player_hand) display_hand(dealer_hand, is_dealer=True) # Player's turn while calculate_hand_value(player_hand) < 21: action = input("Do you want to 'hit' or 'stand'? ").lower() if action == 'hit': player_hand.append(deck.pop()) display_hand(player_hand) elif action == 'stand': break # Calculate final value of player's hand player_value = calculate_hand_value(player_hand) if player_value > 21: print(f"Your final hand value is {player_value}. You busted!") return # Dealer's turn print(f"\nDealer reveals the hidden card: {dealer_hand[0]}") while calculate_hand_value(dealer_hand) < 17: print("Dealer hits.") dealer_hand.append(deck.pop()) display_hand(dealer_hand, is_dealer=True) # Final dealer value dealer_value = calculate_hand_value(dealer_hand) print(f"Dealer's final hand value: {dealer_value}") # Determine the winner if dealer_value > 21: print("Dealer busted! You win!") elif player_value > dealer_value: print("You win!") elif player_value < dealer_value: print("Dealer wins!") else: print("It's a tie!") # Run the game if __name__ == '__main__': play_blackjack()