Learning LibraryGame Development LibraryKids

Keyboard input: move things with the arrow keys

A game gets fun when you control it. Keyboard input lets your code check which keys are held down and move the ship in response.

The big idea

Keyboard input means checking which keys are pressed, then reacting — like moving the ship when an arrow key is held.

See it in code

1Start simple

Input is really one question: is a key held? We use True for held. If it's held, we react — here, move the ship's x to the left:

python
left_held = True
x = 240

if left_held:
    x = x - 6

print("Ship x is", x)
Run it — the held key moves the ship left:
Ship x is 234

A key is held or not — True or False. The if turns that into an action. That's all input is.

2A step further

Now a real Ship, and we check the key every frame. Holding left for 20 frames slides the ship well over to the side:

python
from game import Stage, Ship

screen = Stage.create()
Stage.clear(screen)

ship = Ship(240, 520)
left_held = True

for frame in range(20):
    if left_held:
        ship.move_left()

ship.draw(screen)
Run it — 20 frames of holding left move the ship a long way:
A blue player ship near the bottom of a dark play area, moved to the left side after the left key was held for many frames.

One frame moves the ship a little. Many frames of holding left add up to a big slide. That's why the check goes inside the loop.

3In our world

Now the real keyboard. pygame.key.get_pressed() tells us which keys are down right now. We check both arrows: left moves the ship left, right moves it right. Inside the game loop, this runs every frame:

python
import pygame
from game import Stage, Ship

screen = Stage.create()
Stage.clear(screen)

ship = Ship(240, 520)

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
    ship.move_left()
if keys[pygame.K_RIGHT]:
    ship.move_right()

ship.draw(screen)
Run it — the ship is ready to move the moment you hold an arrow:
A blue player ship centered near the bottom of a dark play area.

In the still picture no key is held, so the ship stays put. But drop these checks inside the game loop, and holding the left arrow slides the ship left frame after frame — smooth movement, all from a key check.

The same idea, everywhere

Every game reads your controls this way: check what's pressed, then act. Arrow keys move a character, the space bar jumps or shoots, a letter opens the map. Input is the bridge between the player and the game.

Try it yourself

Add an up-arrow check with keys[pygame.K_UP] (the Ship moves side to side, but you could nudge other sprites). Then imagine holding both arrows — what should happen? Try both ifs being true.

The common mistake

Checking a key only once instead of every frame. Key checks belong inside the game loop, so they run again and again. Check just once and the ship would only ever react for a single instant.

What it unlocks

Reading keys drives sprites through conditionals, and lives inside the game loop.