Friday, May 15, 2015

python - sprite group doesn't support indexing


I have a sprite group created with pygame.sprite.Group() (and add sprites to it with the add method)


How would I retrieve the nth sprite in this group?


Code like this does not work:


mygroup = pygame.sprite.Group(mysprite01)
print mygroup[n].rect


It returns the error: group object does not support indexing.


For the moment I'm using the following function:


def getSpriteByPosition(position,group):
for index,spr in enumerate(group):
if (index == position):
return spr
return False

Although working, it just doesn't seem right...



Is there a cleaner way to do this?


EDIT: I mention a "position" and index but it's not important actually, returning any single sprite from the group is enough



Answer



What do you need the index for? Since sprites are hashed, the index is not stable; since you can't use it to easily find the sprite again, I don't know why you'd want to store it; and since you can't easily get from a sprite to an index I don't know how you got it in the first place.


If you need a reference to a sprite, reference the sprite itself, not its index.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...