import random def create_deck(): """Create a deck of cards.""" ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] deck = [{'rank': rank, 'suit': suit} for rank in ranks for suit in suits] random.shuffle(deck) return deck def calculate_hand_value(hand): """Calculate the value of a hand.""" value = 0 num_aces = 0 for card in hand: if card['rank'] in ['K', 'Q', 'J']: value += 10 elif card['rank'] == 'A': num_aces += 1 value += 11 else: value += int(card['rank']) # Adjust the value for aces while value > 21 and num_aces: value -= 10 num_aces -= 1 return value def display_hand(hand, hide_first_card=False): """Display the cards in a hand.""" display = [] for i, card in enumerate(hand): if i == 0 and hide_first_card: display.append("Hidden Card") else: display.append(f"{card['rank']} of {card['suit']}") return display def main(): deck = create_deck() player_hand = [deck.pop(), deck.pop()] dealer_hand = [deck.pop(), deck.pop()] player_turn = True while True: if player_turn: print("Player's turn:") print("Your hand:", display_hand(player_hand)) print("Dealer's hand:", display_hand(dealer_hand, hide_first_card=True)) print("Your total:", calculate_hand_value(player_hand)) action = input("Do you want to (h)it or (s)tand? ").lower() if action == 'h': player_hand.append(deck.pop()) if calculate_hand_value(player_hand) > 21: print("Busted! You went over 21. You lose.") break elif action == 's': player_turn = False else: print("Invalid input. Please enter 'h' or 's'.") else: print("\nDealer's turn:") print("Your hand:", display_hand(player_hand)) print("Dealer's hand:", display_hand(dealer_hand)) print("Dealer's total:", calculate_hand_value(dealer_hand)) while calculate_hand_value(dealer_hand) < 17: dealer_hand.append(deck.pop()) print("Dealer's final hand:", display_hand(dealer_hand)) if calculate_hand_value(dealer_hand) > 21: print("Dealer busted! You win.") elif calculate_hand_value(dealer_hand) >= calculate_hand_value(player_hand): print("Dealer wins.") else: print("You win!") break if __name__ == "__main__": main()