Pygame代码不适用于精灵组中的每个精灵



对于我的pygame塔防程序,我正在尝试弄清楚如何实现与地图上已经放置的其他塔的碰撞。

放置过程会创建一个 48x48 预览精灵,当玩家鼠标出现在游戏屏幕上时,该角色会在网格中移动。塔精灵保存在一个名为tower_sprites的组中。我有这段代码来检查精灵是否与某些地形图块和塔精灵碰撞(这是在精灵更新功能中):

if y < C.map_width and x < C.map_height: #if preview sprite coords are on the game screen (x and y are rounded coords of the preview tower at certain points as each tile is 16x16 while the tower is 48x48)
if live_grid.tilemap[x][y] != 0: #if the coordinate is not grass
self.map_collide.append(1)
else:                            #if the coordinate is grass
self.map_collide.append(0) 
for sprite_object in tower_sprites:         #for each sprite in tower_sprites
print (sprite_object)
if sprite_object.rect.colliderect(self.rect):   #if the rect of the preview sprite collides with a tower sprites rect
self.tower_collision = True
else:
self.tower_collision = False

for 循环向前部分旨在检查预览精灵是否与任何塔精灵 RECT 碰撞。如果是这样,它将变量设置为 true 或 False。

然后,程序检查类中不同函数中的self.tower_collision是否为真,如果是,则向主游戏循环返回一个值:

def collide_boolean(self):
if 1 in self.map_collide: #for map collision
del self.map_collide[:]
return False #False = can't place
if self.tower_collision == True: #for tower collision
return False
else:   #for map collision
del self.map_collide[:]
return True

然而,此代码产生的问题是,它只检查玩家放置的最后一个精灵是否与预览精灵冲突,而不是之前的其他精灵。我希望程序检查所有塔精灵,但我不确定如何做到这一点。

我需要做什么来改变这一点?如果您到目前为止想要该程序的完整保管箱,请询问。

编辑:Dropbox 链接 https://www.dropbox.com/sh/ajwlkwufrxadoqo/AAASwxQPK8gFG-0zixfc2fC1a?dl=0

除非被碰撞的精灵是tower_sprites中的最后一个,否则通过循环的后续迭代将再次用False覆盖self.tower_collision

最新更新