2016-05-22 5 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 
関連する問題