I just started with python/pygame and wanted to create a simple screen with a red moving rectangle. It worked! Now I wanted to let the rectangle move while a key is pressed down.

I tried to store False or True in values for each direction (e.g pressedu for pressed up) and later ask if the value is True. If yes, the rectangle should move in the asked direction.

But my rectangle still only moves one step when I keep a key pressed. Can somebody find the error because I can't.

Thank you!

while gameexit == False:
    for event in pygame.event.get():

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                pressedl = True
            if event.key == pygame.K_RIGHT:
                pressedr = True
            if event.key == pygame.K_UP:
                pressedu = True
            if event.key == pygame.K_DOWN:
                pressedd = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                pressedl = False
            elif event.key == pygame.K_RIGHT:
                pressedr = False
            elif event.key == pygame.K_UP:
                pressedu = False
            elif event.key == pygame.K_DOWN:
                pressedd = False

        if pressedl == True:
            x -= playersize/2
        if pressedr == True:
            x += playersize/2
        if pressedu == True:
            y -= playersize/2
        if pressedd == True:
            y += playersize/2

        playerpos = [x,y]

        if event.type == pygame.QUIT:

    pygame.draw.rect(screen, RED, [playerpos[0],playerpos[1],playersize,playersize])

New contributor
  • Check your indentation. the if pressedl == True: is inside the for event ... loop but needs to be outside – Thomas Weller Aug 12 at 18:58

PyGame's KEYUP and KEYDOWN events are only fired once when the action happens. So if the key is held down there are no further UP/DOWN events until the key is released.

You may wish to use the pygame.key.get_pressed() dictionary to check which keys are currently pressed:

# Movement keys
keys = pygame.key.get_pressed()
if ( keys[pygame.K_UP] ):
elif ( keys[pygame.K_DOWN] ):
elif ( keys[pygame.K_LEFT] ):
elif ( keys[pygame.K_RIGHT] ):
elif ( keys[pygame.K_q] and ( keys[pygame.K_RCTRL] or keys[pygame.K_LCTRL] ) ):
    done = True

Your Answer

sabrinap is a new contributor. Be nice, and check out our Code of Conduct.

