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?