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:

  • We create a Surface (the sprite)
  • color it (sieena1)
  • crete the rect
  • put the time to None
  • the update method will check if the time is passed since the action took place
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:

  • we get eventual click on the “x” button of the window to close it
  • get the keydown press and put the time to the actual value of ticks (to check how much time passes)
  • update the group (all_sprites, but there is just one sprite)
  • colors the screen… (to delete past images… unuseful at the moment when it’s all still)
  • draws the group of all (1 for now) sprites
  • update the screen with flip
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
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.