[Tutor] Pygame related question

Peter Otten __peter__ at web.de
Sun May 25 14:34:42 CEST 2014


diliup gabadamudalige wrote:

> I need to random pick a pygame sprite from a sprite class.
> The random module does not allow this to be used on a group.
> Is the shortest way to raed in the attributes thatr I need into a list and
> then random pick that or is there a shorter way? Sample code is given
> below.
> 
>                         scalelist=[]
>                         for scale in all_scales:
>                             scalelist.append( [scale.name,
>                             scale.scaletype]
> )
> 
>                         scale = random.choice(scalelist)
> 
> where all_scales is a sprite class with 45 objects.
> I append the 2 attributes of each sprite to a scalelist with the above
> function and then random pick an item from the scalelist.
> 
> Is this the shortest way?

Not the shortest, but probably an efficient way: subclass 
pygame.sprite.OrderedUpdates and use the subclass to group your sprites:

# untested
class MyGroup(pygame.sprite.OrderedUpdates):
    def __getitem__(self, index):
        return self._spritelist[index]

group = MyGroup(sprite1, sprite2, ...)
some_sprite = random.choice(group)



More information about the Tutor mailing list