Menu
CoddyTech

The Sprite Class

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

Every game object so far has had an image, a Rect, an update and a way to be drawn. pygame has a class built for exactly that: pygame.sprite.Sprite. Your game objects become subclasses of it:

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

Three rules. Call super().__init__() first: it sets up what the Sprite class needs inside. Name the picture self.image and the position self.rect, exactly: pygame's own code reads those two names. Put the per-frame rules in update.

The ship image is loaded once at the top, as ship_image, and the class uses it. For now, draw the sprite with a blit: screen.blit(player.image, player.rect). The next lesson lets pygame draw it.

challenge icon

Challenge

Medium
  1. Write class Player(pygame.sprite.Sprite) as above: self.image is ship_image, self.rect has its bottom middle at (320, 470).
  2. Its update moves the Rect 6 pixels left or right with the arrows and clamps it to the window: move the starter's lines into it.
  3. Make player = Player(), call player.update() each frame and blit player.image at player.rect.

Try it yourself

import pygame

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

ship_image = pygame.image.load("assets/images/ship.png").convert_alpha()
ship_rect = ship_image.get_rect(midbottom=(320, 470))

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

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

    screen.fill((20, 22, 40))
    screen.blit(ship_image, ship_rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground