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.
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?