在pygame中共享两个对象的内存

时间:2014-05-31 12:55:48

标签: memory pygame share

我正在写一个游戏,我有一个坦克,每个坦克都可以射击子弹。 Tank和Bullet类都有坐标和方向。当我们射击子弹时,它会获得坦克的坐标,但是当我在move方法中更改子弹的坐标时,坦克的坐标也会发生变化。如何在不产生大量变量的情况下避免这种内存共享?

class Tank:

    def __init__(self, coords, direction):
        self.coords = coords
        self.direction = direction
        self.bullet = None

    def shoot_bullet(self):
        self.bullet = Bullet(coords, direction)

class Bullet:

    def __init__(self, coords, direction):
        self.coords = coords
        self.direction = direction

    def _move(self):
         self.coords[0] += 4

1 个答案:

答案 0 :(得分:0)

我猜coordslist。因此,当您将列表从Tank传递到Bullet时,您会对单个list进行操作,因此更改将是"可见"在Tank Bullet内。

复制list

def shoot_bullet(self):
    self.bullet = Bullet(self.coords[:], self.direction)

或使用其他数据结构,例如tuple或者,因为您使用pygame,Rect