2016-05-22 30 views
0

我想用pygame在python中製作遊戲。我的代碼似乎是正確的,但我得到以下錯誤。如何修復pygame中的UnboundLocalError

> Traceback (most recent call last): 
    File "C:\Users\500198\Desktop\Dodge It.py", line 195, in <module> 
    gameLoop() 
    File "C:\Users\500198\Desktop\Dodge It.py", line 190, in gameLoop 
    runGame() 
    File "C:\Users\500198\Desktop\Dodge It.py", line 182, in runGame  
    x += x_change 
UnboundLocalError: local variable 'x' referenced before assignment 

我所試圖做的是移動food image.But出於某種原因變量「X」不會改變,給我上面的錯誤。

加載圖像

carimg=pygame.image.load('food.png') 
x=(display_width*0.45)  
y=(display_height*0.48) 
x_change =0 

汽車圖像

這裏是我的畫上車屏功能:

def car(x,y): 
    gameDisplay.blit(carimg,(x,y)) 

這是我的遊戲運行起來

def runGame(): 
     gameExit = False 
     gameOver = False 
     while not gameExit: 
      while gameOver == True: 
       #Game Over message 

       gameDisplay.fill(white) 
       message_to_screen("Game over", 
            red, 
            y_displace=-50, 
            size="large") 
       message_to_screen("Press C to play again or Q to quit.", 
            white, 
            y_displace=50, 
            size="medium") 
       pygame.display.update() 

       for event in pygame.event.get(): 
        if event.type == pygame.KEYDOWN: 
         if event.key == pygame.K_q: 
          gameExit = True 
          gameOver = False 
         if event.key == pygame.K_c: 
          gameLoop() 
      #Game Controls 
      for event in pygame.event.get(): 
       if event.type == pygame.QUIT: 
        gameExit = True 
       if event.type == pygame.KEYDOWN: 
        if event.key == pygame.K_LEFT: 
         x_change = -5 #Change is x co ordinate by -5 
        elif event.key == pygame.K_RIGHT: 
         x_change = 5 #Change is x co ordinate by +5 

       if event.type == pygame.KEYUP: 
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: 
         x_change=0 #Player should not move up or down 

      x += x_change #X change since i need to move the image 
      gameDisplay.fill(white) 
      car(x,y) 
      pygame.display.update() 
      clock.tick(FPS) 

我的比賽環

def gameLoop(): 
    runGame() 
    pygame.quit() 
    quit() 

循環調用

gameLoop()

+0

我在python 2.7中編寫這段代碼。這是因爲python 2.7和python 3之間語法錯誤和混淆。 –

回答

0

你需要在一開始定義x和y爲全球性的,在使用他們的任何功能。

global x, y, x_change 
carimg=pygame.image.load('food.png') 
x=(display_width*0.45)  
y=(display_height*0.48) 
x_change =0 

並且在遊標循環中。當他們被傳入汽車繪圖功能時,它應該沒問題。

global x,y, x_change