Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Is there a way to shufle a group of sprites created with:

pygame.sprite.Group()

I have tried using random.shuffle but it apparently doesn't work on sprite groups.

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Since groups are an iterator, you can use:

sprs = list(spr_group)
random.shuffle(sprs)

You should not rely on Python's hashing order to randomize sprites for you. It is not a good RNG.

share|improve this answer
    
oh, great, thanks –  user3956 May 2 '11 at 14:01

According to pygame documentation:

The Sprites in the Group are not ordered, so drawing and iterating the Sprites is in no particular order. http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group

I think the best you can do is not to use the Group, and make your own group mechanism. If you need only ordered update then use http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.OrderedUpdates

share|improve this answer
    
Thanks, I will keep the sprite group though. Your first sentence is correct, each time I create/empty/create the group it comes back in a different order, which is just what I need. –  user3956 May 2 '11 at 9:31
    
-1. If you desperately need the group to shuffle you can simply subclass Group, you don't need to avoid it. But you probably don't want the group per se to be shuffled; you just want a shuffled copy of the sprites in the group. –  user744 May 2 '11 at 13:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.