在 python 中为游戏状态使用枚举

丹尼尔·贝克

我目前正在使用 pyGame 在 python 中开发一个游戏,并希望对游戏中的不同状态(游戏状态、级别状态等)使用枚举。

我从 Enum 类继承了我自己的 GameState 类,如下面的代码所示。我设置了枚举成员(mainMenu、inGame 等...),然后将它们放入名为 allGameStates 的列表中。

尝试遍历包含 setter 函数中所有游戏状态的列表时遇到问题。

我得到 -> AttributeError: 'GameState' 对象没有属性 'allGameStates'

此外,将鼠标悬停在列表变量 allGameStates 上时,它说 ->

推断类型:GameState

不应该是列表类型吗?

任何建议都会很可爱!

class GameState(Enum):

    mainMenu = 'MainMenu'
    inGame = 'InGame'
    pause = 'Pause'
    exit = 'Exit'

    allGameStates = list([mainMenu, inGame, pause, exit])
    curgamestate = allGameStates[0]

    def __init__(self, newgamestate, *args):
        super().__init__(*args)

        self.gamestate = newgamestate

    @property
    def gamestate(self):
        """Gets the current game state"""
        return self.curgamestate

    @gamestate.setter
    def gamestate(self, state):
        """Sets the current game state to another"""
        try:
            for gamestates in self.allGameStates:
                if gamestates.name == state:
                    self.curgamestate = state

        except ValueError as err:
            print(err.args)
伊森·弗曼

喜欢你的长相问题是时机的一方和理解一个1

  • 枚举成员名称('mainMenu''pause'等)Enum直到类完成后才真正转换为成员这意味着任何类级引用 ( 'allGameStates' = ...) 都引用字符串。

  • self.curgamestate = ...——这是在实例(Enum成员)上设置当前游戏状态,而不是在类上——所以“当前”游戏状态可能(并且将会!)是一团糟。你需要的是self.__class__.curgamestate = ...

  • 最后,关于转换成什么的经验法则Enum- 任何简单的名称分配。所以,不仅是mainMenuinGamepause,并exit转换成EnumS,但如此是allGameStatescurgamestate2

一些提示:

  • 一旦GameState建成,list(GameState)会给你(正确的)成员名单

  • self.gamestate 是相同的 self.name

  • self.allGameStates应该只是self.__class__(与普通类不同,一个Enum类是可迭代的)

——

1有关如何使用的一些想法,请参阅何时何地使用Enum

2请参阅定义类常量以了解如何将简单的名称分配转换为Enum成员

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章