Sign in to follow this  
Kada

Pygame problem working with pygame.sprite.Group()

Recommended Posts

Kada    100
Hi, I have recently learned about sprite groups. While they are documented and described as extremely helpful when working with more than one sprite of a particular type, I seem to have noticed there is something sprite groups wont allow me to do, which makes me feel like they are pointless to work with. Let's say I have a unit class that gets a circle drawn around the unit when it is selected, I would put this in my class' draw method:
def draw(self):
     screen.blit(self.image, self.rect)
     if self.selected:
          pygame.draw.circle(screen, (0, 255, 0), self.center, 6)


Pretty simple right? Well the sprite group draw method does this: "Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect for the position." What this is saying is that it will only draw the image, not everything I want drawn along with it inside the draw method (which can potentially be HP Bars, Selection Rings, any more). Should I just do away with sprite groups entirely and do everything like this?
[...]
myObjects = []
[...]
for object in myObjects:
    object.update()

for object in myObjects:
    object.draw()

Share this post


Link to post
Share on other sites
Hollower    685
If we're looking at a subclass of pygame.sprite.Sprite, this is really an OO-design issue. You have made these sprite objects have extra responsibilities outside the realm of being sprites. The sprite isn't what's selected, the unit is. You should have a unit class which has a sprite attribute and a selected attribute. Or, if I was coding this, I would maintain a completely separate list of "selected units" and draw the circles in a separate loop iterating over that list (no more if checks!). I can't think of a reason a unit itself needs to know it is selected. Maybe some sort of "command dispatcher", if this is like an RTS, but not the individual units. Perhaps I'm guessing too much about the nature of your game based on the fact that you are selecting units.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this