How can I make a sprite move when key is held down

enrique2334 picture enrique2334 · Apr 1, 2012 · Viewed 32.9k times · Source

Currently the sprite only moves 1 pixel every time a key is pressed. How could I cause the plumber sprite to move constantly when left or right key is being held down?

while running:
    setup_background()
    spriteimg = plumberright

    screen.blit(spriteimg,(x1, y1))

    for event in pygame.event.get():
         if event.type == pygame.QUIT:
             running = False
         elif event.type == pygame.KEYDOWN:
             if event.key == pygame.K_UP:
                 x1 = x1 + 0
                 y1 = y1 - 1
             elif event.key == pygame.K_DOWN:
                 x1 = x1 + 0
                 y1 = y1 + 1
             elif event.key == pygame.K_LEFT:
                 x1 = x1 -1
                 y1 = y1 + 0
             elif event.key == pygame.K_RIGHT:
                 x1 = x1 + 1
                 y1 = y1 + 0

    pygame.display.flip()
    clock.tick(120)

Answer

qiao picture qiao · Apr 1, 2012

You can use pygame.key.get_pressed to do that.

example:

while running:
    keys = pygame.key.get_pressed()  #checking pressed keys
    if keys[pygame.K_UP]:
        y1 -= 1
    if keys[pygame.K_DOWN]:
        y1 += 1