如何使用python shelve

时间:2018-11-17 17:15:45

标签: python shelve roguelike

我正在用Python设计类似rogue的游戏,并且我使用的是简化的实体/组件模型-没有所有系统。这些组件使添加和删除游戏对象的属性变得非常容易。我在Entity上有一个 getattr 方法,它使直接从Entity直接访问组件值变得非常方便,但是我认为这会造成问题,因为在尝试重新加载保存的书架时达到了最大递归深度。

在不弄乱保存过程的情况下如何保持便利?

Component类现在非常简单:

class Component(object):                                                                                       
    def __init__(self, entity=None):                                                                           
    self.entity = entity

这是我的Entity类:

import uuid
class Entity(object):
    # A generic game object: player, monster, item, stairs, etc.

    def __init__(self, *components):
        # Set a unique uuid
        self._uuid = uuid.uuid4()

        # Add the supplied components.
        self.components = {}
        if components:  # refactor this to *components when all the attributes are components
            for component in components:
                self.set(component)

    @property
    def uuid(self):
        """Property to access the Entity's uuid, exists to prevent uuid modification."""
        return self._uuid

    def find_component(self, name):
        # Searches through the Entity's components to match the given value. If
        # found, it returns the Component that manages that value, otherwise returns None.
        for comp in self.components.values():
            if hasattr(comp, name):
                return comp
        return None

    def __getattr__(self, name):
        comp = self.find_component(name)
        if comp:
            return getattr(comp, name)
        raise AttributeError("Entity has no component with attribute {}".format(name))

    def set(self, component):
        """Sets a new Component."""
        key = type(component)
        self.components[key] = component

    def get(self, component):
        """ Returns the specified Component, if it exists, otherwise returns None."""
        return self.components.get(component, None)

    def has(self, component):
        """ Returns True if this Entity contains the specified Component, otherwise returns False."""
        return self.get(component) is not None

    def rm(self, component):
        """ Removes a Component."""
        return self.components.pop(component, None)

0 个答案:

没有答案