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
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:
left_held = True
x = 240
if left_held:
x = x - 6
print("Ship x is", x)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.
Now a real Ship, and we check the key every frame. Holding left for 20 frames slides the ship well over to the side:
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)
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.
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:
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)
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.
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.