Pygame - 在精灵中加载图像

Ale*_*XYX 6 python pygame

如何将图像加载到精灵中而不是为精灵绘制形状?例如:我将一个 50x50 的图像加载到一个精灵中而不是绘制一个 50x50 的矩形

到目前为止,这是我的精灵代码:

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
Run Code Online (Sandbox Code Playgroud)

skr*_*krx 5

首先在全局范围或单独的模块中加载图像并导入它。不要在__init__方法中加载它,否则每次创建实例时都必须从硬盘中读取它,这很慢。

现在您可以IMAGE在类 ( self.image = 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)
Run Code Online (Sandbox Code Playgroud)

如果你想为同一个类使用不同的图像,你可以在实例化过程中传递它们:

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)
Run Code Online (Sandbox Code Playgroud)

使用convertor convert_alpha(对于具有透明度的图像)方法来提高 blit 性能。


如果图像位于子目录中(例如“图像”),请使用以下命令构建路径os.path.join

import os.path
import pygame as pg

IMAGE = pg.image.load(os.path.join('images', 'an_image.png')).convert_alpha()
Run Code Online (Sandbox Code Playgroud)