Explain in detail the two ways of pygame capturing keyboard events

  • 2021-10-24 23:19:57
  • OfStack

Mode 1: Use the pygame. event. get () method in pygame to capture keyboard events. Keyboard events captured in this way must be pressed and then popped once.
Example Example:


for event in pygame.event.get(): #  Capture keyboard events 
  if event.type == pygame.QUIT: #  Determine the key type 
    print(" Press the exit button ")

Mode 2: In pygame, you can use pygame. key. get_pressed () to return all key tuples. By judging the keyboard constant, you can judge which key is pressed in the tuple. If pressed, this key information will exist in the tuple. In this way, the keyboard events can also be captured, and there is no need to press and then pop up, and 1 will respond when pressed, so the flexibility is relatively high.

Sample code:


mykeyslist = pygame.key.get_pressed() #  Get key tuple information 
if mykeyslist[pygame.K_RIGHT]: #  If the key is pressed, the value is 1
  print(" Press the right direction button ")
 

Summary:
Comparison of two ways: The flexibility of way 1 is not as good as that of way 2. If the game requires high flexibility, it is recommended to use way 2.

The pygame key is continuously pressed to respond

I am writing a small aircraft war program of pygame but I have encountered a small problem, only this record

Manipulate the left and right movement of the aircraft through keyboard events:


elif event.type == KEYDOWN:

    #  Detect whether the key is a Or left
     if event.key == K_a or event.key == K_LEFT:
       plane_temp.move_left()

Although I can move, I need to press a button every time I move, which makes me feel very uncomfortable

If you want to achieve it, you can press it continuously and have the corresponding effect

Check the data and find

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.

By default, you can only press the key once, so you take a clever one to see which keys have been pressed, and then realize the corresponding operation through a loop


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

Corresponding help documentation for pygame:
https://www.pygame.org/docs/ref/key.html#comment_pygame_key_set_repeat


Related articles: