python - Pygame - 在 Sprite 中加载图像

标签 python pygame

如何将图像加载到 sprite 中而不是为 sprite 绘制形状? 例如:我将 50x50 的图像加载到 Sprite 中,而不是绘制 50x50 的矩形

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

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

最佳答案

第一个load全局范围或单独模块中的图像并将其导入。不要在__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)

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

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)

使用 convertconvert_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()

关于python - Pygame - 在 Sprite 中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47082209/

相关文章:

Python:两个同名包;你如何指定加载哪个?

python - Numpy:按索引将行从一个矩阵添加到另一个矩阵

python - 仅将函数应用于 Pandas Dataframe 列的一部分

python - 在python中获取随机 bool 值?

python - 如何在多个开发环境中使用 Flask-migrate

python - Python/Pygame 中用于识别按键的正则表达式

python - 检测pygame中文本框和圆圈之间的碰撞

python - 如何在 pygame 中进行平滑移动 + 旋转?

python - 在屏幕上移动 Sprite

python - Pygame 矩形类