Mercury Platinum
Mercury Platinum

Reputation: 1569

Pygame - Loading images in sprites

How do I load an image into a sprite instead of drawing a shape for the sprite? Ex: I load a 50x50 image into a sprite instead of drawing a 50x50 rect

Here is my sprite code so far:

class Player(pygame.sprite.Sprite):

    def __init__(self, color, width, height):

        super().__init__()
        #Config
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

            # Draw
        pygame.draw.rect(self.image, color , [0, 0, width, height])

        # Fetch
        self.rect = self.image.get_rect()

    def right(self, pixels):
        self.rect.x += pixels
    def left(self, pixels):
        self.rect.x -= pixels
    def up(self, pixels):
        self.rect.y -= pixels
    def down(self, pixels):
        self.rect.y += pixels

Upvotes: 7

Views: 15758

Answers (1)

skrx
skrx

Reputation: 20438

First load the image in the global scope or in a separate module and import it. Don't load it in the __init__ method, otherwise it has to be read from the hard disk every time you create an instance and that's slow.

Now you can assign the global IMAGE in the class (self.image = IMAGE) and all instances will reference this image.

import pygame as pg


pg.init()
# The screen/display has to be initialized before you can load an image.
screen = pg.display.set_mode((640, 480))

IMAGE = pg.image.load('an_image.png').convert_alpha()


class Player(pg.sprite.Sprite):

    def __init__(self, pos):
        super().__init__()
        self.image = IMAGE
        self.rect = self.image.get_rect(center=pos)

If you want to use different images for the same class, you can pass them during the instantiation:

class Player(pg.sprite.Sprite):

    def __init__(self, pos, image):
        super().__init__()
        self.image = image
        self.rect = self.image.get_rect(center=pos)


player1 = Player((100, 300), IMAGE1)
player2 = Player((300, 300), IMAGE2)

Use the convert or convert_alpha (for images with transparency) methods to improve the blit performance.


If the image is in a subdirectory (for example "images"), construct the path with os.path.join:

import os.path
import pygame as pg

IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()

Upvotes: 6

Related Questions