2015-09-06 54 views
0

我正在構建一個蛇遊戲,我試圖讓蛇rect繼續移動,而event.type == pygame.KEYDOWN。我可以讓該塊在KEYDOWN上移動,但它不會通過更新rectlead_x值繼續移動。Pygame - 問題改變x值雖然event.type == pygame.KEYDOWN

import pygame 
pygame.init() 

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

gameDisplay = pygame.display.set_mode((800,600)) 
pygame.display.set_caption('Slither') 

gameExit = False 

lead_x = 300 
lead_y = 300 
lead_x_change = 0 
lead_y_change = 0 

clock = pygame.time.Clock() 

while not gameExit: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      gameExit = True 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT: 
       lead_x_change = -10 
       lead_y_change = 0 
      elif event.key == pygame.K_RIGHT: 
       lead_x_change = 10 
       lead_y_change = 0 
      elif event.key == pygame.K_UP: 
       lead_y_change = -10 
       lead_x_change = 0 
      elif event.key == pygame.K_DOWN: 
       lead_y_change = 10 
       lead_x_change = 0 
     if event.type == pygame.MOUSEMOTION: 
      lead_y_change = 0 
      lead_x_change = 0 

     print(event) 
     lead_x += lead_x_change 
     lead_y += lead_y_change 

     gameDisplay.fill(white) 
     gameDisplay.fill(black, rect=[lead_x,lead_y,10,10]) 
     gameDisplay.fill(red, rect=[200,200,10,10]) 
     pygame.display.update() 

     clock.tick(15) 

pygame.quit() 
quit() 

回答

2

看來你已經把遊戲循環代碼放在事件處理程序中。從包容

lead_x + = lead_x_change和clock.tick(15)之間的各行中刪除的縮進我也會刪除線

if event.type == pygame.MOUSEMOTION: 
    lead_y_change = 0 
    lead_x_change = 0 

,因爲他們將從如果您移動鼠標停止移動的領先地位。