我正在写一个游戏,我有一个坦克,每个坦克都可以射击子弹。 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
答案 0 :(得分:0)
我猜coords
是list
。因此,当您将列表从Tank
传递到Bullet
时,您会对单个list
进行操作,因此更改将是"可见"在Tank
和 Bullet
内。
复制list
:
def shoot_bullet(self):
self.bullet = Bullet(self.coords[:], self.direction)
或使用其他数据结构,例如tuple
或者,因为您使用pygame,Rect
。