Problems with restarting the game

22 Sep, 2019

Serhii writes (excerpted from two emails):

I teach programming lessons for the pupils. We try to do restart button for the "Bounce" as it follows:
jasonrbriggs.com/journal/2014/09/03/restarting-the-game.html
...there is a problem in "command=restart".

If I run your code I get the following error:

Traceback (most recent call last):
  File "game1.py", line 105, in <module>
    game.add_restart()
  File "game1.py", line 86, in add_restart
    self.restart_button = Button(tk, text="Click to Restart Game", command=restart, bg="green")
NameError: name 'restart' is not defined

Looking at your code...

    def add_restart(self):
        self.restart_button = Button(tk, text="Click to Restart Game", command=restart, bg="green")
        self.restart_button.pack()

...the problem is you don't actually have a function called restart anywhere - which explains the error message "name 'restart' is not defined". The easiest way to fix this, is to define that function inside your Game class, in which case the above function should actually be:

    def add_restart(self):
        self.restart_button = Button(tk, text="Click to Restart Game", command=self.restart, bg="green")
        self.restart_button.pack()

(note the addition of self there)

The restart function itself should remove the restart button from the screen, move the paddle and ball back to the starting position, and reset the score. I suggest you create a simple function first, just to prove the button works:

    def restart(self):
        print("Restart the game!")

If you see "Restart the game!" printed when clicking the button, you know you're good to start adding the code to do the actual restart (you might also find this post useful: journal/2018/03/04/restarting-the-bounce-game-revisited). The other thing you might want to think about changing, is to only add the restart button if the game is over (so that's a small change to the while loop at the bottom).

Hope that helps.