3

These two pieces of code output the same thing. What's the difference between them and when should we prefer using one over the other?

   if event.type==pygame.KEYDOWN:
        if event.key==pygame.K_LEFT:
            xc=-4
        if event.key==pygame.K_RIGHT:
            xc=+4
        if event.key==pygame.K_UP:
            yc=-4
        if event.key==pygame.K_DOWN:
            yc=+4

    if event.type==pygame.KEYUP:
        if event.key==pygame.K_LEFT or event.key==pygame.K_RIGHT:
            xc=0
        if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
            yc=0

        pressed=pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]:
        xc=-4
    elif pressed[pygame.K_RIGHT]:
        xc=+4
    else:
        xc=0

    if pressed[pygame.K_UP]:
        yc=-4
    elif pressed[pygame.K_DOWN]:
        yc=+4
    else:
        yc=0
Danana
  • 31
  • 1
  • 5

2 Answers2

4

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.

pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.

See also:

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
4

pygame.KEYDOWN events are only fired when the key is first pressed. You can customize this behavior with pygame.key.set_repeat() in order to make it fire a fixed rate when the key is pressed, though you can't make it match your framerate exactly using this method. This should generally be used for text input, or if an action should happen once when the key is pressed first.

Using pressed will be true as long as the key is pressed, regardless of the setting of set_repeat. This is generally used if something should happen every frame while the key is pressed.

mousetail
  • 7,009
  • 4
  • 25
  • 45