Menu
CoddyTech

Arrow Keys

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 5 of 32.

To move the square, keep its position in variables and draw it there every frame. Change the variables and the next frame shows the square somewhere else.

pygame.key.get_pressed() tells you which keys are held down right now. Index it with a key constant such as pygame.K_RIGHT: the result is True while that key is down.

x = 100

while running:
    # events
    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT]:
        x += 4
    # fill, then draw at x

Hold Right and the square moves 4 pixels in every frame, 240 pixels a second at 60 frames a second. The arrow keys are K_LEFT, K_RIGHT, K_UP and K_DOWN. Up means a smaller y.

Make the variables before the loop. A variable set inside the loop starts over on every frame.

challenge icon

Challenge

Easy

Move the square with the arrow keys:

  1. Before the loop, make x, y = 220, 160 and speed = 4.
  2. In the loop, after the events, read the keys with pygame.key.get_pressed(). Each held arrow changes x or y by speed.
  3. Draw the square at (x, y, 40, 40).

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Move the Square")
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), (220, 160, 40, 40))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in The Game Loop

Practice on your own: Pygame playground