Menu
CoddyTech

Objects with Images

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

The enemies are images moving on Rects, and the starter keeps three Rects and three blits by hand. A class can hold an image and its Rect together:

class Enemy:
    def __init__(self, image, x, y):
        self.image = image
        self.rect = image.get_rect(center=(x, y))
        self.speed = 2

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

    def draw(self, screen):
        screen.blit(self.image, self.rect)

The image is passed in, not loaded in __init__. Load each file once at the top and hand the same Surface to every enemy that wears it: ten red enemies share one red picture. Each enemy gets its own Rect, though, so each moves on its own.

Moving the enemy is moving its Rect, and drawing it is blitting its image at the Rect: the two attributes every game object in this section has.

challenge icon

Challenge

Medium
  1. Write the class Enemy with __init__(self, image, x, y), update(self) and draw(self, screen), as above: the Rect centred at (x, y), moving down 2 pixels a frame, back above the top once it is below the window.
  2. Make enemies, a list of three: the red one centred at (160, 100), green at (320, 100), yellow at (480, 100).
  3. Update and draw every enemy in the list; remove the three Rects.

Try it yourself

import pygame

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

red = pygame.image.load("assets/images/enemy_red.png").convert_alpha()
green = pygame.image.load("assets/images/enemy_green.png").convert_alpha()
yellow = pygame.image.load("assets/images/enemy_yellow.png").convert_alpha()

red_rect = red.get_rect(center=(160, 100))
green_rect = green.get_rect(center=(320, 100))
yellow_rect = yellow.get_rect(center=(480, 100))

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

    for rect in (red_rect, green_rect, yellow_rect):
        rect.y += 2
        if rect.top > 480:
            rect.bottom = 0

    screen.fill((20, 22, 40))
    screen.blit(red, red_rect)
    screen.blit(green, green_rect)
    screen.blit(yellow, yellow_rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sprites and Images

Practice on your own: Pygame playground