有没有一种方法可以在python中生成对象的不同实例?

时间:2019-06-17 21:41:21

标签: python

我正在用python(使用街机库)制作游戏。我开设了“武器”课程,可以在其中制作不同的武器实例(具有不同的精灵,伤害统计信息等)。我想要这样,当某个变量为True时,枪支会创建一个类(子弹)的新实例,但我不想将每个实例分配给一个新变量等。 有没有办法做到这一点?而且请不要太复杂,因为我对Python的了解还不够。

class Weapon(object):
    def __init__(self, sprite, size):
        self.weapon = arcade.Sprite(sprite,size)
        self.attacking = True

    def draw(self):
        self.weapon.draw()
        if self.attacking:
            # Creates an instance of Bullet Class with initialized variables
            # Every single time this variable is turned into True

2 个答案:

答案 0 :(得分:0)

您可以为此使用二传手

class Weapon(object):
    ...

    @property
    def attacking(self):
        return self._attacking

    @attacking.setter
    def attacking(self, value):
        if value and not self._attacking:
            # logic for when attacking become true
        self._attacking = value

然后,当您对代码的其他部分执行somewep.attacking = True时,设置器将运行。关于保存Bullet实例。如果实例化Bullet具有所需的所有副作用,那么您无需保存它,只需保存Bullet(parameters, ...)就可以了。

如果Bullet是由框架绘制的,则它具有对它的引用,并且只要框架引用它,GC就不应该收集它

答案 1 :(得分:0)

我不会那样做,我将创建一个包含draw()逻辑的Sprite类,其中,Player和Weapon类将继承该玩家,其中将包含武器并在Game类中实例化。包含所有逻辑

class Sprite:
    def draw(self):
        # Draw logic, maybe have an image sprite member variable

class Bullet(Sprite):
    def __init__(self, posX, posY, angle, velocity, game):
        self.posX = posX
        self.posY = posY
        self.angle = angle
        self.velocity = velocity
        self.game = game
        self.game.bullets.append(self)

    def fly(self):
         # Add some trigonometry here using the angle and velocity and implement some collision algorithm

class Weapon(Sprite):
    posX = 0
    posY = 0 #Probably gonna need to keep track of the position, you should init them in constructor
    angle = PI
    bullets = []

    def shoot(self):
        if len(self.bullets) <= 10: # maybe you don't want too many bullets
            self.bullets.append(Bullet(self.posX, self.posY, self.angle, 100))

class Player(Sprite):
    posX = 0
    posY = 0
    def __init__(self, game):
        self.game = game
        self.weapon = Weapon()

    def shoot(self):
        self.weapon.shoot()

class Game:
    players = []
    bullets = []

    def __init__(self, player_count=1):
        for i in range(player_count):
            self.players.append(Player(self))

    def draw(self):
        for player in self.players:
            player.draw()
        for bullet in self.bullets:
            bullet.fly()


def main():
    game = Game(1)
    game.start() # need to implement start logic, rerendering every few MS, etc.

if __name__ == "__main__":
    main()