Python-循环骰子掷骰子游戏重播

问题描述 投票:0回答:2

如果在询问用户是否要再次掷骰子后输入无效响应,我应该如何重播下面的循环?

我无法使它正常工作,而不会弄乱while循环。这是我到目前为止的内容


# Ask the player if they want to play again

another_attempt = input("Roll dice again [y|n]?")

while another_attempt == 'y':

        roll_guess = int(input("Please enter your guess for the roll: "))
        if roll_guess == dicescore :
            print("Well done! You guessed it!")
            correct += 1
            rounds +=1
            if correct >= 4:
        elif roll_guess % 2 == 0:
            print("No sorry, it's", dicescore, "not", roll_guess)
            incorrect += 1
            rounds +=1
        else:
            print("No sorry, it's ", dicescore, " not ", roll_guess, \
                    ". The score is always even.", sep='')
            incorrect += 1
            rounds +=1
        another_attempt = input('Roll dice again [y|n]? ')

if another_attempt == 'n':
    print("""Game Summary""")


else:
    print("Please enter either 'y' or 'n'.")

python loops if-statement while-loop dice
2个回答
0
投票

从底部的while循环中删除if else语句,并在while循环中添加以下内容:

another_attempt = input('Roll dice again [y|n]? ')
     if another_attempt != 'n' or another_attempt == 'y':
        another_attempt = 'y'
     elif another_attempt == 'n':
         print("""Game Summary
===========

You played""", rounds, """games
|--> Number of correct guesses:""", correct, """
|--> Number of incorrect guesses:""", incorrect, """
Thanks for playing!""")
         exit()



0
投票

我建议您通过两个while循环来完成,并使用函数使代码逻辑更清晰。

def play_round():
    # Roll dice
    # Compute score
    # Display dice
    # Get roll guess

def another_attempt():
    while True:
        answer = input("Roll dice again [y|n]?")
        if answer == 'y':
            return answer
        elif answer == 'n':
            return answer
        else:
            print("Please enter either 'y' or 'n'.")

def play_game():
    while another_attempt() == 'y':
        play_round()
    # Print game summary
© www.soinside.com 2019 - 2024. All rights reserved.