How to get if a key is pressed pygame [duplicate]

The current state of the keys can be get by pygame.key.get_pressed().

Get the sate of the keys keys = pygame.key.get_pressed() and evaluate if the UP or DOWN is pressed by if keys[pygame.K_UP]: respectively if keys[pygame.K_DOWN]:, continuously in the main application loop:

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        # [...]
    if keys[pygame.K_DOWN]:
        # [...]

Note, the states which are returned by pygame.key.get_pressed() are updated when the events are handled by pygame.event.pump() or pygame.event.get().

Leave a Comment