import random # Define the card ranks, suits, and values ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] 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} # Define the player and dealer classes class Player: def __init__(self, name): self.name = name self.hand = [] def add_card(self, card): self.hand.append(card) def get_hand_value(self): hand_value = sum(values[card.rank] for card in self.hand) num_aces = sum(1 for card in self.hand if card.rank == 'A') while hand_value > 21 and num_aces: hand_value -= 10 num_aces -= 1 return hand_value def show_hand(self, hide_first_card=False): print(f"{self.name}'s hand:") for i, card in enumerate(self.hand): if i == 0 and hide_first_card: print("Hidden Card") else: print(f"{card.rank} of {card.suit}") print(f"Total Value: {self.get_hand_value()}") class Card: def __init__(self, rank, suit): self.rank = rank self.suit = suit # Define the deck class class Deck: def __init__(self): self.cards = [Card(rank, suit) for rank in ranks for suit in suits] self.shuffle() def shuffle(self): random.shuffle(self.cards) def deal_card(self): return self.cards.pop() # Define the game functions def initial_deal(deck, player, dealer): player.add_card(deck.deal_card()) dealer.add_card(deck.deal_card()) player.add_card(deck.deal_card()) dealer.add_card(deck.deal_card()) def player_turn(deck, player): while player.get_hand_value() < 21: player.show_hand() choice = input("Hit or Stand? (h/s): ").lower() if choice == 'h': player.add_card(deck.deal_card()) elif choice == 's': break def dealer_turn(deck, dealer): while dealer.get_hand_value() < 17: dealer.add_card(deck.deal_card()) def check_winner(player, dealer): player_value = player.get_hand_value() dealer_value = dealer.get_hand_value() if player_value > 21: return "Dealer wins! Player busted." elif dealer_value > 21: return "Player wins! Dealer busted." elif player_value > dealer_value: return "Player wins!" elif dealer_value > player_value: return "Dealer wins!" else: return "It's a tie!" # Main game logic def main(): print("Welcome to Blackjack!") player_name = input("Enter your name: ") player = Player(player_name) dealer = Player("Dealer") deck = Deck() while True: deck.shuffle() player.hand.clear() dealer.hand.clear() initial_deal(deck, player, dealer) player.show_hand() dealer.show_hand(hide_first_card=True) player_turn(deck, player) if player.get_hand_value() > 21: print("Player busted!") else: dealer_turn(deck, dealer) dealer.show_hand() print(check_winner(player, dealer)) play_again = input("Do you want to play again? (y/n): ").lower() if play_again != 'y': break if __name__ == "__main__": main()