【发布时间】:2022-01-09 05:09:40
【问题描述】:
我一直在开发这款奇幻战斗游戏,尽管在游戏最后开始的 while True 循环没有迭代,但它按预期工作。我尝试使用 continue 没有成功。我已经包含了一个流程图来直观地展示游戏的逻辑。我没有收到任何错误,应该是无限的循环只是在最后停止而没有重新开始。我可以让它迭代直到它到达break 之一吗?
"""
Fantasy Battle Game
Player against Dragon
"""
# Player
wizard = "Wizard"
elf = "Elf"
human = "Human"
# Player health
wizard_hp = 70
elf_hp = 100
human_hp = 150
# Player damage force
wizard_damage = 150
elf_damage = 100
human_damage = 20
# Dragon health and damage force
dragon_hp = 300
dragon_damage = 50
# Print the list of characters
print(wizard)
print(elf)
print(human)
# Input function to choose player
character = input("Choose your character: ")
# While loop to represent player profile
while True:
if character == "Wizard":
my_hp = wizard_hp
my_damage = wizard_damage
break
elif character == "Elf":
my_hp = elf_hp
my_damage = elf_damage
break
elif character == "Human":
my_hp = human_hp
my_dammage = human_damage
break
else:
print("Unknown Character")
break
# Print player selection
print(character)
# print player health:
print(my_hp)
# print player damage force:
print(my_damage)
# Start game
while True:
# Player start first battle against Dragon
dragon_hp = dragon_hp - my_damage
# If dragon health is positive show remaining health
if dragon_hp > 0:
print(f'{character} damaged the dragon!')
print(f'The Dragon hitpoints are now {dragon_hp}')
# If dragon health is negative or null - game over
elif dragon_hp <= 0:
break
print(f'The Dragon lost the battle!')
# Dragon start second battle against player
my_hp = my_hp - dragon_damage
# If player health is positive show remaining health
if my_hp > 0:
print(f'The Dragon strikes back at {character}')
print(f'The {character} hitpoints are now {my_hp}')
# If player health is negative - game over
elif my_hp <= 0:
break
print(f'The {character} lost the battle!')
【问题讨论】:
-
将
print语句放在break之前,这样您就可以看到它何时爆发。 -
第一个
while循环完全没用——它在每个分支之后都会中断,因此永远不会真正循环。你也可以删除它。在第二个循环中,如果您希望它基于某些条件运行,您可以将其作为 while 条件而不是True:while dragon_hp > 0 and my_hp >0
标签: python python-3.x loops while-loop nested-loops