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:
- Create a new
- Add it to
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)) 81 82 # Create a custom event for adding a new enemy 83 ADDENEMY = pygame.USEREVENT + 1 84 pygame.time.set_timer(ADDENEMY, 250) 85 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 108 109 # Did the user click the window close button? If so, stop the loop. 110 elif event.type == QUIT: 111 running = False 112 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) 119 120 # Get the set of keys pressed and check for user input 121 pressed_keys = pygame.key.get_pressed() 122 player.update(pressed_keys) 123 124 # Update enemy position 125 enemies.update()
For more information about the
time module, check out the
Become a Member to join the conversation.