Reset and restart pygame program doesn’t work

You’ve overcomplicated the system. What you are actually doing is recursively instantiating a new Gui object and new application loop into an existing Gui object and application loop.
If GameState is implemented correctly, it should be sufficient to create a new GameState object and continue the existing application loop instead of recursively creating a new Gui instance:

import board as b

class Gui():
    def __init__(self):

        self.gamestate = b.GameState()

    def run(self):

        running = True
        while running:

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

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_r:
                        self.gamestate = b.GameState()

            # [...]

if __name__ == '__main__':

The instruction self.board = s.start_position doesn’t create a new board object. self.board and s.start_position refer to the same object. If you change one of the objects, the other object seems to change in the same way since there is only one object.
Either you need to make a deep copy of the board object when you start the game or you need to reset the object when the game restarts.

A solution might be to use the Python copy module. deepcopy can create a deep copy of an object:

import copy
self.board = copy.deepcopy(s.start_position)`

Note, not all object can be deep copied. For instance a pygame.Surface cannot be deep copied.

Leave a Comment