简体   繁体   中英

pygame: draw() currently draws all sprites in a group. How can I just draw a specific one

<Group(4 sprites)>

I have 4 sprites in a group they all ready to draw with the line,

stuff_to_draw.draw(screen)

They all currently draw at the same time.

Is it possible to do something like this

stuff_to_draw[0].draw(screen)

I've looked at

[https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group][1]

Although I cannot find any helpfull information about selecting a specific element in the group.

What am I trying to achieve?

The sprite group currently holds a answer sprite which consists of a location (x,y) and a image of the letter to blit.

Currently accross all maps the answer is blitted instead of on the current question. So I would like to be able to say on question one *stuff_to_draw[0]* then question two *stuff_to_draw[1]*.

First, add a self.type to your each of your sprites. Give it a value, such as self.type = 1 . Then call this when you want to draw a certain sprite or group of sprites:

for sprite in group: #Replace group with your sprite group
    if sprite.type == 1: #Or whatever type you want
        sprite.draw(screen)
    elif sprite.type == 2:
        sprite.draw(screen)
    #Etc...

Next, in your sprite class make sure you inherit from pygame.sprite.Sprite :

class my_sprite_class(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__()
        #Etc...

    #Add this draw function so we can draw individual sprites
    def draw(self, screen):
        screen.blit(self.image, self.rect)

I forgot that individual sprites don't have a draw function, just the groups. @pmoleri @jackdh my bad

Please read this post here to get an idea of what the class can do.

If you have any more questions just comment below.

You could blit any individual sprite, but I don't recommend it. This would be the way:

sprite = stuff_to_draw.sprites()[0]
screen.blit(sprite.image, sprite.rect)

My recommendation is to keep in the Sprites Group what you want to draw at a moment, and keep the rest in a separate list or group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM