所以我正在通过“Learn Python The Hard Way”来学习 Python, 我目前正在写一个简单的文本冒险。
我的问题出在代码的“战斗”部分(如下所示)。只有数字 1 和 2 需要由用户按下。如果按下不同的 int ,它会正确地抛出“抱歉,不明白”,但如果按下一个字母,它就会崩溃并退出,并说(非常正确)它正在等待一个 int 。显然我的问题是,如何将其设置为期望两者,并在按下字母时抛出错误?
提前致谢:)
while True:
player_dmg = randint(1, 10)
enemy_dmg = randint(1, 10)
if enemy_hp < 0:
os.system('clear')
print "[ENEMY NUTRALISED]"
print
print hit_e
raw_input()
return 'forth_area'
elif player_hp < 0:
return 'death'
else:
print "[COMBAT OPTIONS]"
print "1. Attack"
print "2. Defend"
print
choice = raw_input("*>>*")
choice = int(choice)
print
if choice == 1:
enemy_hp = enemy_hp - player_dmg
print "[ENEMY STATUS: %d]" % enemy_hp
print "[DAMAGE DONE: %d]" % player_dmg
print
player_hp = player_hp - enemy_dmg
print "[DAMAGE RECIVED: %d]" % enemy_dmg
print "[CURRENT STATUS: %d]" % player_hp
elif choice == 2:
enemy_hp = enemy_hp - player_dmg / 2
print "[ENEMY STATUS %d]" % enemy_hp
print "[DAMAGE DONE %d]" % player_dmg
print
player_hp = player_hp - enemy_dmg
player_hp = player_hp + 3
print "[DAMAGE RECIVED: %d]" % enemy_dmg
print "[CURRENT STATUS: %d]" % player_hp
print
else:
print no_understand
最佳答案
你有:
choice = raw_input("*>>*")
choice = int(choice)
# . . .
if choice == 1:
# . . .
elif choice == 2:
最简单的修复方法是使用:
choice = raw_input("*>>*")
# . . .
if choice == '1':
# . . .
elif choice == '2':
raw_input
返回一个字符串。为什么要转换成数字呢?只需测试文本 '1'
和 '2'
等。它还可以更轻松地添加字符命令(例如 'q'
退出)。
关于python - 尝试在 while 循环中设置 "wrong key pressed"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14665674/