1

I have a simple code where a rectangle is displayed and when keyboard button 'a' is pressed, its width will increase by 1.

import pygame, sys

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)
    pygame.display.set_caption('hello world')
    WHITE=(255,255,255)
    BLUE=(0,0,255)
    rectWidth = 1

    while True:
        DISPLAY.fill(WHITE)
        pygame.draw.rect(DISPLAY,BLUE,(100,100,100,50), rectWidth)
        
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            rectWidth += 1
        
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()

        pygame.display.update()
        pygame.time.delay(20)

main()

Problem: It works fine. However, if I declare keys outside of while loop, pressing a is not recognized.

    keys = pygame.key.get_pressed()

    while True:
        DISPLAY.fill(WHITE)
        pygame.draw.rect(DISPLAY,BLUE,(100,100,100,50), rectWidth)
        
        if keys[pygame.K_a]:
            rectWidth += 1

What I've tried: I've tried reading other questions about "get_pressed() not working" but none were specific to my situation. Also tried to look at the source code for get_pressed function but couldn't find it.

Can anyone tell me why declaring keys outside of while loop will result in pressing the 'a' key not being recognized and is there a way for me to see the source code for get_pressed function?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
moortje
  • 45
  • 7

1 Answers1

1

pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is 1, otherwise 0. It is a snapshot of the keys at that very moment. If you do this before the loop, you will only get the state of the keys at the beginning of the application. You must retrieve the new state of the keys in each frame. Also see How can I make a sprite move when key is held down.
Pygame is OpenSource, based on SDL 2.0 and implemented (partially) in C. The source code can be found here: https://github.com/pygame/pygame (the pygame.key module is implemented in key.c: https://github.com/pygame/pygame/blob/main/src_c/key.c)

Rabbid76
  • 202,892
  • 27
  • 131
  • 174