函数中的随机数保持不变,例如当数字为1时,它保持为1.但是当它在函数外部时,它会生成其他数字。
如何在函数中生成非重复随机数?
from random import *
randomEnemyNames = ["Gandalf", "Batman", "Magikarp", "Ed Sheeran", "Justin Bieber"]
class Character(object):
def __init__(self, name):
self.name = name
self.attackPhysical = getrandbits(4)
self.attackMagical = getrandbits(5)
self.enemyAttack = getrandbits(6)
self.critChance = random()
self.randomHeal = getrandbits(3)
def attack(self, enemy):
#inside the class and functions
print self.critChance #testing with two trials to see if all of it goes random in different ways
print self.critChance
print self.attackPhysical
print self.attackPhysical
print self.attackMagical
print self.attackMagical
print enemy.enemyAttack
print enemy.enemyAttack
print self.critChance
print self.critChance
print self.randomHeal
print self.randomHeal
print self.name
print enemy.name
the_player = Character("Roy")
the_enemy = Character(choice(randomEnemyNames))
the_player.attack(the_enemy)
#outside the class and functions
print random()
print getrandbits(3)
print getrandbits(4)
print getrandbits(5)
print getrandbits(6)
raw_input("Enter to exit")
答案 0 :(得分:1)
您正在为类的这些属性赋值,而不是代码,它可能看起来像这样:
def getrandbits(n):
return 9 # I rolled 3d6
class Character:
def __init__(self):
self.attackPhysical = getrandbits(4)
def attack(self, enemy):
print(self.attackPhysical)
print(self.attackPhysical)
您每次都需要生成一个新号码。也许像:
class Character:
def __init__(self):
self.attackPhysical = 4
def roll(self, n):
return getrandbits(n)
def attack(self, enemy):
physical_dmg = self.roll(self.attackPhysical)