Home > Mobile >  In game loop, how do I restart game properly using nested class or loop?
In game loop, how do I restart game properly using nested class or loop?

Time:10-15

I making a game in python3 using pygame, logic of my game happens in run loop. My question is How do I make game restart, without having use nested class and loop as in example below?

I am afraid this code will use too much memory when player dies enough dies, but maybe my understanding of this code is wrong? (I assume, when player dies every time a new game class is made and so does new variables.

class Game:
    def init:
        #code goes here
    def run(self,deathcount):
        while self.running==True:
        #code goes here
        if player dies
           deathcount =1
           game = Game()
           self.running=False
           game.run(death_count)

if name == "main":
    game = Game()
    game.run(death_count=0)

CodePudding user response:

The general approach would be to have an outer loop. The outer loop runs as long as the game is not terminated. In the loop, the Game object is created and the application loop is executed:

class Game:
    def __init__(self):
        # [...]

    def run(self, death_count):
        
        quit_game = False
        game_over = False
        while not quit_game and not game_over:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    quit_game = True

            # [...]

            if player_dies:
                game_over = True

        return quit_game
           
if name == "main":
    death_count = 0
    quit_game = False
    while not quit_game:
        game = Game()
        quit_game = game.run(death_count)
        death_count  = 1
  • Related