0

I'm trying to get a rectangle to move on screen, but the keyboard presses aren't working, and I can't solve it. Can someone help?

import pygame

WIN = pygame.display.set_mode((900, 500))
pygame.display.set_caption("coolioso")

FPS = 60
keys_pressed = pygame.key.get_pressed()

vel = 10

player = pygame.Rect(450, 250, 50, 50)



def draw_window():
    WIN.fill((255, 255, 255))
    pygame.draw.rect(WIN, (255, 0, 0), (player))

def main():

    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False


        if event.type == pygame.KEYDOWN:
            if keys_pressed[pygame.K_w]:
                player.y += vel
        
        
        
        draw_window()
        pygame.display.update()
            
    pygame.quit()

if __name__ == "__main__":
    main()

I tried using multiple different methods like functions, putting the key press statement elsewhere, but nothing worked and nothing changed.

The Boip
  • 1
  • 2
  • 1
    You set `keys_pressed` once at the top, and never change it. That's not a dynamic variable -- it doesn't change automatically. To get the new key state, you have to FETCH the new key state. Move that statement to just after the `if` for KEYDOWN. – Tim Roberts Feb 18 '23 at 02:25

0 Answers0