有一个“程序”,其中有 Viking、Wizzard Assasin 类,然后应该形成两个团队 red_team 和 blue_team。每个团队可以有 3 个成员 dude, dude2, dude3 任务是随机分配类到 dude/2/3 变量。我是这样实现的:
chance = randint (1, 3)
If chance == 1:
dude = Viking (name = 'Red Viking')
if chance == 2:
dude = Wizzard (name = 'Red Wizzard')
if chance == 3:
dude = Assasin (name = 'Red Assasin')
red_taem.append (dude.name)
chance = randint (1, 3)
If chance == 1:
dude2 = Viking (name = 'Red Viking')
if chance == 2:
dude2 = Wizzard (name = 'Red Wizzard')
if chance == 3:
dude2 = Assasin (name = 'Red Assasin')
red_team.append (dude2.name)
chance = randint (1, 3)
If chance == 1:
dude3 = Viking (name = 'Red Viking')
if chance == 2:
dude3 = Wizzard (name = 'Red Wizzard')
if chance == 3:
dude3 = Assasin (name = 'Red Assasin')
red_team.append (dude3.name)
而这种恐怖,只属于一队三人参赛!如果有20个呢?
实际上问题是:如何简化?为了不写10万行代码。
附言 如果您提供解决方案,请向我解释您的解决方案将如何工作。
类:实际上,这里仍然是 beleberd ...
class Viking:
def __init__(self, name):
self.name = name
self.hp = 100
self.energy = 100
self.damage = 30
self.block = 15
self.role = 'tank'
class Assasin:
def __init__(self, name):
self.name = name
self.hp = 100
self.energy = 100
self.damage = 30
self.block = 15
self.role = 'ass'
class Wizzard:
def __init__(self, name):
self.name = name
self.hp = 100
self.energy = 100
self.damage = 30
self.block = 15
self.role = 'tank'
函数random.choices(population, weights=None, *, cum_weights=None, k=1)返回从 中
k
随机选择的元素的列表population
。例子:
更新:
在打印类对象时获取名称 ( ) -为所有类
self.name
定义一个方法:__repr__()