添加后,列表的最后一项不会更改

时间:2015-10-03 14:52:39

标签: python pygame

我正在尝试在pygame库的帮助下编写一个小型滚动游戏。当我试图在运行时添加障碍时,我注意到pygame / python中有一些奇怪的行为。

class ObstaclesGroup(pygame.sprite.Group):
    def update(self, offset):    
        lastSprite = self.sprites()[-1]
        if lastSprite.rect.x < distance + 640:
            # add obstacle with a distance of 300 px to the previous
            self.add(Obstacle(distance + 940))
            sprite = self.sprites()[-1]

            # often the values are the same, although the last one 
            # should be 300px bigger
            # update: they even seem to be identical
            if (lastSprite == sprite):
                print (lastSprite.rect.x,  "   ", sprite.rect.x)

在第二次执行下部(在&#39; if&#39;之后)后,lastSprite和sprite的x坐标似乎相同。

以下是控制台的一些示例输出:

740     1043
1043     1043
1043     1043
1043     1043
1043     1344
1344     1344
1344     1648
1648     1648
1648     1648
1648     1648
1648     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     1953
1953     2326
2326     2326
2326     2326
2326     2326
2326     2326
2326     2326
2326     2326
2326     2326
2326     2288
2288     2288
2288     2288
2288     2288
2288     2288
2288     2288
2288     2288
2288     2288
2288     2288
2288     2288
2288     2288

sprite(Obstacle)似乎没有被正确添加到精灵组中,尽管它们被绘制(我可以看到具有不同偏移的多个障碍,因为它在每个游戏循环周期中都会增加)。 可能是什么问题?

更新 如果它们结束时添加:两个精灵是相同的。

1 个答案:

答案 0 :(得分:3)

http://caniuse.com显示sprite.Group.sprites()的结果只是字典键列表。字典是无序的,因此您无法确定该列表中的最后一个精灵是您添加的最后一个精灵。
试试这个:

class ObstaclesGroup(pygame.sprite.Group):
    def update(self, offset):

        # function that returns the x-position of a sprite
        def xPos(sprite):
            return sprite.rect.x

        # find the rightmost sprite
        lastSprite = max(self.sprites(), key=xPos)
        if xPos(lastSprite) < distance + 640:
            # add obstacle with a distance of at least 300 px to the previous
            self.add(Obstacle(distance + 940))

顺便说一句==检查是否相同,而不是身份。如果您想知道自己是否正在处理同一个对象,则应使用is;)