1

I'm trying to add a pause function to my Pygame, but there's an error constantly coming up --> UnboundLocalError: local variable 'pause' referenced before assignment I don't know how to solve this, and I've re-arranged the code a couple of times. Any help would be appreciated. Code is down below...

            #PAUSING
            if pause:
                screen.fill((0, 0, 0))
                pause_text = font2.render("PAUSE",True,(255,255,255))
                screen.blit(pause_text, (468 - (pause_text.get_width() // 2), 368 - (pause_text.get_height() // 2)))

            pause = False
            pause_time = 0 #Time spent with the game paused

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    if pause:
                        pause = False
                        pause_time += time.time() - pause_time_start
                    else:
                        pause = True
                        pause_time_start = time.time()

As I mentioned earlier, the output should be pausing the game. For this, I'd just like for someone to show me the proper way to arrange the code.

Zaed
  • 21
  • 5
  • 2
    `pause` is referenced in `if pause` without having a value, presumably this is in a function, so `pause` will be a local variable because you assign to it: `pause = False` and `pause = True` – juanpa.arrivillaga Apr 17 '19 at 22:43
  • So where should I move the ```pause``` to? Thanks in advance – Zaed Apr 17 '19 at 22:47
  • The variable needs to be initialized outside the function, before you call the function. – Barmar Apr 17 '19 at 22:48
  • That is up to you, but you need to assign it before you use it. – juanpa.arrivillaga Apr 17 '19 at 23:00
  • @Zaed yes, to assign to a variable is `x = `. Think about it, I can't *use `x`*, say `print(x)` before I assign to x, `x = 'foo'`. The assignment must come first – juanpa.arrivillaga Apr 17 '19 at 23:05
  • Ok it works now thanks so much... but there's another problem -__- ..... The pause function isn't even WORKING! – Zaed Apr 17 '19 at 23:08
  • pause can't work if you set `pause = False` and `pause_time = 0` in every loop inside mainloop. Assign these values BEFORE mainloop and later change it only in `if/else`. – furas Apr 17 '19 at 23:43
  • you could render text "PAUSE" before mainloop. You don't change this text so you don't have to render it again in every loop. Inside loop you have to only blit this text. Before loop you could also calculate its position - you don't have to calculate it again and again. If you want to center it on screen then (befor loop) you can do `pause_rect = pause_text.get_rect()` and `pause_rect.center = screen.get_rect().center`, and inside loop `blit(pause_text, pause_rect)` – furas Apr 17 '19 at 23:46

0 Answers0