๐Ÿ‘พ Adding Enemies | myBetabox

๐Ÿ‘พ Adding Enemies

Keyboard Guide

Adding Enemies

The Code Explained

Let’s code to set up the enemy class and objects like we did for the projectiles.

self.image = pygame.Surface((40, 40))
self.image = enemy_img
self.image = pygame.transform.scale(enemy_img(40, 40))
self.rect = self.image.get_rect

You can scale, or change the size, of the enemy image to any width and height you want but we recommend 40×40.

Now we’re ready to give the enemies starting spawn positions! Let’s use the random import we coded at the beginning of the project to give enemies random starting spots. We’ll have them spawn offscreen then float down into the game area.

self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)

Also set the enemy speed! You can change the number ranges to be anything besides 4-8 but know the higher the number, the faster the speed.

self.speedy = random.randrange(4,8)

Update the enemy positions during gameplay. This code tells the enemies to come down the screen.

self.rect.y += self.speedy

If an enemy reaches the bottom without hitting you then we should spawn a new enemy at the top and including its speed. Let’s do this with an if statement.

if self.rect.top > HEIGHT + 10:
ย self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
ย  ย self.speedy = random.randrange(4, 8)

We’ve just coded the enemy class and objects, awesome!