0

我正在用 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
4

2 回答 2

1

我不会那样做,我会创建一个包含 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()
于 2019-06-17T22:01:41.653 回答
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对代码的其他部分执行操作时,setter 将运行。关于保存 Bullet 实例。如果实例化Bullet具有它需要的所有副作用,那么你不需要保存它,Bullet(parameters, ...)你会没事的。

如果Bullet框架正在绘制,那么它有一个对它的引用,只要框架引用它,GC就不应该收集它

于 2019-06-17T21:50:39.637 回答