So I\'ve gotten to the point in my program where I need to create a group for some sprites that the player can collide with without dying (like some other sprites I may have
Just call the super __init__
function with the list of groups. For example:
def __init__(self):
pygame.sprite.Sprite.__init__(self, self.groups)
Then, in each class of your hierarchy, you should define an attribute self.groups and the super constructor will make the work of adding each instance to its groups. This is the cleanest solution in my opinion. Otherwise, just call the super constructor explicitly with the list of groups in every class.
I know this question has already been answered, but the best method is like what kelwinfc suggested. I'll elaborate so it's more understandable.
# First, create you group
gems = pygame.sprite.Group()
class Jewel (pygame.sprite.Sprite): # Inherit from the Sprite
def __init__ (self, *args): # Call the constructor with whatever arguments...
# This next part is key. You call the super constructor, and pass in the
# group you've created and it is automatically added to the group every
# time you create an instance of this class
pygame.sprite.Sprite.__init__(self, gems)
# rest of class stuff after this.
>>> ruby = Jewel()
>>> diamond = Jewel()
>>> coal = Jewel()
# All three are now in the group gems.
>>> gems.sprites()
[<Jewel sprite(in 1 groups)>, <Jewel sprite(in 1 groups)>, <Jewel sprite(in 1 groups)>]
You can also add more with gems.add(some_sprite)
and likewise remove them with gems.remove(some_sprite)
.
To answer your first question; to create a group you would do something like this:
gems = pygame.sprite.Group()
Then to add a sprite:
gems.add(gem)
Regarding the attributes for the group you'd like to edit it depends what they are. For example you could define something like this to indicate the direction of the group:
gems.direction = 'up'
Easier yet you can pass the sprites directly on to the constructor:
gems = pygame.sprite.Group(gem1, gem2)