import random # Initialize the deck suits = ['♠', '♣', '♥', '♦'] ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'] deck = [(rank, suit) for suit in suits for rank in ranks] # Function to deal a hand of cards def deal_hand(num_cards): hand = random.sample(deck, num_cards) for card in hand: deck.remove(card) return hand # Function to check if a move is valid def is_valid_move(card, pile_card): return card[0] == pile_card[0] or card[1] == pile_card[1] or card[0] == '8' # Function to play the game def play_game(): # Deal initial hands player_hand = deal_hand(8) computer_hand = deal_hand(8) pile = [random.choice(deck)] # Loop until someone wins while True: print("Player's hand:", player_hand) print("Top of the pile:", pile[-1]) # Player's turn valid_move = False while not valid_move: player_choice = input("Your turn. Choose a card to play: ") player_choice = player_choice.upper() # Check if the player wants to draw or quit if player_choice == 'DRAW': player_hand.extend(deal_hand(1)) print("You drew a card.") continue elif player_choice == 'QUIT': print("You quit the game.") return # Check if the player's move is valid valid_cards = [card for card in player_hand if is_valid_move(card, pile[-1])] if player_choice not in valid_cards: print("Invalid move. Try again.") continue for card in player_hand: if card == player_choice: pile.append(card) player_hand.remove(card) valid_move = True break elif card[0] == '8': pile.append(card) player_hand.remove(card) valid_move = True break if len(player_hand) == 0: print("Congratulations! You won!") return # Computer's turn valid_move = False for card in computer_hand: if is_valid_move(card, pile[-1]): pile.append(card) computer_hand.remove(card) valid_move = True break if not valid_move: computer_hand.extend(deal_hand(1)) print("Computer drew a card.") if len(computer_hand) == 0: print("Sorry, you lost. Better luck next time!") return # Start the game play_game()