I have an issue with resetting my game in pygame when the user is asked to restart. The program is constructed like this:
import board as b
class Gui():
def __init__(self):
pygame.init()
self.gamestate = b.GameState()
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
running = False
pygame.quit()
Gui().run
if __name__ == '__main__':
Gui().run()
What happens when the user tries to restart is that the Gui closes and the while loop exits as they should. It then opens a new window BUT it has not cleared the gamestate, so my gamestate from previous run is still there. I thought that the line self.gamestate = b.GameState() would create a new gamestate for me but that seems not to be the case. Here is a short snippet from the board file:
class GameState:
def __init__(self):
self.board = s.start_position
When calling it I thought it would set the board to start position and all its parameters to inititial, but something is not right and I have not been able to solve this for 3 days now. I hope you can help me how to clear the gamestate and start from fresh again.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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):
pygame.init()
self.gamestate = b.GameState()
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
self.gamestate = b.GameState()
# [...]
if __name__ == '__main__':
Gui().run()
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0