简体   繁体   English

猜数字游戏 python(让游戏每次都要求玩)

[英]Number guessing game python (make the game ask to play every time)

import random

def game():
    number = random.randint(0, 10)
    guess = 0
    print("Guess a number from 0-10:")
    while number != guess:
        try:
            guess = int(input(""))
            if number != guess:
                print("you haven't guessed the number, keep trying")
            else:
                print("You guessed it!")
                break
        except ValueError:
            print("Please enter an integer")

game()

choose = input("Would you like to play again?\n")
while choose == "yes":
    game()
    if choose == "no":
        break

I'm trying to add a feature where every time the game is won, the user has the option to play again, right now the game runs, then you win, it asks if you want to play again, you say yes, it runs again then you win and it runs again without asking.我正在尝试添加一个功能,每次游戏获胜时,用户都可以选择再次玩,现在游戏运行,然后你赢了,它询问你是否想再次玩,你说是,它运行然后你又赢了,它又不问就跑了。

You're currently only asking the user if he wants to play again once , and keep it going with the while loop.您目前只询问用户是否想再玩一次,并继续使用while循环。 You should ask the user again after every time the game is played, like so:每次玩完游戏后,您都应该再次询问用户,如下所示:

choose = input("Would you like to play again?\n")
while choose == "yes":        
    game()
    choose = input("Would you like to play again?\n") #add this line
    if choose == "no":
        break

Choose is only set one time, so the while-loop never breaks.选择只设置一次,因此 while 循环永远不会中断。 You could simply add:您可以简单地添加:


choose = input("Would you like to play again?\n")

while choose == "yes":
    game()
    choose = input("Would you like to play again?\n")
    if choose == "no":
        break

Or somewhat more elegantly:或者更优雅一些:


choose = input("Would you like to play again?\n")

while choose != "no":
    game()
    choose = input("Would you like to play again?\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM