首页 > 解决方案 > 退出'GAME OVER'的python应用程序

问题描述

我想知道为什么这段代码不起作用;它应该在“GAME OVER”点退出,但它会继续到我定义的下一个函数。sys.exit()我尝试了 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...")

标签: pythonvisual-studio

解决方案


您的代码中有几个问题;为什么你没有测试就写了这么多?

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

    break
    exit()       # This is where ...

您无法到达该exit语句,因为您break在到达那里之前就从循环中。


我强烈建议您备份几行代码并使用增量编程:一次编写几行代码,调试它们,然后在它们完成您想要的操作之前不要继续。

还要查看如何针对各种值测试变量。你的if说法不正确。相反,请尝试您尝试设置的列表包含:

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

推荐阅读