1

I'm currently working on a game in python with pyGame and want to use enums for the different states(gamestate, levelstate etc,) in the game.

I have inherited my own GameState class from Enum class as seen in the code below. I have the enum members set up (mainMenu, inGame etc...) and then put them into a list named allGameStates.

I get a problem when trying to iterate through the list containing all the gamestates in the setter function. I get:

AttributeError: 'GameState' object has no attribute 'allGameStates'

Also, while hovering over the list variable allGameStates it says:

inferred type: GameState

Shouldn't it be a list type?

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)

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Daniel B
  • 111
  • 1
  • 2
  • 8

1 Answers1

1

Looks like your problem is one of timing and one of understanding1:

  • The enum member names ('mainMenu', 'pause', etc.) are not actually converted into Enum members until after the class is completed; this means that any class-level references ('allGameStates' = ...) are referring to strings.

  • self.curgamestate = ... -- this is setting the current game state on an instance (an Enum member), not on the class -- so what the "current" game state is can (and will!) be a confused mess. What you need there is self.__class__.curgamestate = ...

  • finally, a rule of thumb for what gets converted into an Enum -- anything that is a simple name assignment. So, not only are mainMenu, inGame, pause, and exit converted into Enums, but so is allGameStates and curgamestate2.

Some hints:

  • once GameState is built, list(GameState) will give you the (correct) list of members

  • self.gamestate is the same as self.name

  • self.allGameStates should just be self.__class__ (unlike normal classes, an Enum class is iterable)

--

1 see When and where to use for some ideas on how to use Enum

2 see Define a class constant for ways to have simple name assignment not get transformed into Enum members

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237