The Sprite Class
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 17 of 39.
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 -= 6Three 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
MediumTurn the ship into a Sprite.
- Write
class Player(pygame.sprite.Sprite)as above:self.imageisship_image,self.recthas its bottom middle at(320, 470). - Move the starter's movement and clamp lines into its
update. - Make
player = Player(), callplayer.update()each frame and blitplayer.imageatplayer.rect.
Press Play and hold the arrows: the ship moves as before. Then Check.
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
4Sprites and Groups
The Sprite ClassGroupsRemove with kill()Catch with spritecollideGroup Against GroupPractice on your own: Pygame playground