Home > database >  How can I create a Pause function inside a class and then use it inside turtle game?
How can I create a Pause function inside a class and then use it inside turtle game?

Time:03-20

I was working on a snake game using turtle graphics in python. The game worked well. Then, I wanted to improve on it and add a pause function to it. When I just wrote the lines of code for the pause function inside the game code, it worked, but my aim is to create the pause function in a class and be able to use its instance for my subsequent projects instead of just writing the whole functionality again every time.

Since the snake game code is long, I decided to try the pause function on a simple turtle animation to get the hang of it before implementing in my snake game but writing it in a class just isn't working. Here's when I wrote it in the code, which worked:

from turtle import Turtle, Screen

tim = Turtle()
screen = Screen()
is_paused = False

def toggle_pause():
    global is_paused
    if is_paused:
        is_paused = False
    else:
        is_paused = True

screen.listen()
screen.onkey(toggle_pause, "p")

while True:
    if not is_paused:
        tim.forward(12)
        tim.left(10)
    else:
        screen.update()

Here's when I wrote my pause function in a class, which didn't work.

class Pause:
    def __init__(self, is_paused):
        self.is_paused = is_paused

    def toggle_pause(self):
        if self.is_paused:
            is_paused = False
            return is_paused
        else:
            is_paused = True
            return is_paused
from turtle import Turtle, Screen
from pause import Pause

ps = Pause(False)
tim = Turtle()
screen = Screen()

screen.listen()
screen.onkeypress(ps.toggle_pause, "p")

pause = ps.toggle_pause()
while True:
    if not pause:
        tim.forward(12)
        tim.left(10)
    else:
        screen.update()

Can you please tell me what I did wrong? Thanks.

CodePudding user response:

The variable pause is only updated once, outside the while loop. You should use the class variable self.is_paused to test the state of the game.

CodePudding user response:

You need to do two things to get the pausing to work in your game using the class:

  1. Change the definition of the Pause class so it updates its is_paused attribute when its toggle_pause() method is called by adding a self. prefix to the is_paused variable name:

    class Pause:
        def __init__(self, is_paused):
            self.is_paused = is_paused
    
        def toggle_pause(self):
            self.is_paused = not self.is_paused
            return self.is_paused
    
  2. Change the way the pause state is checked in the while loop in the main program:

    ...
    
    while True:
        if ps.is_paused:
            tim.forward(12)
            tim.left(10)
        else:
            screen.update()
    
  • Related