我在做一个坦克游戏,我有坦克和子弹。当我开火时,执行以下方法:
def newshot(self,tank):
shot = bullet()
shot.loc = tank.loc
shot.speed = tank.direction
self.shots.append(shot)
loc是显示位置[x,y]的列表,speed和direction是显示速度[dx,dy]的列表。你知道吗
为了移动每个子弹,速度向量被添加到for循环中的位置。但是每当我改变子弹的位置时,我的坦克的位置也会改变(我在for循环前后打印了一个坦克的位置)。 我解决问题的方法是
shot.loc = tank.loc
是的
shot.loc = [tank.loc[0],tank.loc[1]]
我的问题是区别在哪里?
你需要
deepcopy
这个列表。即:下面是它的工作原理:
您复制了引用而不是值,这意味着两个变量指向同一个对象。你知道吗
从https://docs.python.org/2/library/copy.html:
将
tank.loc
列表复制到shot.loc
的最简单方法是对整个列表进行切片:但其他有效的建议请参见https://stackoverflow.com/a/2612815/768176。你知道吗
使用时:
shot.loc
和tank.loc
是对同一列表的引用。你知道吗要复制列表,请使用:
相关问题 更多 >
编程相关推荐