Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.

Custom Events

In this lesson, you’ll add custom events to your game to create new enemies. The design calls for enemies to appear at regular intervals. This means that, at set intervals, you need to do two things:

  1. Create a new Enemy
  2. Add it to all_sprites and enemies

Let’s see how to create a custom event that’s generated every few seconds. You can create a custom event by naming it:

78 # Create the screen object
79 # The size is determined by the constant SCREEN_WIDTH and SCREEN_HEIGHT
80 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
82 # Create a custom event for adding a new enemy
83 ADDENEMY = pygame.USEREVENT + 1
84 pygame.time.set_timer(ADDENEMY, 250)
86 # Instantiate player. Right now, this is just a rectangle.
87 player = Player()

Next, you need to insert this new event into the event queue at regular intervals throughout the game. That’s where the time module comes in. Line 84 fires the new ADDENEMY event every 250 milliseconds, or four times per second. You call .set_timer() outside the game loop since you only need one timer, but it will fire throughout the entire game.

Add the code to handle your new event:

 99 # Main loop
100 while running:
101     # Look at every event in the queue
102     for event in pygame.event.get():
103         # Did the user hit a key?
104         if event.type == KEYDOWN:
105             # Was it the Escape key? If so, stop the loop.
106             if event.key == K_ESCAPE:
107                 running = False
109         # Did the user click the window close button? If so, stop the loop.
110         elif event.type == QUIT:
111             running = False
113         # Add a new enemy?
114         elif event.type == ADDENEMY:
115             # Create the new enemy and add it to sprite groups
116             new_enemy = Enemy()
117             enemies.add(new_enemy)
118             all_sprites.add(new_enemy)
120     # Get the set of keys pressed and check for user input
121     pressed_keys = pygame.key.get_pressed()
122     player.update(pressed_keys)
124     # Update enemy position
125     enemies.update()

For more information about the time module, check out the pygame documentation.

Comments & Discussion

Become a Member to join the conversation.