gpt4 book ai didi

python - 我有一个 while 循环用于一个由于某种原因无法运行的游戏

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:26 25 4
gpt4 key购买 nike

我在使这个 while 循环工作时遇到问题,任何帮助/建议将不胜感激。

这是循环(它不是完整的程序):

import random

while your_health or enemy_health >= 10:
print("He is still attacking you.")
print("you may either:"
"a-dodge"
"b-attack back")
fight_choice_1_1 = input("What do you do?")

if fight_choice_1_1 == "a":
d20_1_1 = random.randint(1, 20)
if d20_1_1 >= 10:
print("you dodge the attack")
elif d20_1_1 <= 10:
your_health -= knife_damage
print("you get hit")
if your_health <= 0:
print("you lose. :(")
elif enemy_health <= 0:
print("you win!")

if fight_choice_1_1 == "b":
d20_1_1 = random.randint(1, 20)
if d20_1_1 >= 10:
print("you get out of the way and hit him")
enemy_health -= sword_damage
elif d20_1_1 <= 10:
print("he hits you, but you get a hit in too")
your_health -= knife_damage
enemy_health -= sword_damage
print("you get hit")
if your_health <= 0:
print("you lose. :(")
elif enemy_health <= 0:
print("you win!")

最佳答案

而不是:

while your_health or enemy_health >= 10:

我想你的意思是:

while your_health >= 10 or enemy_health >= 10:

你所拥有的是正确的英语,如“while (your health or enemy health) is greater than 10”,但计算机语言的语法更严格一些。

对于计算机来说,这意味着“当(你的生命值)或(敌人的生命值大于 10)时”,并且在真值的上下文中,许多语言只会将非零值视为真值。 Python 确实遵循该约定。

来自 5.10 Boolean operations在线 Python 文档:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

(我的粗体)。所以声明:

while your_health or enemy_health >= 10:

是有效的(假设它是数字,并且您从不让它在您的代码中降到零以下,合理的假设给出了它的预期目的):

while (your_health > 0) or (enemy_health >= 10):

换句话说,只要您的玩家有 任何 生命值,循环就会继续,而不是十个或更多生命值。

关于python - 我有一个 while 循环用于一个由于某种原因无法运行的游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8766035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com