What all things happens inside pygame when I press a key? When to use pygame.event==KEYDOWN

pygame.key.get_pressed() returns a list with the current states of a key. When a key is hold down, the state for the key is True, else it is False. Use pygame.key.get_pressed() to evaluate if a key is continuously pressed.

while True:

    pressed_key= pygame.key.get_pressed()
    if pressed_key[pygame.K_UP]:
        # the code in this condition is executed as long UP is hold down 
        # [...]

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.

while True:

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                # The following code is executed once, every time when ESC is pressed.
                # [...]

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                # The following code is executed once, every time when ESC is released.
                # [...]

Leave a Comment