Python while循环想用Y/N选项重复或退出游戏

2024-04-25 19:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我做了一个简单的战舰游戏。在游戏的最后,无论它以失败的胜利告终,我希望用户能够再次玩或退出。这段代码打算接受一个输入,确保它是“y”或“n”,然后将控制初始while循环的变量设置为false(如果输入为“n”)。不知何故,当循环再次运行时,无论我做什么,它都会将输入设置回“y”—我已经使用print语句进行了检查,它肯定会正确地设置为“n”,但是如果我在while循环之后立即再次打印值,那么它就是“y”。while循环会再次运行,而不管输入是什么。如何修复它,使“n”正确退出循环?在

restart = "y"
while restart[0] not in ("n", "N"):
    def play_again():
       print ("")
       restart = input("Enter y to play again or n to quit: ")
       print ("")
       try: 
            x = str(restart)
       except ValueError:
            print ("Please enter y or n.")
            print ("")
            play_again()
       else:
            if str(restart) != "y" and str(restart) != "n":
                print ("Please enter y or n.")
                print ("")
                play_again()
    *game*
    play_again()

Tags: orto代码用户false游戏playrestart
1条回答
网友
1楼 · 发布于 2024-04-25 19:26:42
def restart_game():
    try:
        restart = input("Enter y to play again or n to quit: ")
        if restart == "y":
            return True
        if restart == "n":
            return False
        raise ValueError
    except ValueError:
        print ("Please enter y or n.")
        return True


while True:
    print 'Playing the game ...'
    if not restart_game(): break

相关问题 更多 >

    热门问题