Home > Net >  Does endless creation of objects to start new game hog ram in Python?
Does endless creation of objects to start new game hog ram in Python?

Time:12-15

I made my first game with python. The structure of program is roughly this: import pygame

class Game:

    def __init__(self):
        pygame.init()

    ... rest of the code

    def new_game(self):
        Game()

...rest of the code


if __name__ == "__main__":
    #while True: ###This line was added to original by mistake
    Game()

When I finished project I realised that by starting new game it does create new Game object and starts game from scratch, but it probably still keeps the old games variables, sprites, etc. in memory even though anything isn't happening there anymore.

Is my assumption correct and if so how should I structure my code instead?

EDIT: From what I gathered from comments this would be better structure:

class Game:

    def __init__(self):
        pygame.init()
    
    def __exit__(self):
        #Code here?
    
    ... rest of the code
   
...rest of the code
    
    
if __name__ == "__main__":
    while True:
        game = Game()
        game.run()

CodePudding user response:

I suggest a different approach The run method should return whether the game should continue or not. So You can do:

if __name__ == "__main__":
    run_game = True
    while run_game:
        game = Game()
        run_game = game.run()

When the game ends the method run () must return True if a new game is to be started, otherwise it must return False.

class Game:

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

    def run(self):

        # application loop
        running = True
        while running:
            # [...]

        # ask to restart game 
        start_new_game = # [...] set True or False 

        return start_new_game
  • Related