2015-12-26 4 views
-2

я получаю ошибку:Python Pygame: UnboundLocalError: локальная переменная «х» обращаться до присвоения

UnboundLocalError: local variable 'x' referenced before assignment

всякий раз, когда я пытаюсь запустить мою игру.

Я не уверен, как исправить это, и искали часы. Я пытаюсь сделать print x. X был назначен 2 раза, и я начинаю сильно расстраиваться.

Любая помощь приветствуется, и объяснение действительно помогает, поскольку я все еще новичок в 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() 
+1

Отступ кода, который вы вставили, сломан. – ThiefMaster

+2

Просьба указать номер строки ошибки. Вероятно, это происходит на одной строке, поэтому нам не нужна вся программа – Arc676

+3

Какова величина переменной x в функции move()? Где он получает ценность? Насколько я могу видеть (и я мог ошибаться), функция не видит глобального значения переменной x, но пытается напечатать свою собственную переменную, которая будет объявлена ​​в ее собственной области. Если вы хотите использовать его как глобальную переменную, вам нужно использовать ключевое слово «global». Для получения дополнительной информации см. Http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – prkist

ответ

2

Проблема может быть упрощена следующим образом:

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

Вы определили переменную в одной функции, а затем пытались использовать его в другом. См. Using global variables in a function other than the one that created them.

Другим решением было бы создать класс, а затем сказать self.x.

Смежные вопросы