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

时间:2014-12-27 19:31:01

标签: python function loops random integer

我想制作一个可以做某种战斗日志的程序。你有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!")

然而,当我运行这个代码时,它或者陷入了无限循环的错误"错过"或处理相同的伤害值。

3 个答案:

答案 0 :(得分: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!

答案 1 :(得分:2)

您根本不需要全局,根本不需要使用它,您只需将更新的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!")

答案 2 :(得分:1)

程序启动时会生成两个随机数,而不会更改它们。你应该做的是每次调用attack()时重新生成它们:

HP = 100

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

此外,使用==而不是is来比较整数(或者,就此而言,大多数其他事情):

if hitChance == 0:

is运算符有其用途,但它们非常罕见。