How to use pygame.KEYDOWN?

青春壹個敷衍的年華 提交于 2019-11-27 05:31:00
sloth

Use pygame.KEYDOWN and pygame.KEYUP to detect if a key is physically pressed down or released. You can activate keyboard repeat by using pygame.key.set_repeat to generate multiple pygame.KEYDOWN events when a key is held down, but that's rarely a good idea.

Instead, you can use pygame.key.get_pressed() to check if a key is currently held down:

while True:
    ...
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_w]:
       print("w is pressed")
    if pressed[pygame.K_s]:
       print("s is pressed")
event.key == chr('a') 

event.key returns the ascii of the key

I would advice you to stick with the event-driven approach rather than using a polling mechanism.

You should let the key events alter some internal state to reflect a pressed key imo.

Example: You are controlling a spaceship with your keyboard. You want the propulsion rockets to fire when you press one of 'w', 's', 'a' or 'd' to make the ship accelerate in a certain direction:

  • On pygame.KEYDOWN event, set an appropriate acceleration vector for the object if event.key in [K_w, K_s, K_a, K_d].
  • On pygame.KEYUP event, set the acceleration vector to the zero vector if event.key in [K_w, K_s, K_a, K_d].

This will effectively make the object accelerate while a movement key is pressed, and stop accelerating when the key is released.

Use pygame.key.set_repeat().

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!