Menu
CoddyTech

Groups

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 17 of 36.

Sprites come in crowds: enemies, lasers, coins. A Group holds many sprites and does the same thing to all of them:

enemies = pygame.sprite.Group()
for i in range(5):
    enemies.add(Enemy(64 + i * 128, 60))

Two calls in the loop replace the loops you wrote over a list:

enemies.update()
enemies.draw(screen)

enemies.update() calls update() on every sprite in the group. enemies.draw(screen) blits every sprite's self.image at its self.rect: that is why those two names must be exact. A sprite in a group needs no draw method of its own.

A group also knows its size, len(enemies), and you can loop over it with for enemy in enemies:. Draw the group after the fill, like any other picture.

challenge icon

Challenge

Medium
  1. Replace enemy with a Group named enemies holding five Enemy sprites, centred at x = 64, 192, 320, 448 and 576, all at y = 60.
  2. Call enemies.update() each frame.
  3. Draw them with enemies.draw(screen), after the fill.

Try it yourself

import pygame

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

ship_image = pygame.image.load("assets/images/ship.png").convert_alpha()
enemy_image = pygame.image.load("assets/images/enemy_red.png").convert_alpha()


class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = ship_image
        self.rect = self.image.get_rect(midbottom=(320, 470))

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= 6
        if keys[pygame.K_RIGHT]:
            self.rect.x += 6
        self.rect.clamp_ip(screen.get_rect())


class Enemy(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = enemy_image
        self.rect = self.image.get_rect(center=(x, y))

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


player = Player()
enemy = Enemy(320, 60)

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

    player.update()
    enemy.update()

    screen.fill((20, 22, 40))
    screen.blit(enemy.image, enemy.rect)
    screen.blit(player.image, player.rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Sprites and Images

Practice on your own: Pygame playground