Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pygame - Loading images in sprites

Tags:

python

pygame

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
like image 885
Mercury Platinum Avatar asked Nov 02 '17 18:11

Mercury Platinum


People also ask

How do I add an image to a sprite pygame?

How to display images with PyGame ? Create a display surface object using display. Create a Image surface object i.e. surface object in which image is drawn on it, using image. Copy the image surface object to the display surface object using blit() method of pygame display surface object.

Can pygame load PNG?

Pygame is able to load images onto Surface objects from PNG, JPG, GIF, and BMP image files.


1 Answers

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()
like image 174
skrx Avatar answered Sep 28 '22 00:09

skrx