Pygame/Python:无法为房间加载系统创建表面的深度复制(tl;底部的博士)

Pygame/Python: Can't create deepcopy of surfaces for room loading system (tl;dr at bottom)

tl;底部的博士。 post 的大部分内容是为我的问题提供背景信息。如果不需要,我的主要问题在下面。

我目前正在做一个 pygame 项目(动作冒险游戏),我目前正在研究与对象持久性和房间转换相关的东西。基本上,我想创建一个系统,其中我有一个字典,其中包含有关特定房间的所有信息,包括它使用的 图像和该房间中的对象 .

我的游戏有一个字典,其中包含在我的游戏中正在更新和执行操作的当前对象的列表。我们称之为 instances。每当我向 instances 添加一个对象时,它就会出现在游戏中。考虑到这一点,让我们考虑一下将对象加载到特定房间的实际工作方式。 我的系统的工作方式是我有一个名为 room 的变量,它包含一个表示我当前所在房间的字符串。我有另一个字典,其中包含一个房间内的所有对象。让我们称之为 room_dictroom_dict 会有键 "objects":[obj1,obj2]。因此,基于 room 的当前值,它可以访问某些对象(即,room_dict[room]["objects"] 将 return 当前房间中所有对象的列表)。

现在我已经解释了其工作原理的基础知识,我有一个方法可以真正知道我何时触发了房间转换(或者更确切地说,何时更改 room 的值)。发生这种情况时,房间(我刚刚进入的房间)中存在的所有对象都会从 instances 字典中清除。 room_dict[room]["objects"] 中的所有对象都添加到 instances 中,因此它们现在出现在游戏中。到目前为止是有道理的,对吧?

主要问题是当 instances 字典中的对象(当前加载的对象)正在更新时,room_dict[room]["objects"] 中的对象也会更新。这意味着如果我改变一个房间里敌人的位置然后离开房间并且return,对象将在那个位置而不是原来的位置创建。所以我尝试做 instances[list_of_enemies].append(copy.copy(enemy_object)) 来添加对象的副本。但这仍然不起作用,当我尝试执行 copy.deepcopy() 时,解释器说它无法序列化该对象,因为它的属性之一是 pygame.Surface 对象。

所以换句话说,我的主要问题是我想复制一个包含 pygame.Surface 作为其属性的对象,它根本不引用原始对象。我将如何使用具有 pygame.Surface 类型属性的对象进行深层复制?

tl;dr:我想复制一个对象,该对象的属性是 pygame.Surface 对象,但 copy.deepcopy() 不是工作。有没有其他不引用原始对象的复制方式?

编辑:忘记提及该项目相当庞大,因此很难为上下文提供代码。我个人认为不需要它,但我想我还是会把它放出来。谢谢大家!

解决此问题的一种方法是每次需要新副本时从 json 文件创建对象,而不是事先创建对象。

或者您可以更改您的复制方法:实施 __deepcopy__ and/or __copy__ 并复制没有 image 属性的对象的属性,也许只是创建一个新的实例.

简单示例:

import pygame
from copy import deepcopy
from itertools import cycle

# an implementation of something in our game
class Cloud(pygame.sprite.Sprite):
    def __init__(self, pos, speed):
        super().__init__()
        self.pos = pos
        self.speed = speed
        self.image = pygame.Surface((50, 20))
        self.image.set_colorkey((11, 12, 13))
        self.image.fill((11, 12, 13))
        pygame.draw.ellipse(self.image, 'white', self.image.get_rect())
        self.rect = self.image.get_rect(topleft=self.pos)

    def update(self):
        super().update()
        self.rect.move_ip(self.speed, 0)
        if not pygame.display.get_surface().get_rect().colliderect(self.rect):
            self.rect.right = 0

    def __deepcopy__(self, memo):
        # just create a new instance 
        return Cloud(self.pos, self.speed)

# the definition of our game world
game_data = {
    'WORLD_A': {
        'color': 'lightblue',
        'objects': pygame.sprite.Group(Cloud((50, 50), 1))
    },
    'WORLD_B': {
        'color': 'red',
        'objects': pygame.sprite.Group(Cloud((100, 100), 2), Cloud((80, 30), 3))
    },

}

screen = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

keys = cycle(game_data.keys())

# happy deepcopying
current = deepcopy(game_data[next(keys)])

while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            quit()
        if e.type == pygame.KEYDOWN:
            # happy deepcopying
            current = deepcopy(game_data[next(keys)])
            
    screen.fill(current['color'])
    current['objects'].update()
    current['objects'].draw(screen)
    pygame.display.flip()
    clock.tick(30)

另一个解决方案是延迟加载图像并仅在需要时查找它们,这样您就不需要复制它们。这是一个简单的例子:

... see example above ...

# load/create all images once and store them in a dict
def create_cloud_image():
    image = pygame.Surface((50, 20))
    image.set_colorkey((11, 12, 13))
    image.fill((11, 12, 13))
    pygame.draw.ellipse(image, 'white', image.get_rect())
    return image

images = {
    'cloud': create_cloud_image()
}

# a simple sprite that lazy loads its image
class CopyableActor(pygame.sprite.Sprite):
    def __init__(self, image_key, pos):
        super().__init__()
        self.pos = pos
        self.image_key = image_key

    def init_image(self):
        self.image = images['cloud']
        self.rect = self.image.get_rect(topleft=self.pos)

    def update(self):
        if not hasattr(self, 'image'):
            self.init_image()

# an implementation of something in our game
class Cloud(CopyableActor):
    def __init__(self, pos, speed):
        super().__init__('cloud', pos)
        self.speed = speed

    def update(self):
        super().update()
        self.rect.move_ip(self.speed, 0)
        if not pygame.display.get_surface().get_rect().colliderect(self.rect):
            self.rect.right = 0


... see example above ...