import random # Card values card_values = { '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 11 } # Function to deal a card def deal_card(): """Return a random card from the deck.""" card = random.choice(list(card_values.keys())) return card # Function to calculate hand total def calculate_hand_total(hand): """Calculate the total value of a hand of cards, adjusting for Aces.""" total = sum(card_values[card] for card in hand) ace_count = hand.count('A') # Adjust for aces (if total > 21, convert Aces from 11 to 1) while total > 21 and ace_count: total -= 10 ace_count -= 1 return total # Function to display the hand def display_hand(player, hand, total): """Display the current hand and its total.""" print(f"{player}'s hand: {', '.join(hand)} (Total: {total})") # Function for the player's turn def player_turn(player_hand): """Handle the player's turn.""" while True: display_hand("Player", player_hand, calculate_hand_total(player_hand)) if calculate_hand_total(player_hand) > 21: print("You busted! Your total exceeds 21.") return False # Player lost action = input("Do you want to 'hit' or 'stand'? ").lower() if action == 'hit': player_hand.append(deal_card()) elif action == 'stand': return True # Player stands # Function for the dealer's turn def dealer_turn(dealer_hand): """Handle the dealer's turn.""" while calculate_hand_total(dealer_hand) < 17: display_hand("Dealer", dealer_hand, calculate_hand_total(dealer_hand)) print("Dealer hits.") dealer_hand.append(deal_card()) display_hand("Dealer", dealer_hand, calculate_hand_total(dealer_hand)) return calculate_hand_total(dealer_hand) <= 21 # Dealer didn't bust # Function to play the game def play_game(): """Play a full round of the game.""" # Deal initial cards to player and dealer player_hand = [deal_card(), deal_card()] dealer_hand = [deal_card(), deal_card()] # Display initial hands (dealer's second card is hidden) print(f"Dealer's hand: {dealer_hand[0]}, ?") display_hand("Player", player_hand, calculate_hand_total(player_hand)) # Player's turn if not player_turn(player_hand): return "Dealer wins!" # Player busted # Dealer's turn dealer_total = calculate_hand_total(dealer_hand) if not dealer_turn(dealer_hand): return "Player wins!" # Dealer busted # Compare totals to determine the winner player_total = calculate_hand_total(player_hand) if player_total > dealer_total: return "Player wins!" elif player_total < dealer_total: return "Dealer wins!" else: return "It's a draw!" # Main loop for multiple rounds def main(): """Main game loop for multiple rounds.""" print("Welcome to the Game of 21!") while True: result = play_game() print(result) play_again = input("Do you want to play again? (yes/no): ").lower() if play_again != 'yes': print("Thanks for playing! Goodbye.") break # Start the game if __name__ == "__main__": main()