Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 41 ยท Sprites and Collision

Sprites and Groups in Pygame

Organize game objects with pygame.sprite.Sprite and Group. Subclass Sprite, give it image and rect, update and draw whole groups, remove with kill, and use layers.

When a game has one ball and one paddle you can manage them by hand. Once there are twenty enemies, forty bullets and a handful of power-ups, you need structure. Pygame's pygame.sprite module gives you two small classes for that: Sprite, a base class for game objects, and Group, a container that updates and draws all its members with one call. This lesson shows how to use both and why they make games easier to grow.

What is a sprite?

A sprite is any visible game object: a player, an enemy, a coin, a bullet. In Pygame a sprite is an instance of a class that inherits from pygame.sprite.Sprite and follows a simple convention:

  • self.image: the Surface to draw.
  • self.rect: the Rect that says where to draw it (and what it collides with).
  • update(...): called every frame to change the sprite's state.
Python
class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()                         # don't forget this!
        self.image = pygame.Surface((40, 40))
        self.image.fill((90, 200, 120))
        self.rect = self.image.get_rect(center=(x, y))
        self.speed = 300

    def update(self, dt):
        keys = pygame.key.get_pressed()
        self.rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * self.speed * dt
        self.rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * self.speed * dt

Calling super().__init__() is required: the base class sets up the internal bookkeeping that groups use. Also note that the rect is where the sprite is; the sprite's position lives in the rect (or in a separate float vector copied into it).

classDiagram
    class Sprite {
      +image
      +rect
      +update()
      +kill()
    }
    class Player
    class Enemy
    class Bullet
    Sprite <|-- Player
    Sprite <|-- Enemy
    Sprite <|-- Bullet
    class Group {
      +add()
      +remove()
      +update()
      +draw(surface)
    }
    Group o-- Sprite

Every game object extends Sprite; Groups hold sprites and operate on all of them.

Groups

A Group is a container for sprites with three jobs: update all, draw all, and make removal easy.

Python
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()

player = Player(400, 500)
all_sprites.add(player)

for i in range(5):
    enemy = Enemy(100 + i * 120, 60)
    enemies.add(enemy)
    all_sprites.add(enemy)

Then, once per frame:

Python
all_sprites.update(dt)          # calls sprite.update(dt) on every member
screen.fill((15, 15, 25))
all_sprites.draw(screen)        # blits sprite.image at sprite.rect for every member

The arguments to Group.update() are passed straight through to each sprite's update(), so use the same signature in all your sprite classes (or accept *args).

Many groups, one sprite

A sprite can belong to any number of groups at once. This is the key to simple collision code: keep an all_sprites group for drawing and updating, and specialized groups (enemies, bullets, walls) for collision checks.

Group methods

Method Purpose
group.add(sprite, ...) / group.remove(...) Put sprites in or out
sprite.add(group) / sprite.remove(group) The same from the sprite's side
sprite.kill() Remove the sprite from all its groups (it is then garbage-collected)
group.empty() Remove every sprite
group.sprites() A list of members
len(group), sprite in group, for s in group Size, membership, iteration
group.has(sprite) Membership test
group.update(*args) Update all
group.draw(surface) Draw all

kill() is how an enemy disappears when shot, a bullet when it leaves the screen, a coin when collected:

Python
def update(self, dt):
    self.rect.y -= self.speed * dt
    if self.rect.bottom < 0:
        self.kill()

Warning: Never remove sprites from a group while iterating over it with a plain for loop. Iterate over group.sprites() (a copy) or use kill() from inside update(), which is safe.

Try it: sprites without a window

Sprites do not need a display, so we can run a whole mini-game state: create a few sprites, update them, draw them onto an off-screen surface and print it.

Python Sprites, groups and kill()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The red block leaves the field first. kill() removed it from both groups, so len(all_sprites) and len(fast) drop together.

Layers and draw order

Group.draw() draws in an unspecified order for plain groups (generally insertion order), so for correct overlap use LayeredUpdates:

Python
all_sprites = pygame.sprite.LayeredUpdates()
all_sprites.add(floor, layer=0)
all_sprites.add(player, layer=2)
all_sprites.add(tree, layer=1)

Higher layers draw on top. You can also set a _layer attribute on the sprite class. Other group types: RenderUpdates (returns dirty rects), GroupSingle (holds exactly one sprite, ideal for player) and OrderedUpdates (strict insertion order).

Python LayeredUpdates controls what is in front

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Controlling sprites

Keep all of a sprite's behavior inside the sprite. The main loop stays tiny:

Python
all_sprites.update(dt)

and each class decides what to do: the player reads the keyboard, an enemy follows a pattern, a bullet flies and dies. To let outside code control a sprite (for example a click that selects it), give it methods such as jump(), take_damage(), set_target(pos), and call those from the event loop. Events trigger actions; update() applies them over time.

When to use sprites

Use pygame.sprite whenever you have several game objects of the same kind. For a game with only a ball and two paddles, plain Rects are fine. You can mix both approaches: sprite groups for the dynamic world and a plain surface for the UI.

Common mistakes

  • Forgetting super().__init__(): groups then raise AttributeError about __g.
  • Forgetting to create self.image or self.rect: Group.draw needs both.
  • Adding a sprite to all_sprites but not to enemies, so collisions never find it.
  • Modifying a group while iterating over it.
  • Changing self.rect size but not updating self.image (or the other way round).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which two attributes does Group.draw() require every sprite to have?

    draw blits sprite.image at sprite.rect.
  2. 2. What does sprite.kill() do?

    Once removed from all groups and no longer referenced, the sprite is garbage collected.
  3. 3. Why do games usually keep both an all_sprites group and specialized groups like enemies?

    A sprite can be in several groups, so you can update everything together and still check only enemies against bullets.
  4. 4. Which group type controls drawing order with layers?

    LayeredUpdates draws lower layers first, so higher layers appear on top.

Summary

  • A sprite is a class with image, rect and update(), inheriting from pygame.sprite.Sprite.
  • Call super().__init__() in your constructor.
  • Groups update and draw all their members; a sprite may be in several groups.
  • kill() removes a sprite from every group.
  • Use LayeredUpdates for draw order and GroupSingle for the player.
  • Put behavior inside the sprite and keep the main loop small.

Next: Collision Detection