Pygame - Loading images in sprites

我们两清 提交于 2019-12-30 22:53:38

问题


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

回答1:


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()


来源:https://stackoverflow.com/questions/47082209/pygame-loading-images-in-sprites

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!