在整数变量被 def 修改后对其进行更新



===编辑已解决!下面的评论中完成了代码!===

制作基于文本的角色扮演游戏。开发惠普系统。我已经设法做出了HP和伤害的定义。我需要这样做,以便它在每次受到伤害后更新HP变量。

我只编码了一个星期,不知道我正在寻找的术语,所以我无法成功搜索答案,但我已经尝试找到答案大约两个小时了。

import random
hit_points = 20
d4_damage = random.randint(1, 4)
d6_damage = random.randint(1, 6)
d8_damage = random.randint(1, 8)
def hp_loss_small():
for x in range(1):
return hit_points - d4_damage

print (hp_loss_small())
def hp_loss_medium():
for x in range(1):
return hit_points - d6_damage

print (hp_loss_medium())
def hp_loss_large():
for x in range(1):
return hit_points - d8_damage

print (hp_loss_large())

正确的结果是,如果您运行了一个伤害防御并损失了 4 点生命值,它会显示 16 点。但它不会更新 hp 变量,所以如果你再受到 2 点伤害,你会达到 18 点 hp。我需要它,所以它会更新变量并转到 14。

for x in range(1):

您可以完全省略它,因为这只运行一次语句。

从函数return值时,可以将结果分配给变量。在您的情况下,您会做hit_points = hp_loss_small().此外,应将当前命中点作为参数 (def hp_loss_small(hit_points)( 传递,并将其称为hp_loss_small(hit_points)

如果有其他人在搜索类似问题时发现这一点,这是我完成的代码:

import random
hit_points = 20
d4_damage = random.randint(1, 4)
d6_damage = random.randint(1, 6)
d8_damage = random.randint(1, 8)
def dead():
if hit_points < 1:
return ('dead message ')
else:
return (' ')
def hp_loss_small(hit_points):
return hit_points - d4_damage
print (hp_loss_small(hit_points))
hit_points = hp_loss_small(hit_points)
print (dead())
def hp_loss_medium(hit_points):
return hit_points - d6_damage
print (hp_loss_medium(hit_points))
hit_points = hp_loss_medium(hit_points)
print (dead())
def hp_loss_large(hit_points):
return hit_points - d8_damage
print (hp_loss_large(hit_points))
hit_points = hp_loss_large(hit_points)
print (dead())

最新更新