0

i try to create a Flappy Bird clone. When i try to define some Global variables visual studio said me that this variables aren't defined in global scope.

Some could help me??

I tried to move the variables in the global scope and it works, but i don't understand why this solution doesn 't work.

This is my code Thanks in advance

import pygame
import random

pygame.init()

background = pygame.image.load('img/background.png')
base = pygame.image.load('img/base.png')
bird = pygame.image.load('img/bird.png')
gameover = pygame.image.load('img/gameover.png')
pipe_down = pygame.image.load('img/pipe.png')
pipe_up = pygame.transform.flip(pipe_down, False, True)

windowX = 288
winwowY = 512
frame_rate = 50

display_surface = pygame.display.set_mode((windowX, winwowY))
FPS = frame_rate

pygame.display.set_caption('Flappy Bird')

def drawObject():
    display_surface.blit(background, (0, 0))
    display_surface.blit(bird, (birdX, birdY))

def update():
    pygame.display.update()
    pygame.time.Clock().tick(FPS)

# Here is where define my global vars
def initializes():
    global birdX, birdY, birdSpeedY
    birdX = 60
    birdY = 150
    birdSpeedY = 0

initializes()

while True:
    birdSpeedY += 1
    birdY += birdSpeedY

    drawObject()
    update()

1 Answer 1

1

The message is telling you exactly what the issue is. The global variables aren't defined in global scope.

That means that for these variables that you are telling it you want to use from the global namespace global birdX, birdY, birdSpeedY, it expects to find a definition of those in that uppermost namespace. The global keyword does NOT create them in the global namespace just because you use it. They must exist there independent of that.

For them to be defined in the global scope there needs to be an assignment to them in the global namespace, not inside a function or a class. That cannot be something a += either since that is a reference and an assignment and so it assumes that the definition must be elsewhere (or it would be being referenced before a value was assigned).

So somewhere in the global namespace you need an assignment. If you want to handle the initialization in a function (as you are doing) it must still be defined/assigned outside that function, but it can be any value, like None. So you could add this near the top of you program:

birdX = None
birdY = None
birdSpeedY = None

Then still use your initializes() as you are.

Or in your case you would probably just take the stuff inside initializes() and put it at the top /global level.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.