python - 你如何从 Python 的 Sprite 表中选择 Sprite 图像?

标签 python pygame

我想导入 Sprite 表并选择一个 Sprite 。我如何在 Python/pygame 中执行此操作?

最佳答案

上面的spritesheet loader是一个很好的方法。基于该代码,我制作了适用于任何 spritesheet 的通用函数:

#!/usr/bin/python
#
# Sprite Sheet Loader - hammythepig
#
# Edited by Peter Kennedy
#
# License - Attribution - hammythepig
    #http://stackoverflow.com/questions/10560446/how-do-you-select-a-sprite-image-from-a-sprite-sheet-in-python
#
# Version = '2.0'

import pygame,sys
from pygame.locals import *

def sprite_sheet(size,file,pos=(0,0)):

    #Initial Values
    len_sprt_x,len_sprt_y = size #sprite size
    sprt_rect_x,sprt_rect_y = pos #where to find first sprite on sheet

    sheet = pygame.image.load(file).convert_alpha() #Load the sheet
    sheet_rect = sheet.get_rect()
    sprites = []
    print sheet_rect.height, sheet_rect.width
    for i in range(0,sheet_rect.height-len_sprt_y,size[1]):#rows
        print "row"
        for i in range(0,sheet_rect.width-len_sprt_x,size[0]):#columns
            print "column"
            sheet.set_clip(pygame.Rect(sprt_rect_x, sprt_rect_y, len_sprt_x, len_sprt_y)) #find sprite you want
            sprite = sheet.subsurface(sheet.get_clip()) #grab the sprite you want
            sprites.append(sprite)
            sprt_rect_x += len_sprt_x

        sprt_rect_y += len_sprt_y
        sprt_rect_x = 0
    print sprites
    return sprites

#VERSION HISTORY

    #1.1 - turned code into useable function

    #2.0 - fully functional sprite sheet loader

作为引用,这会将工作表从左到右一次一行地切割成单独的 Sprite 。

关于python - 你如何从 Python 的 Sprite 表中选择 Sprite 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10560446/

相关文章:

python - 更快地创建多个数据帧。 for循环太慢

python - 有效地折叠 Parquet 中的行组

python - 如何将某些特定的 .jpg 文件复制到另一个目录?

python - py2exe 突然不再工作。没有名为 _view 的模块

python - 将不同的调色板索引分配给调色板图像

python - 我可以用 C 重写昂贵的 pygame 函数吗?

python - 如何在弹性 beantalk 上更新 python Flask 应用程序?

python - 尝试为一个月中的每一天创建文件

python-3.x - 类型错误 : draw() missing 1 required positional argument: 'win'

python - Pygame - 矩形并排碰撞