Menu
CoddyTech

A List of Enemies

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 15 of 39.

One enemy is an object now. The other two still need their own Rects and blits. Put all three in a list, as the star field did with its stars, and two short loops run them all:

enemies = [Enemy(red, 100, 50), Enemy(green, 300, 50)]

for enemy in enemies:
    enemy.update()

A list can be written out item by item in square brackets, as here, or built with append in a loop. Each enemy in it moves by its own Rect.

Keep every enemy in the list only once. An enemy that is also updated on its own, outside the loop, moves twice each frame.

challenge icon

Challenge

Medium

Keep all three enemies in one list.

  1. Make enemies, a list of three Enemy objects: red centred at (160, 100), green at (320, 100) and yellow at (480, 100).
  2. Update every enemy in the list in the loop, and draw every one after the fill.
  3. Remove red_enemy, the green and yellow Rects and their lines.

Press Play: three enemies fall as before. Then Check.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Enemy Rain")
clock = pygame.time.Clock()

red = pygame.image.load("assets/images/enemy_red.png").convert_alpha()
green = pygame.image.load("assets/images/enemy_green.png").convert_alpha()
yellow = pygame.image.load("assets/images/enemy_yellow.png").convert_alpha()

class Enemy:
    def __init__(self, image, x, y):
        self.image = image
        self.rect = image.get_rect(center=(x, y))
        self.speed = 2

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > 480:
            self.rect.bottom = 0

    def draw(self, screen):
        screen.blit(self.image, self.rect)


red_enemy = Enemy(red, 160, 100)
green_rect = green.get_rect(center=(320, 100))
yellow_rect = yellow.get_rect(center=(480, 100))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    red_enemy.update()
    for rect in (green_rect, yellow_rect):
        rect.y += 2
        if rect.top > 480:
            rect.bottom = 0

    screen.fill((20, 22, 40))
    red_enemy.draw(screen)
    screen.blit(green, green_rect)
    screen.blit(yellow, yellow_rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground