我有一个乘以用户输入的循环,当循环完成时,我想打破它:
import sys
import time
import msvcrt
from random import randint
import random
def time_input(caption, timeout=3):
start_time = time.time()
sys.stdout.write('%s: ' % (caption))
input = ''
while True:
if msvcrt.kbhit():
chr = msvcrt.getche()
if ord(chr) == 13:
break
elif ord(chr) >= 32:
input += chr
if len(input) == 0 and (time.time() - start_time) > timeout:
break
调用此循环的地方是:
def battle(animal, weapon, health):
print "To try to kill the {};" \
" you must press the correct key" \
" when it appears on the screen." \
" Press enter when ready".format(animal)
raw_input()
keys = 'abcdefghijklmnopqrstuvwxyz'
animal_health = 100
while health > 0:
while True:
if animal == 'mountain lion':
animal_damage = randint(27, 97)
animal_output = "The mountain lion slashes at you doing {} damage!".format(animal_damage)
else:
animal_damage = randint(10, 25)
animal_output = "The {} slashes at you doing {} damage!".format(animal, animal_damage)
correct_key = random.choice(keys)
print "Enter: {}".format(correct_key)
to_eval = time_input('> ')
if to_eval == correct_key:
damage = weapon_info(weapon, animal_health)
print damage
animal_health -= damage
print "The {} has {} health remaining".format(animal, animal_health)
if animal_health <= 0:
win_battle(animal, weapon)
else:
print animal_output
health -= animal_damage
print "You have {} health remaining".format(health)
if health <= 0:
lose_battle(animal)
break
battle('mountain lion', 'knife', 100)
当按下所有正确的键并且运行状况为0或更低时,如何使此循环中断
到目前为止,它是这样做的:
试图杀死山狮;出现时必须按正确的键 在屏幕上。准备好后按回车键
Enter: h
h: h
You slash at them with your knife doing 20
20
The mountain lion has 80 health remaining
Enter: a
a: a
You slash at them with your knife doing 24
24
The mountain lion has 56 health remaining
Enter: j
j: j
You slash at them with your knife doing 23
23
The mountain lion has 33 health remaining
Enter: p
p: p
You slash at them with your knife doing 10
10
The mountain lion has 23 health remaining
Enter: k
k: k
You slash at them with your knife doing 26
26
The mountain lion has -3 health remaining
You pick up the dead mountain lion and start walking back to camp.
You found extra meat!
Enter: h # Just keeps going
h: Traceback (most recent call last):
File "battle.py", line 97, in <module>
battle('mountain lion', 'knife', 100)
File "battle.py", line 31, in battle
to_eval = time_input(correct_key)
File "C:\Users\thomas_j_perkins\bin\python\game\settings.py", line 36, in time
_input
if msvcrt.kbhit():
KeyboardInterrupt
使用
return
来转义battle
-函数。我猜就在这里如果战斗成功的话,也许你想归还你现在的生命值?通过简单地返回健康值而不是什么都不返回应该很容易,即
return healt
而不是仅仅return
你可能也想在输掉一场战斗后做同样的事情,但不返回任何生命值,即
return 0
相关问题 更多 >
编程相关推荐