Global game variables not being updated

Viewed 51

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?

1 Answers

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
        ...
Related