import random # define 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 create a deck of cards def create_deck(): deck = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] * 4 random.shuffle(deck) return deck # function to calculate the total score of a hand def calculate_total(hand): total = 0 aces = hand.count('A') # add up the face cards and number cards for card in hand: total += CARD_VALUES[card] # adjust for aces if needed while total > 21 and aces: total -= 10 aces -= 1 return total # function to simulate the dealers turn def dealer_turn(deck, dealer_hand): while calculate_total(dealer_hand) < 17: dealer_hand.append(deck.pop()) return dealer_hand # function to print the hands and total score def print_hands(player_hand, dealer_hand, reveal_dealer=False): print(f"Player's hand: {', '.join(player_hand)} | Total: {calculate_total(player_hand)}") if reveal_dealer: print(f"Dealer's hand: {', '.join(dealer_hand)} | Total: {calculate_total(dealer_hand)}") else: print(f"Dealer's hand: {dealer_hand[0]}, ?") # function to check for the winner def check_winner(player_hand, dealer_hand): player_total = calculate_total(player_hand) dealer_total = calculate_total(dealer_hand) if player_total > 21: return "Player busts! Dealer wins." elif dealer_total > 21: return "Dealer busts! Player wins." elif player_total == dealer_total: return "It's a draw!" elif player_total > dealer_total: return "Player wins!" else: return "Dealer wins!" # main game function def play_game(): # initial setup deck = create_deck() player_hand = [deck.pop(), deck.pop()] dealer_hand = [deck.pop(), deck.pop()] # players turn while True: print_hands(player_hand, dealer_hand) choice = input("Do you want to 'hit' or 'stand'? ").lower() if choice == 'hit': player_hand.append(deck.pop()) if calculate_total(player_hand) > 21: print_hands(player_hand, dealer_hand, reveal_dealer=True) print("Player busts! Dealer wins.") return elif choice == 'stand': break else: print("Invalid choice. Please enter 'hit' or 'stand'.") # dealers turn dealer_hand = dealer_turn(deck, dealer_hand) print_hands(player_hand, dealer_hand, reveal_dealer=True) # determine winner print(check_winner(player_hand, dealer_hand)) # play the game if __name__ == "__main__": print("Welcome to the Game of 21!") play_game()