Pygame problem working with pygame.sprite.Group()

Recommended Posts

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 on other sites
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.

Create an account

Register a new account

• Forum Statistics

• Total Topics
628305
• Total Posts
2981962

• 9
• 12
• 11
• 12
• 11