Python:如何将多个 Sprite 合并为一个并保存图像?

标签 python pygame python-imaging-library sprite sprite-sheet

目前,我正在开发一个 2D 自上而下风格的 RPG(在 Pygame 中;Python 的最新版本),我想让角色绘制过程尽可能简单。然而,我不知道如何实现它。

我已经知道使用 for 循环绘制 Sprite 会降低游戏的性能,然后我还要担心更多代码。

我想要做的是拍摄一个“裸体” Sprite ,将眼睛、头发和衣服放在上面,然后将其另存为新图像。

(MaleSprite.png + Eyes1.png + Hair1.png + Clothes1.png = Spritesheet.png)

我已经有一个用于裸体 Sprite 的 Sprite 表,还有一个用于发型的 Sprite 表。我需要将头发向上移动两个像素,然后将其绘制在角色顶部,然后将其保存到新图像(由于角色的 Sprite 表高 64 像素,因此新图像高 66 像素)。

我将处理代码中出现的任何其他依赖项,我只需要组合这些图像,并且我相信我应该为此使用 Pillow。

我想获取玩家对眼睛颜色、头发和服装的选择,然后将其写入他们的玩家文件。之后,makesprite()函数应该获取 Sprite ,根据需要调整它们(头发将向上移动两个像素,帽子可能会更多),然后将其保存为我可以使用的新 Sprite 表(png)在我的 sprite.draw() 函数中。

最佳答案

Pygame 可以很好地处理这个问题,不需要其他库。看看 image模块,您将在其中找到 save 函数以及 tostring/fromstring

但是,如果您从一组模板创建玩家 Sprite ,则没有太多理由将图像实际保存到磁盘。您可以在启动时通过将所有不同部分( body 、头发、眼睛......)传输到新的 Surface 上来创建玩家图像,然后使用它。

下面是一些伪代码:

import pygame 
from collections import defaultdict

def load_image(filename): 
    ... load and cache the image ...

offset = defaultdict(lambda: (0, 0))
offset['eyes'] = (0, 2) # let's blit eyes not at (0, 0), but at (0, 2)

def build_body_image(**look):
    surf = pygame.Surface((66, 66))
    for part in look:
        surf.blit(load_image(look[part]), offset[part])

class Actor(pygame.sprite.Sprite):
    def __init__(self, **look):
        super().__init__()
        self.look = look
        self.image = build_body_image(**self.look)
        ...

player = Actor(body='MaleSprite.png',
               clothes='Clothes1.png'
               eyes='Eyes1.png',
               hair='Hair1.png')

如果您想保留播放器外观,只需保留 look 属性,然后在启动时调用 build_body_image 即可重新创建最终的播放器图像。

当然,有多种方法可以完成类似的操作(例如,您可以只存储索引而不是完整的文件名和/或在 Sprite 表中查找图像等),选择适合您需求的方法。

关于Python:如何将多个 Sprite 合并为一个并保存图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54698799/

相关文章:

python - 如何将嵌套未知层数的新 JSON 节点添加到现有 JSON 文件中?

python - VS Code 中使用的 Pygame with Pygame Snippets

python - Pygame 按钮 get.pressed()

python - 用 Pillow 阅读的 Gif 有黑色边框

python - 在 PIL 中更新像素颜色后图像未保存

python - 理解 Python 中的 super

python - “<' not supported between instances of ' 方法”和 'method' - Python、Django

python - 为什么这个 x 路径只带来一个值?

Python 3.2,Pygame "AttributeError: ' pygame.Rect'对象没有属性 'bullet_RECT'

python - Django:更改图像大小并上传到 S3