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
Enemy
- Add it to
all_sprites
andenemies
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
80screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
81
82# Create a custom event for adding a new enemy
83ADDENEMY = pygame.USEREVENT + 1
84pygame.time.set_timer(ADDENEMY, 250)
85
86# Instantiate player. Right now, this is just a rectangle.
87player = 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
100while 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 pygame
documentation.
jamesbrown68 on July 11, 2020
Like someone else commented, I had to slow the enemy speed way down on my Windows 10 machine to make the game at all playable. I used ‘self.speed = random.randint(1, 2)’, as anything more than 2 was just a streak across the screen.
But then, that only leaves two speeds, slow and fast. I hunted around and found a way to use a float rather than an integer:
‘self.speed = random.uniform(1,2)
This seemed no different from random.randint(1,2) when it comes to enemy speed.
I also tried values less than 1 and greater than 2, such as (0.5, 2.5) but the results seemed the same. It feels like the slowest speed was 1. Going as high as 3 made some of the enemies into mere blurs–way too fast.
So I was expecting a range of float values, but it feels like perhaps some rounding to the nearest integer was occurring, maybe?