user2737037
user2737037

Reputation: 1157

Last item of list does not change after adding

I am trying to write a small scroller game with help of the pygame library. When I tried to add obstacles at runtime, I noticed some odd behaviour in 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)

After the lower part (after 'if') gets executed the second time, the x coordinates of lastSprite and sprite seem to be the same quite a lot.

Here is some example output from the console:

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

The sprites (Obstacle) seem not to be added properly to the spritegroup, although they are drawn (I can see multiple obstacles with different offsets because it is increased in every gameloop cycle).
What could be the problem?

UPDATE: Added if at they end: the two sprites are identical.

Upvotes: 1

Views: 64

Answers (1)

swenzel
swenzel

Reputation: 7173

The source reveals that the result of sprite.Group.sprites() is just a list of dictionary keys. Dictionaries are unordered, so you cannot be sure that the last sprite in that list is the last one you added.
Try this:

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))

And by the way == checks for equality, not for identity. If you want to know whether you're dealing with the same object, you should use is ;)

Upvotes: 3

Related Questions