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

问题描述 投票:0回答:1

对于我的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

python pygame
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.