how to display only a few sprites from a group at a time

Question:

i wanted to make a game start screen and wanted to show only a few buttons at a time from a group, but i did not want to create multiple groups for each screen as i think its not optimal.

i have currently used this, but it draws all buttons on all screens.

if screen_mode == 'main':
        buttons_group.draw(screen, [play_buttons, option_buttons])
elif screen_mode == 'options':
        buttons_group.draw(screen, [credit_buttons])

should i just create a new group for each screen_mode?

Asked By: Frenzymouse

||

Answers:

There is not solution using on single pygame.sprite.Group and pygame.sprite.Group.draw. However, there are many other options. Here are a few of them:

  1. Use multiple pygame.sprite.Groups. Put the sprites you want to show into a group and draw only that group. There is no downside to this approach. The groups only contain a reference to the sprites.

  2. Do not use pygame.sprite.Group.draw, but iterate through the sprites and blit only the sprites that meet a certain condition

    for sprite in buttons_group.sprites():
        if sprite.evalaute_your_condition():
            screen.blit(sprite.image, sprite.rect)
    
  3. Use pygame.sprite.LayeredDirty and pygame.sprite.DirtySprite. DirtySprite have a visible attribute. With this attribute you can set the visibility of the sprite.

Answered By: Rabbid76
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.