2016-11-26 141 views
0

我正在製作一款適合學校的遊戲,這是一款迷你RPG遊戲。我試圖編碼它,以便圖像更改,但我的代碼不起作用。我瀏覽過很多文章,但我還沒有找到適合我的案例的工作解決方案。我是否在某個特定領域做錯了什麼,或者我是否以完全錯誤的角度開始了代碼?非常感謝幫助。在pygame中更改圖像

import pygame 

pygame.init() 

width = 800 
height = 600 

black = (0, 0, 0) 
white = (255, 255, 255) 
red = (255, 0, 0) 
green = (0, 255, 0) 
blue = (0, 0, 255) 

gameDisplay = pygame.display.set_mode((width, height)) 
pygame.display.set_caption('8Bit Adventure Time!') 
clock = pygame.time.Clock() 

finnImg = [pygame.image.load('AdvManRight.png'), pygame.image.load('AdvManLeft.png')] 
finnImg_current = finnImg[0] 

finnwidth = 115 
finnheight = 201 

def Finn(x, y): 
    gameDisplay.blit(finnImg_current, (x, y)) 

def game_loop(): 

    x = ((width/2) - (finnwidth/2)) 
    y = ((height/2) - (finnheight/2)) 


    gameExit = False 

    while not gameExit: 

     x_change = 0 
     y_change = 0 

     gameDisplay.fill(white) 
     Finn(x,y) 

     for event in pygame.event.get(): 

      if event.type == pygame.QUIT: 
       pygame.quit() 
       quit() 

      if event.type == pygame.KEYDOWN: 
       if event.key == pygame.K_LEFT: 
        finnImg_current = finnImg[0] 
        pygame.display.update() #the image is supposed to change here, but nothing happens... 
        x_change = -40 
       if event.key == pygame.K_RIGHT: 
        finnImg_current = finnImg[1] 
        pygame.display.update() #the image is supposed to change here, but nothing happens... 
        x_change = 40 
       if event.key == pygame.K_UP: 
        y_change = -40 
       if event.key == pygame.K_DOWN: 
        y_change = 40 

     x += x_change 
     y += y_change 

     pygame.display.update() 
     clock.tick(60) 

game_loop() 
pygame.quit() 
quit() 

回答

0

你有一個全局變量finnImg_current這是什麼被blit的屏幕,當你調用Finn(x, y)。但是在你的遊戲循環中,你正在創建一個局部變量,也叫做finnImg_current。這些是不同的!

要解決此問題,您只需在功能game_loop的頂部鍵入global finnImg_current即可。另外,pygame.display.update()應該只在遊戲循環中調用一次,最好在其結束時調用。

嘗試在編寫代碼時遵循PEP8約定,這使得其他程序員更容易閱讀它。基本上,變量和函數應該用lowercase_and_underscore來命名,而類別則應該用CamelCase來命名。儘量不要混合這些,因爲它會令人困惑。

+0

謝謝!一旦我讀完信息,它就起作用了。 –