退出python应用程序进行“游戏结束”

2024-09-21 03:25:11 发布

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

我想知道为什么这个代码不起作用;它应该在“游戏结束”时退出,但它将继续执行我定义的下一个函数。 我尝试了exit()的其他变体,例如:sys.exit()quit()SystemExit。你知道吗

run_attack = input("What do you do: Run/Attack\n")
run = ['run', 'Run', 'RUN']
attack = ['attack', 'Attack', 'ATTACK']
run_attack = 1
while run_attack < 10:
    if run_attack == ("run") or ("Run") or ("RUN"):
        print ("You turn to run from the wolf but he quickly pounces 
               you...")
        time.sleep(2)
        print("You are quickly ripped apart and just about get to see 
             yourself be eaten.")
        print("GAME OVER")
        break
        exit()       #This is where the game should exit, yet after input it 
                            continues to the next function


    elif run_attack == ("attack") or ("Attack") or ("ATTACK"):
         print("You brace yourself for a bite and have no time to reach" 
                 "for any kind of weapon form your backpack.")
        time.sleep("2")
        input("You clock the dog hard, twice on the muzzle.")
        print("The dog recoils in pain and retreats back to the woods.")
        print("You quickly start running as you assume there will be a den in the woods.")
        break       

    else:
        input("Type Run or Attack...")

Tags: orandthetorunyouinputtime
2条回答

您的代码中有几个问题;为什么编写这么多代码而不进行测试?你知道吗

首先,读取用户的输入,立即用1替换is,然后尝试(错误地)测试它,就好像它仍然是一个字符串一样。你发布的代码有几个语法错误,所以我在重现这个问题时遇到了一些麻烦。然而,最明显的问题是:

    break
    exit()       # This is where ...

您无法到达exit语句,因为您在到达该语句之前从循环中break。你知道吗


我强烈建议您备份到几行代码并使用增量编程:一次编写几行代码,调试这些代码,直到它们完成您想要的操作为止。你知道吗

还可以查看如何根据各种值测试变量。您的if语句不正确。相反,请尝试设置列表:

if run_attack in run:
    ...
elif run_attack in attack:
    ...

我冒昧地重写了你的整个程序,向你展示了它的一些错误和一些技巧。我已经做了没有循环,因为你从来没有使用它无论如何。。。一旦掌握了while循环,您可以在以后添加它,但是您确实应该回到这里的一些基本内容:

run_attack = input("What do you do: Run/Attack\n")

if run_attack.lower() == "run":
    print("""some
        stuff
        with
        multiple
        lines and GAME OVER""")
    exit()

elif run_attack in ("attack", "Attack", "ATTACK"):
    print("""some
        stuff
        with
        multiple
        lines""")

else:
    input("Type Run or Attack...")

注意事项:

  1. 对字符串使用"""可以在不使用多个print语句的情况下编写多行

  2. 在字符串上使用str.lower()使所有内容都易于比较,因为您只需将它与每个字符串的小写版本进行比较。但是对于attack,您可以注意到我使用了不同的包含测试,没有多个条件。不管哪种方法在这里都管用。

  3. 与这里的另一个答案(以及许多注释)一样,您应该只使用exit()完全退出程序,或者只使用break退出循环并继续执行整个循环下的其他代码。

  4. 重写循环时,使用while number_of_turns < 10这样的条件,不要忘记将1添加到每个循环的圈数中,否则该条件总是True,并且您将有一个无限循环。。。

实际上,我很惊讶这段代码与您期望的行为有任何相似之处,我的建议是回到python的基础,学习循环、字符串方法和基本命令。剩下的已经在这里的另一个答案中说了(坦白地说,这比我的好),只是想补充一些想法。你知道吗

相关问题 更多 >

    热门问题