我想做一个程序,可以做一些战斗日志。你以50%的几率打击敌人,造成10到25点的伤害。你知道吗
from random import randint
hitChance = randint(0,1)
damage = 10 + randint(0, 15)
HP = 100
def atack():
global HP
if hitChance is 0:
print("Missed")
elif hitChance is 1:
HP -= damage
print(damage, " delt")
print(HP, " left")
while HP > 0:
atack()
print("You defeated the enemy!")
然而,当我运行这段代码时,它要么陷入一个无限循环的“missed”,要么造成相同的伤害值。你知道吗
将变量从全局空间中取出并放入函数中。你知道吗
然后,在while循环外进行最后一次打印通话。你知道吗
样本输出:
你在程序启动时生成两个随机数,并且从不改变它们。相反,您应该在每次调用
attack()
时重新生成它们:另外,使用
==
而不是is
来比较整数(或者,对于这个问题,大多数其他的东西):is
操作符有它的用途,但是它们非常罕见。你知道吗您不需要全局的,而且使用它很少是一个好的设计,您只需在攻击功能中传递和返回更新的HP:
相关问题 更多 >
编程相关推荐