Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 3 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

As other already said, the sprite.Group iterator yield its members in an unordered way (like a dict, not like a a list).

So if you're after a simple unordered list (not properly shuffled with a random method - if you want that follow user744's answer), just get what it gives by default.

The "problem" here is quite the contrary: how to get an ordered list of sprites from it (or a sprite by its index in the group)

share|improve this answer

Your Answer

 
discard

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