Pygame by examples 1: kill a sprite after a while…

One example is better than a thousand words

Starting a new serie called Pygame by examples, to show a lot of simple but practical example of usage of pygame tools. In this example we will see how to “kill” a sprite some time after an action, like the key pressed.

The Enemy class

When we make an istance of the Enemy sprite we:

class Enemy(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = pg.Surface((50, 30))
        self.image.fill(pg.Color('sienna1'))
        self.rect = self.image.get_rect(center=pos)
        self.time = None

    def update(self):
        if self.time is not None:  # If the timer has been started...
            # and 500 ms have elapsed, kill the sprite.
            if pg.time.get_ticks() - self.time >= 1500:
                self.kill()

The main function

Here we create the window and set the clock. Create a group and the sprite (that will put the sprite in the group object that will be drawn into the while loop that follows.

In the while loop:

def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    enemy = Enemy((320, 240), all_sprites)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.KEYDOWN:
                # Start the timer by setting it to the current time.
                enemy.time = pg.time.get_ticks()

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)

This is the window with the sprite. If you press a key, the sprite will be “killed”, aka destroyed and will disappear when the window is refreshed after 1500 frames.


Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts