这里稍微记录一下key.get_pressed() 和 KEYDOWN, KEYUP的用法。
1. key.get_pressed()
返回的是一个布尔值列表,通过True记录该键被按下了,False 表示没有, 但是存在一个缺点是当键按的太快的时候是没办法准确的给定键按下的顺序,在处理text entry 这种我们就不推荐使用。但是想游戏中方向键移动,这种没问题。
eg:
list1 = pygame.key.get_perssed()
if list1[K_w]:
print("key W is being pressed")
官方解释如下:
pygame.key.get_pressed()
get the state of all keyboard buttons
get_pressed() -> bools
Returns a sequence of boolean values representing the state of every key on the keyboard. Use the key constant values to index the array. A
True
value means that the button is pressed.Note:
Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. There is no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to
pygame.key.get_pressed()
. There is also no way to translate these pushed keys into a fully translated character value. See thepygame.KEYDOWN
events on thepygame.event
pygame module for interacting with events and queues queue for this functionality.
2. KEYUP/KEYDOWN event
这种是将键的输入作为event的形式记录,code会清楚的handle每一次的key down 和 up, 但是带来一个问题是当key被快速按下时,会产生大量的event,会影响code的处理速度,因此建议在比较少(偶尔)需要键盘操作的情况下,可以使用此种办法。通过event.type == pygame.KEYDOWN or event.type = pygame.KEYUP 来捕获。