简体   繁体   English

如何将我的代码返回到代码开头?

[英]How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. 当玩家要求重新启动游戏时选择“是”后,我一直试图将代码返回到开头。 How do I make the game restart? 如何使游戏重启?

I've tried as many solutions as possible and have ended up with this code. 我尝试了尽可能多的解决方案,并最终获得了这段代码。 Including continue, break, and several other obvious options. 包括继续,中断和其他几个明显的选项。

import time
def start():
    score = 0
    print("Welcome to Atlantis, the sunken city!")
    time.sleep(1.5)
    print("You are the first adventurist to discover it!")
    time.sleep(1.5)
    print("Do you explore or talk to the merpeople?")
    time.sleep(1.5)
    print("Type 1 to explore Atlantis alone.")
    time.sleep(1.5)
    print("Type 2 to talk to the resident merpeople.")

start()

def surface():
    print("You return to the surface.")
    print("When you go back to Atlantis it's gone!")
    print("Your findings are turned to myth.")
    print("The end!")
    print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
    score = -1

def castle():
    print("The merpeople welcome you to their castle.")
    print("It is beautiful and you get oxygen.")
    print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
    score = 1
    print("To explore alone enter 5. To go to the surface enter 6.")


def drowndeath():
    print("You begin to explore around you.")
    print("You avoid the merpeople who avoid you in return.")
    print("But, OH NO, your oxygen begins to run out!")
    print("You run out of air and die.")
    print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
    score = 4

def merpeople():
    print("The merpeople talk kindly to you.")
    print("They warn you that your oxygen tank is running low!")
    print("You can follow them to their castle or go back to the surface.")
    print("Type 3 to go to the castle or 4 to go to the surface.")
    score = 5

def alone():
    print("You begin to explore alone and discover a secret caven.")
    print("You go inside and rocks trap you inside!")
    print("You die underwater.")
    print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
    score = 6

def famous():
    print("You come back to land with new discoveries!")
    print("Everyone loves you and the two worlds are now connected!")
    print("You win!")
    print("Wanna play again?If you do, type yes! If you wanna leave, type no!")


def choice_made():
    choice = input("Make your decision!\n ")
    if choice == "1":
        drowndeath()
    elif choice == "2":
        merpeople()
    else:
        print("Please enter a valid answer.")
        choice_made()

choice_made()

def choice2_made():
    choice2 = input("What do you do?\n ")
    if choice2 == "4":
        surface()
    elif choice2 == "3":
        castle()
    elif choice2 == "yes":
        start()
    elif choice2 == "no":
        exit()
    else:
        print("Please enter a valid answer.")
        choice2_made()
choice2_made()

def choice3_made():
    choice3 = input("Make up your mind!\n ")
    if choice3 == "5":
        alone()
    if choice3 == "6":
        famous()
    else:
        print("Please enter a valid answer.")
        choice3_made()
choice3_made()

def restart_made():
    restart = input("Type your answer!\n ")
    if restart == "yes":
        sys.exit()
    elif restart == "no":
        exit()
    else:
        print("Please choose yes or no!")
        restart_made()

restart_made()

while True:

    choice = input("Make your decision!\n ")
    if choice == "1":
        drowndeath()
    elif choice == "2":
        merpeople()    
    else:
        print("Please enter a valid answer.")
        choice_made()

choice_made()

while True:
    choice2 = input("What do you do?\n ")
    if choice2 == "4":
        surface()
    if choice2 == "3":
        castle()
    else:
        print("Please enter a valid answer.")
        choice2_made()
choice2_made()

while True:
    choice3 = input("Make up your mind!\n ")
    if choice3 == "5":
        alone()
    if choice3 == "6":
        famous()
    if choice3 == "1":
        drowndeath()
    if choice3 == "2":
        merpeople()
    else:
        print("Please enter a valid answer.")
        choice3_made()
choice3_made()

while True:
    restart = input("Type your answer!\n ")
    if restart == "yes":
        sys.exit()
    elif restart == "no":
        exit()
    else:
        print("Please choose yes or no!")
        restart_made()

restart_made()

I want for my code to restart completely when 'yes' is typed after given the option. 我希望给定选项后键入“是”时代码完全重新启动。

In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. 通常,如果您希望能够“回到起点”,则希望有一个包含所有内容的循环。 Like 喜欢

while True:
    """ game code """

That would basically repeat your entire game over and over. 这样基本上可以一遍又一遍地重复您的整个游戏。 If you want it to end by default, and only restart in certain situations, you would do 如果您希望它在默认情况下结束,并且仅在某些情况下重新启动,则可以

while True:
    """ game code """

    if your_restart_condition:
        continue # This will restart the loop

    if your_exit_condition:
        break # This will break the loop, i.e. exit the game and prevent restart

    """ more game code """

    break # This will break the loop if it gets to the end

To make things a little easier, you could make use of exceptions. 为了使事情变得容易一些,您可以使用异常。 Raise a RestartException whenever you want to restart the loop, even from within one of your functions. 每当您想重新启动循环时,即使从一个函数中,也要引发RestartException。 Or raise an ExitException when you want to exit the loop. 或在要退出循环时引发ExitException。

class RestartException(Exception):
    pass

class ExitException(Exception):
    pass

while True:
    try:
        """ game code """

    except RestartException:
        continue

    except ExitException:
        break
    break

You have two main options. 您有两个主要选择。 First option: make a main function that, when called, executes your script once. 第一种选择:创建一个主函数,该函数在被调用时将执行一次脚本。 Then, for the actual execution of the code, do this: 然后,对于代码的实际执行,执行以下操作:

while True:
    main()
    if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
        break

Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, eg os.system("python3 filename.py") . 其次,兼容性较差的选项:使用ossubprocess os.system("python3 filename.py")发出shell命令以再次执行脚本,例如os.system("python3 filename.py")

EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. 编辑:尽管事实上不建议这样做,但我还是决定帮助一位朋友并重写您的脚本。 Please do not ask for this in the future. 请不要在将来要求这样做。 Here it is: 这里是:

import time, sys
score = 0
def makeChoice(message1, message2):
    try:
        print("Type 1 "+message1+".")
        time.sleep(1.5)
        print("Type 2 "+message2+".")
        ans = int(input("Which do you choose? "))
        print()
        if ans in (1,2):
            return ans
        else:
            print("Please enter a valid number.")
            return makeChoice(message1, message2)
    except ValueError:
        print("Please enter either 1 or 2.")
        return makeChoice(message1, message2)
def askRestart():
    if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
        print()
        print("Okay. Restarting game!")
        playGame()
    else:
        print("Thanks for playing! Goodbye!")
    sys.exit(0)
def surface():
    print("You return to the surface.")
    print("When you go back to Atlantis it's gone!")
    print("Your findings are turned to myth.")
    print("The end!")
def castle():
    print("The merpeople welcome you to their castle.")
    print("It is beautiful and you get oxygen.")
    print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
    print("You begin to explore around you.")
    print("You avoid the merpeople who avoid you in return.")
    print("But, OH NO, your oxygen begins to run out!")
    print("You run out of air and die.")
def merpeople():
    print("The merpeople talk kindly to you.")
    print("They warn you that your oxygen tank is running low!")
    print("You can follow them to their castle or go back to the surface.")
def alone():
    print("You begin to explore alone and discover a secret caven.")
    print("You go inside and rocks trap you inside!")
    print("You die underwater.")
def famous():
    print("You come back to land with new discoveries!")
    print("Everyone loves you and the two worlds are now connected!")
    print("You win!")
def playGame():
    print("Welcome to Atlantis, the sunken city!")
    time.sleep(1.5)
    print("You are the first adventurer to discover it!")
    time.sleep(1.5)
    print("Do you explore or talk to the merpeople?")
    time.sleep(1.5)
    ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
    if ans == 1:
        drowndeath()
        askRestart()
    merpeople()
    ans = makeChoice("to go to the castle", "to return to the surface")
    if ans == 2:
        surface()
        askRestart()
    castle()
    ans = makeChoice("to return to the surface", "to explore alone")
    if ans == 1:
        famous()
    else:
        alone()
    askRestart()
playGame()

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

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