Arrow Keys
Lesson 5 of 40 in Coddy's Make Games with Pygame course.
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 xHold 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
EasyMove the square with the arrow keys:
- Before the loop, make
x, y = 220, 160andspeed = 4. - In the loop, after the events, read the keys with
pygame.key.get_pressed(). Each held arrow changesxorybyspeed. - 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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Make Games with Pygame
Practice on your own: Pygame playground