How to detect a key-press with pygame?

Question:

I am making a shooting game in pygame, but this code:

checkfocus = pygame.key.get_focused()
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
#THIS PART DOES NOT WORK
            if event.type == pygame.K_w:
                print(checkfocus)
                print("up")
                pygame.key.set_repeat(0, 1)
                yvalue -= 20
                if yvalue < 0:
                    yvalue = 0
                print(yvalue)
                pygame.time.wait(100)
                screen.fill((52, 61, 82))
                screen.blit(harryshoot, (20, yvalue))
                pygame.display.flip()

somehow doesn’t work, despite other if event.type codes working just fine. Whats the problem here? Why is it only this code that does not get keyboard input? I have tried changing the keys, but that didn’t help.(print("up") also does not show up so it’s not the code itself which is not working).

Asked By: Raifa

||

Answers:

pygame.K_w is not an event type, but a key. You need to verify that the event type is pygame.KEYDOWN and the key is pygame.K_w:

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key== pygame.K_w:
                # [...]

The keyboard events KEYDOWN and KEYUP (see pygame.event module) create a pygame.event.Event object with additional attributes. The key that was pressed can be obtained from the key attribute (e.g. K_RETURN , K_a) and the mod attribute contains a bitset with additional modifiers (e.g. KMOD_LSHIFT). The unicode attribute provides the Unicode representation of the keyboard input.

Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.