I have a for loop that takes values from a text file, and then creates and adds a bunch of sprites to a group platformlist_list. The for loop will continue until every line of the text file is read.

self.object = Wall(firstarray[0] , int(firstarray[1]), int(firstarray[2]))

print int(firstarray[3]), ' x ', int(firstarray[4]), ' y' 

self.object.rect.x = int(firstarray[3])
self.object.rect.y = int(firstarray[4])


What I want to be able to do is access these created sprites and move them, but if I use this code to try and move all of the sprites in the platform_list group:

if (loadterrain.character.direction == self.left):
    loadterrain.wall.rect.x += self.movementspeed
    loadterrain.object.rect.x += self.movementspeed
if (loadterrain.character.direction == self.right):
    loadterrain.wall.rect.x -= self.movementspeed
    loadterrain.object.rect.x -= self.movementspeed
    loadterrain.floor.rect.x -= self.movementspeed

The only object on screen that will move is the last object that my for loop has created.

I want to be able to access and modify the x and y positions for every sprite inside of the platform_list but have no idea how to do so because from the research I have done indexing the platform_list is unreliable as it is not ordered.

What is the best way for me to access and modify the positions of all the sprites in that group?


So it looks to me like you want to move all of the sprites in the pygame.sprite.Group initialization.platform_list by the same amount. It should not matter that the sprites in the group are not ordered or indexed.

delta_x, delta_y = 0, 0
if (loadterrain.character.direction == self.left):
   delta_x += self.movementspeed
for sprite in initialization.platform_list:
    sprite.rect.move_ip(delta_x, delta_y)

You can get a plain old python list of the sprites with the sprites() method, if you need it sorted for some reason before iterating through it. For example here's some basic y sorting.

sprites = sorted(initialization.platform_list,
                 key= lambda sprite: -sprite.rect.y)
for sprite in sprites: 
    # ...

Just leave a comment if you need any further help.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .