-2

I get the error:

UnboundLocalError: local variable 'x' referenced before assignment

whenever I try to run my game.

I am unsure of how to fix this and have searched for hours. I am trying to print x. X has been assigned 2 times and I am starting to get really frustrated.

Any help is appreciated and an explanation really helps as I am still new to python.

# --- Import ---
import sys
import random
import pygame
from pygame.locals import *
pygame.init()

# --- Constants ---
size = width, height = 720, 480
speed = [2, 2]

screen = pygame.display.set_mode(size)

pygame.display.set_caption("Broom! || BETA::00.1.0")

clock = pygame.time.Clock()

car_width = 140

largeText = pygame.font.Font('freesansbold.ttf',115)
smallText = pygame.font.Font("freesansbold.ttf",20)
#I added this in to try combat the issue but the issue persisted
x = 240
##

# --- Pictures ---
road = pygame.image.load(r"1.png")
BackgroundPNG = pygame.image.load(r"BackgroundPNG.png")
carImg = pygame.image.load(r"Sp1.png").convert_alpha()
a = pygame.image.load(r"E1.png")
b = pygame.image.load(r"E2.png")
c = pygame.image.load(r"E3.png")
d = pygame.image.load(r"E4.png")
e = pygame.image.load(r"E5.png")

# --- Colours ---
black = (0,0,0)
blue = (0,0,255)
green = (0,200,0)
red = (200,0,0)
green_bright = (0,255,0)
red_bright = (255,0,0)



# --- functions --- 

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def crash():
    message_display("You Crashed")

def message_display():
    largeText
    text_, text_rect = text_objects(text, largeText)
    text_rect.center = ((width/2), (height/2))
    screen.blit(text_, text_rect)
    pygame.display.update()
    time.sleep(2)
    game_running()

def game_intro():

    text_vroom, text_vroom_rect = text_objects("V'Room!", largeText)
    text_vroom_rect.center = ((250),(150))

    text_go, text_go_rect = text_objects("GO", smallText)
    text_go_rect.center = ((75+(100/2)),(400+(50/2)))

    text_exit, text_exit_rect = text_objects("Exit", smallText)
    text_exit_rect.center = ((550+(100/2)),(400+(50/2)))

    running = True

    while running:

        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()

        screen.fill(blue)
        screen.blit(BackgroundPNG,(0,0))
        screen.blit(text_vroom, text_vroom_rect)

        # --- Button GO ---

        if 175 > mouse[0] > 75 and 450 > mouse[1] > 400:
            pygame.draw.rect(screen, green_bright,(75,400,100,50))

        if click != None and click[0] == 1:
            game_running()
        else:
            pygame.draw.rect(screen, green,(75,400,100,50))

        screen.blit(text_go, text_go_rect)

        # --- Button EXIT ---

        if 650 > mouse[0] > 550 and 450 > mouse[1] > 400:
            pygame.draw.rect(screen, red_bright,(550,400,100,50))

            if click != None and click[0] == 1:
                pygame.quit()
                quit()
        else:
            pygame.draw.rect(screen, red,(550,400,100,50))

        screen.blit(text_exit, text_exit_rect)

        pygame.display.flip()

        clock.tick(15)

def game_running():

    print("gamerunning")

    #Create pause here
    #Create stop here
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    x = 240
    y = 280
    x_change = 0
    car_speed = 0
    movement()
    o_y = height

def movement():

    crashed = False
    while not crashed:
        print(x)

        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                crashed = True

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5
                elif event.key == pygame.K_RIGHT:
                    x_change = 5
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0



        x += x_change

        screen.fill(blue)
        screen.blit(road, (0,0))
        screen.blit(carImg, (x,y))

        pygame.display.flip()

        if x < -10:
              x = -10
        else:
            if x > 490:
                x = 490
            else:
                fallingObject()



def fallingObject():
    o_x = random.randrange(0,width)
    o_y = o_y + 20
    objectSpawn = True
    while objectSpawn:
        screen.blit(a, (o_x,o_y))
        movement()
        objectSpawn = False                   
clock.tick(30)
game_intro()
pppery
  • 3,731
  • 22
  • 33
  • 46
Larry
  • 117
  • 2
  • 13
  • 1
    The indentation of the code you pasted is broken. – ThiefMaster Dec 26 '15 at 02:07
  • 2
    Please include the line number of the error. This is probably happening on one line, so we don't need the entire program – Arc676 Dec 26 '15 at 02:13
  • 3
    What is the value of the variable x in the function movement()? Where does it get the value? As far as I can see (and I could be wrong), the function doesn't see the global value of the variable x but tries to print its own variable that would be declared in its own scope. If you want to use it as a global variable, you need to use the "global" keyword. For more information, see: http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – prkist Dec 26 '15 at 02:48

1 Answers1

2

The problem can be simplified like this:

>>> def game_running():
        x = 240
        movement()

>>> def movement():
        print(x)
        x += x_change

>>> game_running()

Traceback (most recent call last):
    print(x)
UnboundLocalError: local variable 'x' referenced before assignment

You defined a variable in one function and then tried to use it in another. See Using global variables in a function other than the one that created them.

Another solution would be to create a class and then say self.x.

Community
  • 1
  • 1
Jim K
  • 12,824
  • 2
  • 22
  • 51