1

I am making a game with two main global variables

game_over = False
flying = True

In my Bird class i can reference these variables. Nowhere in the Bird() class do i change these variables

class Bird(pygame.sprite.Sprite):
    def __init__(self):
        ...
    def update(self):
        if (flying == True) and (game_over == False):
            ...
        if game_over == False:
            ...

However, in another class i need to both reference and set these variables

class Button1(pygame.sprite.Sprite):
    def __init__(self):
        ...
    def update(self):
        if game_over == True:
           ...
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                ...
                game_over = False
                flying = True

Here, I get the error:

UnboundLocalError: local variable 'game_over' referenced before assignment

Instead of setting the global game_over and global flying, it creates new local variables game_over and flying.
How do I fix this?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Vas
  • 130
  • 10

1 Answers1

1

In order to set global variables in Python, you need to declare them at the top of the function. For example,

def update(self):
    global flying, game_over
    if game_over == True:
       ...
        if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
            ...
            game_over = False
            flying = True
        ...
RShields
  • 316
  • 1
  • 8
  • The global variables have already been defined. I tried doing that, but it says SyntaxError: name 'game_over' is used prior to global declaration – Vas Mar 07 '22 at 03:26
  • @VasuK Are the globals defined in the same python file as the `update()` function? – John Gordon Mar 07 '22 at 03:36
  • yes and its working in all other classes only in the Button1 class its not working – Vas Mar 07 '22 at 03:39