(Python) Цикл проверки не обновляет переменную, как ожидалось

Я новичок в изучении Python, всего 6 глав в Начале с Python, 4-е изд. Я пытаюсь закодировать очень упрощенную игру в Блэкджек, но моя текущая проблема заключается в попытке повторить игру, если пользователь захочет (т.е. "Хотите ли вы играть снова?). Когда я ввожу неверный выбор, правильное сообщение проверки Но когда снова появится вопрос, repeat переменная не обновляется с новым вводом, и программа просто завершается, даже если пользователь решил снова играть. Что я делаю неправильно? Я прилагаю всю программу ниже:

# Import the random functionality
import random

# A nifty welcome message
print("Welcome to my Black Jack program! Let's play!\n")

# Define the function for dealing individual cards
def deal_card():
    # Because a deck of cards has face cards and aces, we must assign numerical values to these cards.
    Jack = 10
    Queen = 10
    King = 10
    Ace = 1
    # We make a range from which the random.randrange can choose cards.
    cards = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King]
    # Another variable to define what is being selected.
    drawn_card = cards[random.randrange(1, 13)]
    # The return function stores this data until it is recalled later.
    return drawn_card

# This function gives us the user's card value.
def get_player_score():
    # The player is dealt two cards, so the deal_card function is called twice.
    first_player_card = deal_card()
    second_player_card = deal_card()
    # The value is calculated by adding the two cards.
    sum_player_cards = first_player_card + second_player_card
    print ("Your card total is: ", sum_player_cards, ".", sep="")
    # This primes the feedback loop of "hitting" and "staying"
    choice = int(input("\nWould you like to hit or stay?\nEnter 1 for 'hit' or 2 for 'stay'. "))
    # The player should only have this choice when their card value is not over 21.
    while sum_player_cards < 21:
        if choice == 1:
            new_card = deal_card()
            sum_player_cards = sum_player_cards + new_card
            print ("\nYour new total is: ", sum_player_cards, ".", sep="")
            # Again, if the card value is over 21, their turn is over.
            if sum_player_cards < 21:
                choice = int(input("\nWould you like to to hit or stay? Enter 1 for 'hit' or 2 for 'stay'. "))
        # If the card value is over 21, then the function ends.
        elif choice == 2:
            return sum_player_cards
        # Validation check.
        else:
            print("\nPlease choose 'hit' or 'stay'.")
            choice = int(input("\nAgain, would you like to hit or stay? Enter 1 for 'hit' or 2 for 'stay'. "))
    # If somehow the card value is over 21 at this point, the function ends.
    if sum_player_cards >= 21:
        return sum_player_cards

# Now we determine the dealer's score in much the same way.
def get_dealer_score():
    # Two cards are drawn for the dealer.
    first_dealer_card = deal_card()
    second_dealer_card = deal_card()
    sum_dealer_cards = int(first_dealer_card + second_dealer_card)
    # Here, we must automatically decide for the dealer that if their card value is below 17, they must draw another card.
    while sum_dealer_cards <= 16:
        another_dealer_card = deal_card()
        sum_dealer_cards = sum_dealer_cards + another_dealer_card
    # The previous loop stops when their card value is above 16.
    if sum_dealer_cards > 16:
        print("\nThe dealer's card total is: ", sum_dealer_cards, ".", sep="")
    # The value for the dealer cards is now stored.
    return sum_dealer_cards

# The main function controls the other major functions and determines if the program is repeated.
def main():
    # These new variables allow for the player and dealer card values to be compared.
    player_score = get_player_score()
    dealer_score = get_dealer_score()
    # Now we must define the various end game conditions.
    if player_score > dealer_score and player_score <= 21:
        print("\nYou win!")
    elif dealer_score > player_score and dealer_score <= 21:
        print("\nThe dealer wins!")
    elif dealer_score <= 21 and player_score > 21:
        print("\nYou've gone bust! Dealer wins!")
    elif dealer_score > 21 and player_score <= 21:
        print("\nThe dealer busts! You win!")
    elif dealer_score > 21 and player_score > 21:
        print("\nYou've both gone bust! Nobody wins!")
    elif player_score == dealer_score:
        print("\nPush! Nobody wins!")
    # Prime the variable in order to replay the game.
    repeat = int(input("\nDo you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
    if repeat == 1:
        # This repeats the entire main function, which controls the rest of the program.
        main()
    elif repeat == 2:
        # Here we end the program.
        return repeat
    else:
        # Validation check
        print("Please enter a valid choice.")
        repeat = int(input("Again, do you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))


# And this short line activates the rest of the program.
main()

2 ответа

Решение

Проблема в другом состоянии в этой части кода.

repeat = int(input("\nDo you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
if repeat == 1:
    # This repeats the entire main function, which controls the rest of the program.
    main()
elif repeat == 2:
    # Here we end the program.
    return repeat
else:
    # Validation check
    print("Please enter a valid choice.")
    repeat = int(input("Again, do you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))

Вы ничего не делаете после обновления переменной repeat, поэтому программа просто завершает работу. Возможно, вы захотите удалить этот код из основной функции и добавить его после вызова main(), как показано ниже.

main()
while True:
    repeat = int(input("\nDo you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
    if repeat == 1:
        main()
    elif repeat == 2:
        break
    else:
        print("Please enter a valid choice.")

И измените вашу программу соответственно.

Если вы хотите что-то повторить, используйте петли. Кроме того, чтобы повторить всю программу, не звоните main рекурсивно, но заверните свое тело в петлю. Например, вы можете написать свой код следующим образом:

def main():
    while True:  # infinite loop, programm will repeat until return (or break) is called

        # stuff

        while True:  # another infinite loop
            repeat = int(input("Again, do you want to play again?\nIf 'Yes', enter 1. If 'No', enter 2. "))
            if repeat == 1:
                break  # exit input loop, but not main loop, programm starts over
            elif repeat == 2:
                return # exit main
            else:
               print("Please enter a valid choice.") # invalid input, input loop keeps going
Другие вопросы по тегам