机器人gam的多个对象实例

2024-05-16 23:18:57 发布

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

我正在为一个基于网络的游戏构建一个机器人来学习OOP。 目前,我想知道如何最好地实现有圣骑士的军队和没有圣骑士的军队的想法。如果军队没有圣骑士,我知道这支军队是“特殊的”,也就是说,它不驻扎在村子里

 class Village:
    def __init__(self, name, coord):
        self.name = name
        self. coord = coord


class Army:
    def __init__(self, item):
        self.composition = {'spear': 0, 'sword': 0, 'axe': 0, 'paladin': 0}
        if len(item) == 3:
            item.append('0')
        for index, elem in enumerate(self.composition):
            self.composition[elem] = item[index]

    def merge_army(self, other):
        "Merge all the troops from other with self"
        for item in other.composition:
            self.composition[item] += other.composition[item]
            other.composition[item] = 0 


village = Village('Moscow', [364, 644])
army_example = '250 300 1 1'.split(' ')
army_example2 = '250 300 1'.split(' ')
village.army = []
village.army.append(Army(army_example))
village.army.append(Army(army_example2))

按照代码目前的工作方式,village.army的收益率为:

[<__main__.Army object at 0x00000229C9E99040>, <__main__.Army object at 0x00000229C9E90520>]

很明显,只要询问village.army[0],我就得到了第一个生成的实例。问题是,每当一支军队回到村庄,它就会与驻扎的军队合并。 我应该建立一个班级驻扎的军队吗?类似地,一个阶级远离军队(军队)


Tags: nameselfdefitemclassothercomposition圣骑士