【问题标题】:Keep getting the same random values when using a function使用函数时保持相同的随机值
【发布时间】:2015-02-24 13:40:38
【问题描述】:

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

但是,当我运行此代码时,它要么陷入“错过”的无限循环,要么造成相同的伤害值。

【问题讨论】:

  • 您永远不会重新定义 damagehitChance,因此它始终是相同的值。

标签: python function loops random integer


【解决方案1】:

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

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!

【讨论】:

  • 谢谢!这帮助很大!
  • @HermanLeshkovtsev,不要使用 is 来比较值,“is”用于身份检查而不是值。
  • 为了更好地控制,我会使用random 而不是randint,例如hitChance > 0.7 需要超过 70% 的命中率或 hitChance > target.evadeChance 使用类时。
【解决方案2】:

你不需要全局,使用它很少是一个好的设计,你可以将更新的生命值传递给攻击函数和从攻击函数返回:

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!")

【讨论】:

  • 赞成建议一种摆脱全球性的方法
【解决方案3】:

您在程序启动时生成两个随机数,并且永远不要更改它们。相反,您应该做的是每次调用 attack() 时重新生成它们:

HP = 100

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

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

if hitChance == 0:

is 运算符有其用途,但它们很少见。

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多