【发布时间】:2018-03-03 02:23:39
【问题描述】:
对于我的 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 循环向前部分用于检查预览精灵是否与任何塔精灵矩形碰撞。如果是这样,它将一个变量设置为真,否则为假。
程序然后检查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 程序,请询问。
编辑:Dropbox 链接https://www.dropbox.com/sh/ajwlkwufrxadoqo/AAASwxQPK8gFG-0zixfc2fC1a?dl=0
【问题讨论】:
-
minimal, complete and verifiable example 将帮助我们找到解决方案。
-
可以使用内置的pygame.sprite.collideany(..)吗?