1

我有这个单词 un-scrambler 游戏,它只在 CMD 或 python shell 中运行。当用户正确或错误地猜出单词时,它会说“按任意键再次播放”

我怎样才能让它重新开始?

4

9 回答 9

8

在评估用户输入后不要让程序退出;相反,请在循环中执行此操作。例如,一个甚至不使用函数的简单示例:

phrase = "hello, world"

while input("Guess the phrase: ") != phrase:
    print("Incorrect.")  # Evaluate the input here
print("Correct")  # If the user is successful

这将输出以下内容,同时显示我的用户输入:

Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct

这显然很简单,但逻辑听起来像你所追求的。一个稍微复杂一点的版本,带有定义的函数让您查看您的逻辑适合的位置,可能是这样的:

def game(phrase_to_guess):
    return input("Guess the phrase: ") == phrase_to_guess

def main():
    phrase = "hello, world"
    while not game(phrase):
        print("Incorrect.")
    print("Correct")

main()

输出是相同的。

于 2012-07-12T19:28:37.957 回答
5

甚至以下样式也有效!

看看这个。

def Loop():
    r = raw_input("Would you like to restart this program?")
        if r == "yes" or r == "y":
            Loop()
        if r == "n" or r == "no":
            print "Script terminating. Goodbye."
    Loop()

这是 重复执行函数(语句集)的方法。

希望你喜欢 :) :} :]

于 2016-12-04T09:56:31.920 回答
2

尝试循环:

while 1==1:
    [your game here]
    input("press any key to start again.")

或者,如果你想变得花哨:

restart=1
while restart!="x":
    [your game here]
    input("press any key to start again, or x to exit.")
于 2012-07-12T19:28:44.210 回答
2

这是一个可用于重新运行代码块的模板。将#code 视为一行或多行 Python 代码的占位符。

def my_game_code():
    #code

def foo():
    while True:
        my_game_code()
于 2012-07-12T19:29:21.137 回答
1

你可以使用一个简单的while循环:

line = "Y"

while line[0] not in ("n", "N"):
    """ game here """
    line = input("Play again (Y/N)?")

希望这可以帮助

于 2012-07-12T19:32:12.047 回答
1
while True:
    print('Your game yada-yada')
    ans=input('''press o to exit or any key to continue
''')
    if ans=='o':
        break
于 2020-07-22T06:18:07.770 回答
0

一个简单的方法也是使用布尔值,如果您是初学者(如我)更容易理解。这是我为一个小组项目所做的:

 restart = True

 while restart:
     #the program
     restart = raw_input("Press any key to restart or q to quit!")
     if restart == "q":
         restart = False
于 2017-12-12T16:56:07.740 回答
0

您需要将代码块埋在另一个代码块中。 请按照以下说明进行操作:

Step 1: Top of code def main()  
Step 2: restart = input("Do you want to play a game?").lower()    
Step 3: Next line; if restart == "yes":    
Step 4: Next line; Indent - main()    
Step 5: Next line; else:  
Step 6: Indent - exit()  
Step 7: Indent all code under def main(): 
Step 8: After all code indent. Type main()

您正在做的是将代码块封装到主变量中。程序在 main() 变量中运行一次,然后退出并返回以再次运行 main 变量。重复游戏。希望这可以帮助。

def main():    
    import random
    helper= {}
    helper['happy']= ["It is during our darkest moments that we must focus to see the light.",
        "Tell me and I forget. Teach me and I remember. Involve me and I learn.",
        "Do not go where the path may lead, go instead where there is no path and leave a trail.",
        "You will face many defeats in life, but never let yourself be defeated.",
        "The greatest glory in living lies not in never falling, but in rising every time we fall.",
        "In the end, it's not the years in your life that count. It's the life in your years.",
        "Never let the fear of striking out keep you from playing the game.",
        "Life is either a daring adventure or nothing at all."]

    helper['sad']= ["Dont cry because it’s over, smile because it happened.",
        "Be yourself; everyone else is already taken",
        "No one can make you feel inferior without your consent.",
        "It’s not who you are that holds you back, its who you think you're not.",
        "When you reach the end of your rope, tie a knot in it and hang on."]

    answer = input ('How do you feel : ')
    print("Check this out : " , random.choice(helper[answer]))
    restart = input("Do you want a new quote?").lower()
    if restart == "yes":
        main()

    else:
        exit()
main()

于 2020-05-26T20:03:43.203 回答
0

如何在 python 中使用用户输入 [yes/no] 重新运行代码?

强文本

如何在 python 中使用用户输入 [yes/no] 重新运行代码? 强文本

内部代码 def main(): 尝试:

    print("Welcome user! I am a smart calculator developed by Kushan\n'//' for Remainder\n'%' for Quotient\n'*' for Multiplication\n'/' for Division\n'^' for power")
    num1 = float(input("Enter 1st number: "))
    op = input("Enter operator: ")
    num2 = float(input("Enter 2nd number: "))


    if op == "+":

        print(num1 + num2)
    elif op =="-":
        print(num1 - num2)
    elif op =="*":
        print(num1 * num2)
    elif op =="/" :
        print(num1 / num2)
    elif op =="%":
        print(num1 % num2)
    elif op =="//":
        print(num1 // num2)
    elif op == "^":
        print(num1 ** num2)
    else:
        print("Invalid number or operator, Valid Operators < *, /, +, -, % , // > ")


except ValueError:

    print("Invalid Input, please input only numbers")

restart = input("Do you want to CALCULATE again? : ")


if restart == "yes":


    main()

else:
    print("Thanks! for calculating keep learning! hope you have a good day :)")


    exit()

main() 强文本

您可能会尝试运行整个代码,并允许用户键入“是”或“否”以再次运行程序而无需手动运行它。这是我使用过这个东西的“计算器”的代码。那是你的解决方案吗?

顺便说一句,这是我学习应用此功能的参考链接。 https://www.youtube.com/watch?v=SZdQX4gbql0&t=183s

于 2021-05-12T18:02:18.060 回答