Menu
CoddyTech

Keys Move the Moon

Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 11 of 32.

pygame.key.get_pressed() tells you which keys are held down in this frame. Store its answer once a frame, then ask it about a key:

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    moon_x = moon_x - 4
if keys[pygame.K_RIGHT]:
    moon_x = moon_x + 4

keys[pygame.K_LEFT] is True while Left is held and False otherwise, so the if under it runs on every frame the key is down. Hold Right for one second and the moon moves 240 pixels.

Every key has a name: K_UP, K_DOWN, K_SPACE, K_a for A, K_d for D.

Use two separate ifs, one per key, so each key is tested on its own. The ifs go in the change part, after the event loop.

challenge icon

Challenge

Easy

Move the moon with the arrow keys:

  1. In the change part, read the keys with keys = pygame.key.get_pressed().
  2. While Left is held, subtract 4 from moon_x.
  3. While Right is held, add 4 to moon_x.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()

# Set things up here, before the game loop.
moon_x = 320
moon_y = 240

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

    # Change things here, once a frame.

    screen.fill((20, 24, 48))
    # Draw here, after the fill.
    pygame.draw.circle(screen, (240, 230, 160), (moon_x, moon_y), 50)

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground