pygame.sprite
Base classes for game objects and the containers that update, draw and collide them in bulk.
On this page
Overview#
The pygame.sprite module provides Sprite, a base class for visible game objects, and Group, a container that manages many sprites. You subclass Sprite, give it an image and a rect, and let groups do the repetitive work.
Syntax#
Python
class Enemy(pygame.sprite.Sprite):
def __init__(self, pos, *groups):
super().__init__(*groups) # optional: join groups immediately
self.image = pygame.Surface((32, 32))
self.rect = self.image.get_rect(center=pos)
def update(self, dt):
self.rect.x += round(100 * dt)
enemies = pygame.sprite.Group()
enemies.add(Enemy((100, 100)))
enemies.update(dt) # calls update(dt) on each sprite
enemies.draw(screen) # blits sprite.image at sprite.rectSprite#
| Member | Meaning |
|---|---|
image | Surface to draw (you set it). |
rect | Position and size (you set it). |
update(*args, **kwargs) | Does nothing by default; override it. Groups pass their arguments through. |
kill() | Removes the sprite from every group it belongs to. |
alive() | True if the sprite is in any group. |
groups() | The groups containing the sprite. |
add(*groups) / remove(*groups) | Join or leave groups. |
Group#
| Member | Meaning |
|---|---|
add(*sprites), remove(*sprites), empty() | Manage membership. |
sprites() | A list copy of the sprites (safe to modify while looping). |
update(*args, **kwargs) | Calls update on every sprite. |
draw(surface) | Blits every sprite. Draw order is not guaranteed for Group. |
has(*sprites), len(group), in | Queries. |
Special groups: GroupSingle holds one sprite (handy for the player), RenderUpdates returns changed areas from draw, and LayeredUpdates draws by layer so you control what appears in front.
Collision helpers#
| Function | Returns |
|---|---|
spritecollide(sprite, group, dokill, collided=None) | List of sprites in group that hit sprite. dokill=True kills them. |
spritecollideany(sprite, group, collided=None) | First hit or None. |
groupcollide(group1, group2, dokill1, dokill2, collided=None) | Dict: each sprite in group1 that hit something → list of sprites it hit. |
collide_rect, collide_rect_ratio(r) | Rect tests (optionally scaled). |
collide_circle, collide_circle_ratio(r) | Circle tests using a sprite's radius attribute if present. |
collide_mask | Pixel-perfect test using a sprite's mask attribute or one built from its image. |
Practical example#
sprite_example.pyDownload
"""pygame.sprite: Sprite subclasses, Group, update/draw, kill() and group collisions."""
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 360))
clock = pygame.time.Clock()
class Bubble(pygame.sprite.Sprite):
def __init__(self, *groups):
super().__init__(*groups) # adds itself to the groups
r = random.randint(8, 20)
self.image = pygame.Surface((r * 2, r * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, (157, 194, 255), (r, r), r, 3)
self.rect = self.image.get_rect(center=(random.randint(20, 620), 380))
self.speed = random.uniform(40, 120)
self.radius = r # used by collide_circle
def update(self, dt):
self.rect.y -= round(self.speed * dt)
if self.rect.bottom < 0:
self.kill() # removes it from every group
class Spike(pygame.sprite.Sprite):
def __init__(self, x, *groups):
super().__init__(*groups)
self.image = pygame.Surface((24, 24), pygame.SRCALPHA)
pygame.draw.polygon(self.image, (232, 93, 82), [(12, 0), (24, 24), (0, 24)])
self.rect = self.image.get_rect(midtop=(x, 120))
self.radius = 12
all_sprites = pygame.sprite.Group()
bubbles = pygame.sprite.Group()
spikes = pygame.sprite.Group()
for x in range(60, 640, 120):
Spike(x, all_sprites, spikes)
popped = 0
running = True
while running:
dt = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if random.random() < 0.08:
Bubble(all_sprites, bubbles)
all_sprites.update(dt) # Spike has no update(); Sprite.update does nothing by default
hits = pygame.sprite.groupcollide(bubbles, spikes, True, False, pygame.sprite.collide_circle)
popped += len(hits)
screen.fill((20, 26, 46))
all_sprites.draw(screen)
pygame.display.set_caption(f"Sprites: {len(all_sprites)} popped: {popped}")
pygame.display.flip()
pygame.quit()Common errors#
AttributeError: ... has no attribute '_Sprite__g': you forgotsuper().__init__()in your sprite's__init__.AttributeError: ... has no attribute 'image':group.draw()needs bothimageandrect.- Sprites drawn in the wrong order: use
LayeredUpdateswith a_layerattribute, or several groups drawn in order. - Mask collisions with animated sprites: rebuild
self.maskwhen the image changes.