Objects with Images
Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 14 of 39.
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
MediumTurn the red enemy into an object.
- Under the image loads, write the class
Enemyshown above. - Replace
red_rectwithred_enemy = Enemy(red, 160, 100), and takered_rectout of theforloop. - In the loop, call
red_enemy.update(), and after the fill,red_enemy.draw(screen)in place of the red blit.
Press Play: the three enemies fall as before. Then Check.
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
3Classes for Game Objects
Your First ClassMethodsSelf Is the ObjectA List of ObjectsObjects with ImagesA List of EnemiesA SubclassPractice on your own: Pygame playground