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

2024-10-01 19:23:36 发布

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

当玩家被要求重新启动游戏时,我一直试图在选择“是”后将代码返回到开头。如何重新启动游戏

我尝试了尽可能多的解决方案,最终得到了这段代码。包括continue、break和其他几个明显的选项

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()

我想让我的代码在给定选项后键入“yes”时完全重新启动


Tags: thetonoyouifdefyesrestart
2条回答

你有两个主要的选择。 第一种选择:创建一个主函数,当调用它时,它只执行一次脚本。然后,对于代码的实际执行,请执行以下操作:

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

其次,兼容性较差的选项:使用ossubprocess发出shell命令以再次执行脚本,例如os.system("python3 filename.py")

编辑:尽管事实上这是不鼓励的,所以,我决定帮助一个朋友了,重写你的脚本。以后请不要问这个问题。在这里:

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()

一般来说,如果你想回到某件事的开头,你需要一个包含所有内容的循环。就像

while True:
    """ game code """

这基本上会一遍又一遍地重复你的整个游戏。如果您希望它在默认情况下结束,并且只在某些情况下重新启动,您可以这样做

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

为了让事情变得简单一点,可以使用异常。每当您想重新启动循环时,甚至从您的一个函数中,都会引发RestartException。或在要退出循环时引发ExitException

class RestartException(Exception):
    pass

class ExitException(Exception):
    pass

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

    except RestartException:
        continue

    except ExitException:
        break
    break

相关问题 更多 >

    热门问题