python - 退出'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...")
解决方案
您的代码中有几个问题;为什么你没有测试就写了这么多?
首先,您阅读用户的输入,立即将 is 替换为1
,然后尝试(错误地)测试它,就好像它仍然是一个字符串一样。您发布的代码有几个语法错误,所以我在重现问题时遇到了一些麻烦。然而,最明显的问题就在这里:
break
exit() # This is where ...
您无法到达该exit
语句,因为您break
在到达那里之前就从循环中。
我强烈建议您备份几行代码并使用增量编程:一次编写几行代码,调试它们,然后在它们完成您想要的操作之前不要继续。
还要查看如何针对各种值测试变量。你的if
说法不正确。相反,请尝试您尝试设置的列表包含:
if run_attack in run:
...
elif run_attack in attack:
...
推荐阅读
- postgresql - 如何创建可以从 DBeaver 调用的 PostgreSQL 函数?
- elasticsearch - 弹性搜索在多值字段上返回无结果过滤
- java - 无法在英特尔设备上实例化活动异常
- java - Android Studio 3.5,索引时间
- wpf - 在 Xunit 测试中创建 System.Windows.Media.Pen 时出现间歇性错误
- react-native - 在有天赋的聊天中删除和复制消息
- ruby - 如何使用 Nokogiri 和 XPath 将元素添加到 XML
- ios - Swift - 使用计时器检测用户不活动,然后在 4 分钟后显示警报以提示用户是否仍然存在
- java - 将 ByteBuffer 转换为 Image 会产生嘈杂的输出
- android - 隐藏的蓝牙/BLE 设备