1. 程式人生 > >pygame按鍵持續按下響應

pygame按鍵持續按下響應

在寫一個pygame 的一個小的飛機大戰程式但是碰到一個小問題,僅此記錄

通過鍵盤事件操控飛機的左右移動:
elif event.type == KEYDOWN:

        # 檢測按鍵是否是a或者left
         if event.key == K_a or event.key == K_LEFT:
              plane_temp.move_left()

雖然能實現移動,但是每一次的移動都需要按一下按鈕,使我感覺很難受
想實現可以持續按下,並且可以相應的效果
查資料發現

pygame.key.set_repeat() control how held keys are repeated
set_repeat() -> None set_repeat(delay, interval) -> None When the
keyboard repeat is enabled, keys that are held down will generate
multiple pygame.KEYDOWN events. The delay is the number of
milliseconds before the first repeated pygame.KEYDOWN will be sent.
After that another pygame.KEYDOWN will be sent every interval
milliseconds. If no arguments are passed the key repeat is disabled.

When pygame is initialized the key repeat is disabled.

按鍵是預設只能按下一次,於是就取了一個巧,檢視哪些按鍵是已進按下的,後通過迴圈實現對應操作

key_pressed = pygame.key.get_pressed()
    if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]
        plane_temp.move_left()