在使用函数时保持获得相同的随机值

2024-09-26 17:43:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个程序,可以做一些战斗日志。你以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”,要么造成相同的伤害值。你知道吗


Tags: fromimport程序isdefrandomglobalhp
3条回答

将变量从全局空间中取出并放入函数中。你知道吗

HP = 100

def atack():
    global HP
    hitChance = randint(0,1)
    damage = 10 + randint(0, 15)

    if hitChance == 0:
        print("Missed")

    elif hitChance == 1:
        HP -= damage
        print("{} delt".format(damage))
        print("{} HP left".format(HP))

然后,在while循环外进行最后一次打印通话。你知道吗

while HP > 0:
    atack()

print("You defeated the enemy!")

样本输出:

14 delt
86 HP left
14 delt
72 HP left
15 delt
57 HP left
Missed
Missed
Missed
Missed
Missed
23 delt
34 HP left
10 delt
24 HP left
10 delt
14 HP left
Missed
Missed
Missed
Missed
15 delt
-1 HP left
You defeated the enemy!

你在程序启动时生成两个随机数,并且从不改变它们。相反,您应该在每次调用attack()时重新生成它们:

HP = 100

def atack():
   hitChance = randint(0,1)
   damage = 10 + randint(0, 15)
   ...

另外,使用==而不是is来比较整数(或者,对于这个问题,大多数其他的东西):

if hitChance == 0:

is操作符有它的用途,但是它们非常罕见。你知道吗

您不需要全局的,而且使用它很少是一个好的设计,您只需在攻击功能中传递和返回更新的HP:

HP = 100

def attack(HP):
    hitChance = randint(0,1)
    damage = 10 + randint(0, 15)
    if hitChance ==  0:
        print("Missed")
    elif hitChance == 1: # == not is 
        HP -= damage
        print(damage, " delt")
        print(HP, " left")
    return HP

while HP > 0:
    HP = attack(HP) # reassigns HP from current to HP minus an attack
print("You defeated the enemy!")

相关问题 更多 >

    热门问题