我想知道为什么这个代码不起作用;它应该在“游戏结束”时退出,但它将继续执行我定义的下一个函数。
我尝试了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...")
您的代码中有几个问题;为什么编写这么多代码而不进行测试?你知道吗
首先,读取用户的输入,立即用
1
替换is,然后尝试(错误地)测试它,就好像它仍然是一个字符串一样。你发布的代码有几个语法错误,所以我在重现这个问题时遇到了一些麻烦。然而,最明显的问题是:您无法到达
exit
语句,因为您在到达该语句之前从循环中break
。你知道吗我强烈建议您备份到几行代码并使用增量编程:一次编写几行代码,调试这些代码,直到它们完成您想要的操作为止。你知道吗
还可以查看如何根据各种值测试变量。您的
if
语句不正确。相反,请尝试设置列表:我冒昧地重写了你的整个程序,向你展示了它的一些错误和一些技巧。我已经做了没有循环,因为你从来没有使用它无论如何。。。一旦掌握了
while
循环,您可以在以后添加它,但是您确实应该回到这里的一些基本内容:注意事项:
对字符串使用
"""
可以在不使用多个print
语句的情况下编写多行在字符串上使用
str.lower()
使所有内容都易于比较,因为您只需将它与每个字符串的小写版本进行比较。但是对于attack
,您可以注意到我使用了不同的包含测试,没有多个条件。不管哪种方法在这里都管用。与这里的另一个答案(以及许多注释)一样,您应该只使用
exit()
完全退出程序,或者只使用break
退出循环并继续执行整个循环下的其他代码。重写循环时,使用
while number_of_turns < 10
这样的条件,不要忘记将1
添加到每个循环的圈数中,否则该条件总是True
,并且您将有一个无限循环。。。实际上,我很惊讶这段代码与您期望的行为有任何相似之处,我的建议是回到python的基础,学习循环、字符串方法和基本命令。剩下的已经在这里的另一个答案中说了(坦白地说,这比我的好),只是想补充一些想法。你知道吗
相关问题 更多 >
编程相关推荐