【发布时间】:2019-11-30 18:07:01
【问题描述】:
我正在使用 Learn Python The Hard Way 学习编程。在练习 43 的学习训练中,作者希望我们构建一个简单的战斗系统,用于英雄遇到敌人时。
在我的战斗系统中,玩家和敌人都以 100 HP 开始。我设置了一个列表,其中包含 4 个随机提示玩家。根据提示,玩家需要做出反应。根据场景和反应,玩家会损失生命值、对敌人造成伤害或不受影响。每当他们改变时,程序都会打印出玩家和敌人的剩余HP。
health = 100
enemy_health = 100
battle_prompts = [
"The Gothon raises his rifle, aiming it square in your face.",
"The Gothon aims, then pauses, realising he's yet to reload his ammo.",
"The Gothon charges at you at lightspeed, fists clenched tight.",
"The Gothon runs in your direction, with a menacing grin on his face."
]
while health != 0 and enemy_health != 0:
battle_prompt = battle_prompts[randint(0,3)]
print (battle_prompt)
action = input("> ")
healthbar = (f"HEALTH: {health} | ENEMY HEALTH: {enemy_health}")
if battle_prompt == battle_prompts[0] and action == "dodge":
print ("You dodge the bullet successfully. Nice one!")
elif battle_prompt == battle_prompts[0] and action != "dodge":
health -= 25
print ("You fool! You just got shot!")
print (healthbar)
elif battle_prompt == battle_prompts[1] and action == "shoot":
enemy_health -= 25
print ("Cool! You just caused some alien bloodshed!")
print (healthbar)
elif battle_prompt == battle_prompts[1] and action != "shoot":
print ("The Gothon reloads his rifle successfully. A wasted opportunity!")
elif battle_prompt == battle_prompts[2] and action == "block":
print("You manage to block the Gothon's deadly punches. Way to go!")
elif battle_prompt == battle_prompts[2] and action != "block":
health -= 25
print("What a lamebrain! You just got pounded by an alien!")
print (healthbar)
elif battle_prompt == battle_prompts[3] and action == "punch":
enemy_health -= 25
print("You give that extraterrestrial invader a beautiful uppercut. Wow!")
print (healthbar)
elif battle_prompt == battle_prompts[3] and action != "punch":
print("The Gothon knocks you over. You're not hurt, but you wasted an opportunity.")
else:
if health == 0:
print ("Whoops! Guess you're outta health points! That's all folks!")
return 'death'
elif enemy_health == 0:
print("Good job! You defeated an armed citizen of a galaxy unknown fair and square!")
return 'escape_pod'
我将剩余的 HP 提示分配给变量 healthbar,但似乎无法使其正常工作。如果 HP 有变化,则不会反映在紧随其后打印的提示中;仅在下次 HP 发生变化时显示。我想你可以说提示总是“延迟”一次循环迭代。
例如:
如果我在第一轮造成 25 点伤害,那么输出是
HEALTH: 100 | ENEMY HEALTH: 100
在第二轮中,敌人造成 25 点伤害。输出:
HEALTH: 100 | ENEMY HEALTH: 75
如果我在第三轮躲避攻击,输出是:
HEALTH: 75 | ENEMY HEALTH: 75
程序“实时”计算 HP 值,即如果任何角色的 HP 为零,则执行 while 循环的 else 块,但提示仍然显示他们还剩 25HP。
我尝试将 healthbar 移到 while 循环之外,但提示显示 HP 值始终为 100。但是,当我完全取消 healthbar 变量并通过粘贴替换它的每个实例时整个提示,一切都正确显示。我做错了什么?
【问题讨论】:
标签: python loops printing while-loop