2014-05-21 82 views
0

pygame新手在這裏,我試圖做一個Flappy鳥克隆。我想設置控件,以便按住跳躍鍵不會讓鳥兒跳躍。玩家將不得不繼續跳躍以保持小鳥漂浮,就像原始遊戲一樣。我試圖使用pygame.key.set_repeat()來關閉鍵重複,但它似乎並沒有工作。從查看關於同一主題的其他帖子,我開始認爲這可能是我的事件循環中的一個問題。pygame事件循環的麻煩

感謝您的幫助!

我的代碼:

import pygame 

class Bird(pygame.sprite.Sprite): 
    def __init__(self): 
     #load pic of bird 
     self.image = pygame.image.load('ball.png') 
     #sets bird pic as a rectangle object and moves position to centre 
     self.rect = pygame.rect.Rect((320, 240), self.image.get_size()) 

     #default value for gravity 
     self.dy = 0 #how much to add to current player position 

    def update(self, dt, game): 
     pygame.key.set_repeat() 
     key = pygame.key.get_pressed() 
     if key[pygame.K_UP]: 
      print "jump!!!" 
      self.dy = -400 

     #apply gravity 
     self.dy = min(400, self.dy + 40) 
     self.rect.y += self.dy * dt 

     #collision detection 
     if(self.rect.top <= 0): #top 
      self.rect.y = 0 
      self.dy = -4 
     elif(self.rect.bottom >= 480): #ground 
      self.rect.y = (480-self.rect.width) 

     #blit image to screen 
     screen.blit(self.image, (320, self.rect.y)) 
     pygame.display.flip() 

     print self.rect.center 
     print self.dy 

class Ground(pygame.sprite.Sprite): 
    def __init__(self): 
     self.image = pygame.image.load('ground.png') 
     self.rect = pygame.rect.Rect((0, 480-self.image.get_width()), self.image.get_size()) 



class Game(object): 
    def main(self, screen): 
     clock = pygame.time.Clock() 

     #create background and player object 
     background = pygame.image.load('background.png') 
     #instantiate bird object 
     self.bird = Bird() 
     self.ground = Ground() 

     while 1: 

      dt = clock.tick(30) 

      for event in pygame.event.get(): 
       if event.type == pygame.QUIT: 
        return 
       if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: 
        return 

      screen.blit(background, (0, 0)) 
      pygame.display.flip() 
      self.bird.update(dt/1000., self) #for some reason, update must go last 


if __name__ == '__main__': 
    pygame.init() 
    screen = pygame.display.set_mode((640, 480)) 
    Game().main(screen) 
    pygame.quit() 

回答

2

pygame.key.set_repeat()不會改變任何東西在這裏,因爲鍵重複默認情況下禁用。

而你的錯誤相當簡單:在你的程序將檢查「更新()」方法,如果K_UP是目前壓 - 但你應該只檢查活動,因爲按下按鈕由事件截獲。

簡而言之:事件告訴你是否按下了鍵,「get_pressed()」告訴你是否按下了鍵

因此,您必須編寫類似「jump()」的方法,並在按下K_UP的情況下接收事件時執行它,而不是在「update()」方法內檢查關鍵狀態。不要忘記從「update()」方法刪除跳轉代碼!

class Bird(pygame.sprite.Sprite): 

    def jump(self): 
     print "jump!!!" 
     self.dy = -400 

(...)

for event in pygame.event.get(): 
    if event.type == pygame.QUIT: 
     return 
    if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: 
     return 
    if event.type == pygame.KEYDOWN and event.key == pygame.K_UP: 
     self.bird.jump() 
+0

這完美地工作,仍然是什麼使檢查 「事件」 不同的有點糊塗了。謝謝您的幫助! – whodareswins