啊!!!我对整个Python事物很陌生,我知道如何制作“动画”的唯一方法是使用单独的图片(如每个文件一张图片)。好吧,我得到了一个非常适合我需要的精灵表,唯一的问题是它只是一个精灵表。我不想花时间裁剪每个单独的精灵。
更多信息,我是 python 和 pygame 的新手。八月才开始学习这门语言,这是一门进展非常缓慢的课程……所以如果你能解释一下你在做什么,这样我就可以为未来的项目做这件事,我将非常感激。我也在使用 Python 3.2,如果这有什么区别的话,因为我很确定 Python 2 和 Python 3 之间存在一些语法差异。
谢谢!!!这对我有很大帮助。
还有一个可以为您完成工作的可用库:spritesheet
import spritesheet
...
ss = spritesheet.spritesheet('somespritesheet.png')
# Sprite is 16x16 pixels at location 0,0 in the file...
image = ss.image_at((0, 0, 16, 16))
images = []
# Load two images into an array, their transparent bit is (255, 255, 255)
images = ss.images_at((0, 0, 16, 16),(17, 0, 16,16), colorkey=(255, 255, 255))
…
同时,您可以阅读该
spritesheet
类中的(非常简单的)代码来了解它是如何工作的。
from pathlib import Path
from typing import List, Tuple, Union
import pygame
class Spritesheet:
def __init__(self, filepath: Path, sprite_size: Tuple[int, int]) -> None:
"""Initialize the spritesheet.
Args:
filepath (Path): Path to the spritesheet image file.
sprite_size (Tuple[int, int]): Width and height of each sprite in the sheet.
"""
self.sheet = pygame.image.load(filepath).convert_alpha()
self.sprite_size = sprite_size
def get_sprite(self, loc: Tuple[int, int], colorkey: Union[pygame.Color, int] = None) -> pygame.Surface:
"""Load a specific sprite from the spritesheet.
Args:
loc (Tuple[int, int]): Location of the sprite in the sheet (row, column).
colorkey (Union[pygame.Color, int], optional): Color to be treated as transparent. Defaults to None.
Returns:
pygame.Surface: The sprite image.
"""
x = loc[0] * self.sprite_size[0]
y = loc[1] * self.sprite_size[1]
rect = pygame.Rect(x, y, *self.sprite_size)
image = pygame.Surface(self.sprite_size, pygame.SRCALPHA).convert_alpha()
image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
def get_sprites(self, locs: List[Tuple[int, int]], colorkey: Union[pygame.Color, int, None] = None) -> List[pygame.Surface]:
"""Load multiple sprites from the spritesheet.
Args:
locs (List[Tuple[int, int]]): List of locations of the sprites in the sheet (row, column).
colorkey (Union[pygame.Color, int, None], optional): Color to be treated as transparent. Defaults to None.
Returns:
List[pygame.Surface]: List of sprite images.
"""
return [self.get_sprite(loc, colorkey) for loc in locs]