Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
We’ll read the keyboard and move our rectangle so we can control something on screen (like a player or a cursor).
Inside the game loop we get events. When the user presses a key, we get an event with event.type == pygame.KEYDOWN. The key is in event.key. Pygame gives each key a constant, e.g. pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT, pygame.K_SPACE, pygame.K_a, etc.
You can print which key was pressed to check it works:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
print("UP")
if event.key == pygame.K_DOWN:
print("DOWN")
if event.key == pygame.K_LEFT:
print("LEFT")
if event.key == pygame.K_RIGHT:
print("RIGHT")
Create a rect, then in the KEYDOWN block change its position. Remember: decreasing y moves up (y-axis is flipped), so for “up” we do rect.y -= 1. For “down”, rect.y += 1. Left/right: decrease x for left, increase for right.
Example:
rect = pygame.Rect((200, 200), (20, 20))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
rect.y -= 10 # move up (smaller y)
if event.key == pygame.K_DOWN:
rect.y += 10
if event.key == pygame.K_LEFT:
rect.x -= 10
if event.key == pygame.K_RIGHT:
rect.x += 10
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 0, 0), rect)
pygame.display.flip()
Using rect.y -= 10 is the same as rect.y = rect.y - 10 — just shorter. You can use a variable like speed = 5 and then rect.x += speed to make tuning movement easier.
You can clamp the rect so it doesn’t go off the edges using clamp():
rect.clamp_ip(screen.get_rect())
That keeps the rect fully inside the screen.
clamp_ip so the square can’t leave the window.Once this works, you’ve got a controllable character — next we add collision so it can interact with obstacles.
Next: 5.4 Collision and game logic — when two rects touch.