user10620375
user10620375

Reputation:

What is the better way to make multiple loops in pygame?

I would know what is the best way to make multiple loops inside my pygame project. This is all loops I would have :

load loop
game loop
main loop
setting loop
pause loop

but is this the best way to do this ?

This is what my code look like

run = True
while run :
   # do load loop

def main():
   run = True
   while run :
      if loop == 'main' :
         run2 = True
         while run2 :
             # pygame loop

      if loop == 'pause' :
         run2 = True
         while run2 :
            # other loop
...

if __name__ == '__main__' :
   main()

Upvotes: 2

Views: 1267

Answers (1)

Rabbid76
Rabbid76

Reputation: 210880

Why do you need multiple nested loops? A variabel which stores the current state of the game is sufficient:

def main():
    gamestate = 'load'
    run = True
    while run:

        if gamestate == 'load':
            # [...]

        elif gamestate == 'game':
            # [...]

        # [...]
            # [...]

        pygame.display.flip()

if __name__ == '__main__' :
    main()

If you want to switch the state of the game, then all you have to do is change the variable gamestate.
One main loop which runs the game is all you need. That what happens in the loop, may vary, dependent on the current state of the game. But it is always the same loop, which handles the events, clears the display, draws the scene and finally updates the display.

Note, you can even define functions which do the different parts of the game, but you don't need a loop in the functions:

def load(events):
    # [...]

def game(events):
    # [...]

def main():
    gamestate = 'load'
    run = True
    while run:

        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                run = False

        # [...]

        if gamestate == 'load':
            load(events)

        elif gamestate == 'game':
            game(events)

        # [...]
            # [...]

        pygame.display.flip()

if __name__ == '__main__' :
    main()

Or even in a class:

class MyGame:
    def __init__(self):
        self.gamestate = 'load'
        self.run = True
        self.events = []

    def load(self):
        # [...]

    def game(self):
        # [...]

    def main(self):
        while self.run:

            self.events = pygame.event.get()
            for event in self.events:
                if event.type == pygame.QUIT:
                    self.run = False

            # [...]

            if self.gamestate == 'load':
                self.load()
            elif self.gamestate == 'game':
                self.game()
            # [...]
                # [...]

            pygame.display.flip()

if __name__ == '__main__' :
    app = MyGame()
    app.main()

Upvotes: 3

Related Questions