1

in the below while sentence, 'pressed_key = pygame.key.get_pressed()' is out of for area, this sentence also work well, what is different it under for or not?

while 1:
    clock.tick(60)
    for event in pygame.event.get()
        if event.type == pygame.QUIT
            sys.exit()
    pressed_key = pygame.key.get_pressed()

I added 'pressed_key = pygame.key.get_pressed()' under for and put it out.

  • Checking `pygame.key.getpressed()` vs checking for `KEYDOWN` events can give you somewhat different results and may need different handling depending on what you want the effect to be - for example, if you want continuous movement, or require a keypress per action. See this question for some related discussion, especially the examples given by Rabbid76 : https://stackoverflow.com/questions/16044229/how-to-get-keyboard-input-in-pygame – nigh_anxiety Jun 29 '23 at 03:05

1 Answers1

1

The difference is, that within the for loop, this statement is executed multiple times (as often as the length of Eventlist returned by pygame.event.get()), presumably always returing the same value.

It is sufficient to get the key_pressed only once per clock.tick, elsewise you would create a "sub-frame" resolution of the currently pressed keys, which might not be what you are looking for.

So posititioning it outside the event for loop (either before or after, depending on your game logic) should be the better (and less resource-hungry) way.

Christian Karcher
  • 2,533
  • 1
  • 12
  • 17