Griffin Bender Griffin Bender - 15 days ago 5
Python Question

Adding to a for loop in python from another class

Forgive me, I am a beginner...

In short, I am trying to add to a separate classes for loop in python. Below are details...

I am making a game with python and pygame. I have a base class for all of my 'states' (ex. start state, game state, game over state, ect.) which includes a function which has a for loop checking through pygames 'events' (ex. exiting the program, pressing a key, ect.).

Below is the parent method... It works.

def events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.quit()


Below is the childs method. It wants to add to add a 'key up event' to the already existing 'exit' and 'escape' events...

def events(self):
super().events()
for event in pygame.event.get():
if event.type == pygame.KEYUP:
self.start_state = False


What happens is the code gets stuck in the parents class for loop and ignores all below it. I also tried calling the super below the childs for loop and that just causes it to get stuck in the childs for loop instead and ignores the parents.

I guess a solution would be make a separate method for the childs class events, but I would still like to know if the way that I am trying to do it is possible so that I can avoid having a mess of separate functions.

Thanks.

Answer

Rather then calling loop (for event in pygame.event.get():) inside event method, it would be better to have separate method just to proceed events, but get them some where else

class Base():

    def events(self):
       for event in pygame.event.get():
          self._proceed_event(event)

    def _proceed_event(self, event):        
        if event.type == pygame.QUIT:
            self.quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                self.quit()

class Child(Base):

    def _proceed_event(self, event):
       if event.type == pygame.KEYUP:
          self.start_state = False
       super()._proceed_event(event)