Pygame:保存对象/类/曲面的列表

2024-10-01 02:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个游戏,你可以在其中创建迷宫。将块放置在16x16网格上,同时从各种块中进行选择以使其水平。无论何时创建块,它都会添加此类:

class Block(object):
    def __init__(self,x,y,spr):
        self.x=x
        self.y=y
        self.sprite=spr
        self.rect=self.sprite.get_rect(x=self.x,y=self.y)

一个名为instances的列表。在

我尝试将其搁置到.bin文件中,但它在处理曲面时返回一些错误。如何保存和加载级别?在

感谢任何帮助!:)

以下是整个代码供参考:

^{pr2}$

Tags: rectself网格游戏getobjectinitdef
2条回答

不能序列化/pickle/shelve pygame的Surface对象(至少不需要大量的努力)。所以你的问题的答案是:不要尝试序列化你的表面(这只会浪费磁盘空间)。在

例如,您可以创建一个简单的dict来存储曲面,并让您的类只存储键,例如:

menuspr=pygame.image.load('images/menu.png').convert()
b1spr=pygame.image.load('images/b1.png').convert()
b2spr=pygame.image.load('images/b2.png').convert()
currentbspr=b1spr
curspr=pygame.image.load('images/curs.png').convert()
curspr.set_colorkey((0,255,0))
# create a dict to store all surfaces
surf_dict = {'b1spr': b1spr, 
             'b2spr': b2spr, 
             'currentbspr': currentbspr, 
             'curspr': curspr}

...
class Block(object):
    def __init__(self,x,y,spr):
        self.x=x
        self.y=y
        self.sprite=spr
        # self.sprite is no longer a Surface, but a str
        self.rect=surf_dict[self.sprite].get_rect(x=self.x,y=self.y)

...
    ...
        # don't pass the surface to the Block, just the key 
        instances.append(Block(placepos[0],placepos[1], 'currentbspr'))

...
    for i in instances:
        # get the Surface from the dict, not from the instance itself
        screen.blit(surf_dict[i.sprite],i.rect)

现在您可以节省地尝试pickle/sheldallBlock-实例(我看到您已经问了一个相关的问题here)。在

我自己找到了一个办法。我使用python内置的open(fname,mode)来创建一个级别文件。在

无论何时创建块,它都会获取该块的精灵名称和坐标,并以.bin格式将其添加到保存文件中:

f.write('Block('+str(placepos[0])+','+str(placepos[1])+',b1spr).')

然后我创建了一个函数来读取这个,并相应地创建了级别:

def CreateLevel(levelname):
    f=open(levelname,'r')
    obj=f.read()
    f.close()
    obj=obj.split('.')
    for b in obj:
        instances.append(eval(b))

而且效果很好!在

这是全部代码,谢谢你们的帮助。在

^{pr2}$

相关问题 更多 >