Lesson 8: Moving the Ship โ Keyboard Events (Matthes Ch 12 ยง6 pt 1)
Learning Intentions
- Make the ship respond to Right and Left arrow keys by tracking key-down / key-up events with a flag variable.
Success Criteria
- Pressing Right arrow makes my ship move right.
- Releasing the key makes it stop.
- I can explain what the moving_right flag is for.
๐ Do Now โ Error of the Day
Press and HOLD the Right arrow key right now (in any app). Notice โ it fires once, pauses briefly, then repeats. That's the OS's keyboard autorepeat. We'll do it better with KEYDOWN/KEYUP.
๐ I Do โ Teacher Demo
Live-code the KEYDOWN/KEYUP flag pattern: self.moving_right = True on KEYDOWN, False on KEYUP. Ship.update moves rect.x while flag is True.
๐ค We Do โ Build Together
Class wires up the flag pattern together. Press Right โ ship moves right until you release. Same for Left. Troubleshoot stuck students live.
๐ You Do โ Your Turn
Add Left key support (mirror of Right). Extension: add Up/Down. Arcade quests below practice KEYDOWN/KEYUP + flag patterns.
- Add self.moving_right = False to Ship.__init__
- Write Ship.update() that uses moving_right to move rect.x
- In _check_events, branch event.type: KEYDOWN vs KEYUP
- If event.key == pygame.K_RIGHT, set ship.moving_right True (or False on KEYUP)
๐ฎ Practice Quests โ work through these
Loading practice quests for this lesson...
Three tiers โ pick yours
Support
ship_v2_starter.py with moving_right pre-declared
Core
implement from scratch
Extension
4-direction movement
Extensions
- Add Up/Down arrows using moving_up / moving_down flags.
- Add WASD as alternative keys.
๐ Exit Ticket โ Coding Journal
Journal: explain why the flag pattern is smoother than 'move on KEYDOWN' (what would break?).
Evidence of Learning
Ship moves right while key is held, stops when released. Left arrow works too.