Untitled

 avatar
unknown
plain_text
10 months ago
5.3 kB
43
Indexable
import random

def create_deck():
    """Creates a standard deck of 52 cards."""
    suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
    ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
    deck = []
    for suit in suits:
        for rank in ranks:
            deck.append((rank, suit)) # Stores card as (rank, suit) tuple
    return deck

def shuffle_deck(deck):
    """Shuffles the deck of cards."""
    random.shuffle(deck)
    return deck

def deal_cards(deck, num_cards=7):
    """Deals a specified number of cards to a hand."""
    hand = []
    for _ in range(num_cards):
        if deck: # Ensure there are cards to deal from
            hand.append(deck.pop())
        else:
            print("Deck is empty! Cannot deal more cards.")
            break
    return hand

def get_card_value(card):
    """Returns the numerical value of a card for comparison."""
    rank = card[0] # Access the rank from the card tuple
    if rank in ['Jack', 'Queen', 'King']:
        return 10
    elif rank == 'Ace':
        return 11 # Can be adjusted based on desired Ace value in the game
    else:
        return int(rank)

def play_round(player_hand, cpu_hand, game_deck, cpu_difficulty="easy"): # Added difficulty parameter
    """Plays a single round of the game, including re-dealing."""
    # Check if players need new hands
    if not player_hand:
        print("Your hand is empty! You draw 7 new cards.")
        player_hand.extend(deal_cards(game_deck, 7))
    if not cpu_hand:
        print("CPU's hand is empty! CPU draws 7 new cards.")
        cpu_hand.extend(deal_cards(game_deck, 7))

    if not player_hand or not cpu_hand:
        return

    # Player chooses a card
    print("\nYour hand:")
    for i, card in enumerate(player_hand):
        print(f"{i + 1}. {card[0]} of {card[1]}") # Access rank and suit for display

    while True:
        try:
            choice = int(input("Choose a card to play (enter number): ")) - 1
            if 0 <= choice < len(player_hand):
                player_card = player_hand.pop(choice)
                break
            else:
                print("Invalid choice. Please choose a valid card number.")
        except ValueError:
            print("Invalid input. Please enter a number.")

    # CPU chooses a card based on difficulty
    if cpu_difficulty == "easy":
        # CPU tries to play the lowest card it has
        cpu_card = min(cpu_hand, key=get_card_value)
        cpu_hand.remove(cpu_card) # Remove the chosen card from CPU's hand
    else: # Default or "normal" difficulty (random)
        cpu_card = cpu_hand.pop(random.randint(0, len(cpu_hand) - 1))

    print(f"\nYou played: {player_card[0]} of {player_card[1]}")
    print(f"CPU played: {cpu_card[0]} of {cpu_card[1]}")

    player_value = get_card_value(player_card)
    cpu_value = get_card_value(cpu_card)

    if player_value > cpu_value:
        print("You win the round! You take both cards.")
        player_hand.append(player_card)
        player_hand.append(cpu_card)
    elif cpu_value > player_value:
        print("CPU wins the round! CPU takes both cards.")
        cpu_hand.append(cpu_card)
        cpu_hand.append(player_card)
    else: # Tie
        print("It's a tie! No card exchange this round.")

def check_game_over(player_hand, cpu_hand):
    """Checks if the game is over (one player has all cards)."""
    return not player_hand or not cpu_hand

def calculate_score(hand):
    """Calculates the score (number of cards) in a hand."""
    return len(hand)

def determine_winner(player_score, cpu_score):
    """Determines the winner based on the final scores."""
    if player_score > cpu_score:
        print("You win the game!")
    elif cpu_score > player_score:
        print("CPU wins the game!")
    else:
        print("It's a tie game!")

def jack_apple_game():
    """Main function to run the Jack Apple game."""
    game_deck = create_deck()
    game_deck = shuffle_deck(game_deck)
    player_hand = deal_cards(game_deck, 7)
    cpu_hand = deal_cards(game_deck, 7)

    print("Welcome to Jack Apple!")
    print(f"You start with {calculate_score(player_hand)} cards.")
    print(f"CPU starts with {calculate_score(cpu_hand)} cards.")

    # You can choose the difficulty here: "easy" or "normal"
    difficulty = input("Choose CPU difficulty (easy/normal): ").lower()
    while difficulty not in ["easy", "normal"]:
        difficulty = input("Invalid choice. Please enter 'easy' or 'normal': ").lower()

    while True:
        play_round(player_hand, cpu_hand, game_deck, difficulty) # Pass difficulty to play_round
        print(f"\nYour current cards: {calculate_score(player_hand)}")
        print(f"CPU's current cards: {calculate_score(cpu_hand)}")
        
        if check_game_over(player_hand, cpu_hand):
            print("\nGame Over!")
            player_final_score = calculate_score(player_hand)
            cpu_final_score = calculate_score(cpu_hand)
            print(f"Your final score: {player_final_score}")
            print(f"CPU's final score: {cpu_final_score}")
            determine_winner(player_final_score, cpu_final_score)
            break
        
        input("\nPress Enter to continue to the next round...")

# Run the game
jack_apple_game()
Editor is loading...
Leave a Comment