-3

I'm creating my first Python game ever, and I tried to do pause/unpause game function. I have created a global pause variable which is set to false by declaration. But when i press press button assigned to my pause function the programs gives me this error: local variable 'pause' referenced before assignment

Here's paused() function assignment to a button:

if event.key == pygame.K_p:
    pause = True
    paused()

And here's my paused() function:

def paused():  

while pause:        

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_m:
                pause = False


    pygame.display.update()
    clock.tick(15)          
    #gameDisplay.fill(white)   `
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
  • indentation matters. yours is off. – Patrick Artner Dec 26 '18 at 16:41
  • 4
    you need to read about scoping - your local variable is not known in other functions – Patrick Artner Dec 26 '18 at 16:43
  • [short-description-of-the-scoping-rules](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – Patrick Artner Dec 26 '18 at 16:44
  • why not just say `while True:` I don't often find a good reason to convolute a Boolean just because you don't like its name. The function `paused()` should be enough of an indicator of what is going on to not assign a Boolean to a variable. – d_kennetz Dec 26 '18 at 16:53
  • You could pass the `pause` variable to the `paused` function, otherwise you're going to have to declare `global pause` within `paused` – Rolf of Saxony Dec 26 '18 at 17:05

1 Answers1

0

pause is a local variable of your main, so sending it to the function is necessarry. Also, there were some identation errors. Here is the fixed version:

if event.key == pygame.K_p:
    pause = True
    paused(pause)

def paused(pause):  

    while pause:        

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_m:
                    pause = False


        pygame.display.update()
        clock.tick(15)          
        #gameDisplay.fill(white)   `
Pedro Martins de Souza
  • 1,406
  • 1
  • 13
  • 35