- Understand event-driven programming
- Use keyboard events with turtle.onkey()
- Control a character with arrow keys
- Understand screen.listen() for capturing events
- Learn about constants for configuration values
- Events are things that happen (like pressing a key)
- Our program "listens" for events and responds
- It's like Scratch's "when space key pressed" blocks
- We connect keys to functions: press Up → call up()
- Scratch: "when [up arrow] key pressed" blocks
- Python Turtle: screen.onkey(up, "Up")
- Same idea: key press triggers an action
- Difference: We write functions instead of using blocks
- Week 7: We used functions for drawing
- Week 9: We use functions for movement
- Events let our program be interactive (like a game!)
- This is the foundation for all keyboard-controlled games
- Ask: "How do games know when you press a key?"
- Quick demo: Run week09.py
- Try: Press arrow keys to move the turtle
- Observe: Movement happens when keys are pressed (not continuous)
Part A: What are events? (5 min)
- Event = something that happens (mouse click, key press, timer)
- Event handler = function that runs when event happens
- Event listener = part of program that watches for events
Examples of events:
- Keyboard: key pressed, key released
- Mouse: clicked, moved, dragged
- Time: timer expires
- Game: collision, level complete
Part B: Keyboard events in Turtle (5 min) Three parts needed:
# 1. Create a function (the event handler)
def jump():
print("Player jumped!")
# 2. Tell screen to listen for events
screen.listen()
# 3. Connect key to function
screen.onkey(jump, "space")Part C: Constants (5 min)
STEP = 20 # Capital letters = constant (doesn't change)- Constants are values we set once and use many times
- Makes code easier to change (change STEP in one place)
- Convention: Use ALL_CAPS for constant names
Part A: Setup (5 min)
screen = turtle.Screen()
screen.title("Move the Hero")
screen.setup(width=600, height=400) # Set window size
hero = turtle.Turtle()
hero.shape("turtle") # Built-in shapes: "turtle", "square", "circle"
hero.penup() # Don't draw lines when moving
hero.speed(0) # Instant movement (looks smooth)
STEP = 20 # How far to move each key pressPart B: Movement functions (10 min)
def up():
hero.sety(hero.ycor() + STEP) # Move upExplain each part:
hero.ycor()gets current Y coordinate+ STEPadds to it (moves up)hero.sety(...)sets new Y position
Show why we need 4 separate functions:
def up(): hero.sety(hero.ycor() + STEP) # Increase Y
def down(): hero.sety(hero.ycor() - STEP) # Decrease Y
def left(): hero.setx(hero.xcor() - STEP) # Decrease X
def right(): hero.setx(hero.xcor() + STEP) # Increase XDraw coordinate diagram:
+Y (up)
|
-X ---+--- +X (right)
(left) |
-Y (down)
Part C: Connecting events (5 min)
screen.listen() # Start listening for keyboard
screen.onkey(up, "Up") # When Up arrow → call up()
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.mainloop() # Keep window openImportant: Order matters!
- Create functions first
- Then listen()
- Then connect with onkey()
- Finally mainloop()
Task A: Run and observe
- Run the program
- Test all four arrow keys
- Notice: turtle doesn't turn, just moves
- Try: Move to all four edges of screen
Task B: Modifications (from student_tasks.md)
- Change STEP to 50 (bigger jumps)
- Change STEP to 5 (smaller movements)
- Change hero.shape() to "square" or "circle"
- Change screen size to 800x600
Task C: Creative challenges
- Add WASD keys as alternative controls
screen.onkey(up, "w") screen.onkey(left, "a") screen.onkey(down, "s") screen.onkey(right, "d")
- Make turtle turn to face movement direction
def up(): hero.setheading(90) # Face up hero.forward(STEP)
- Add diagonal movement (combine X and Y changes)
- Add a "reset" key (R) that returns to center
- Keep turtle on screen (boundary checking)
Advanced challenge:
def up():
new_y = hero.ycor() + STEP
if new_y <= 200: # Don't go past top edge
hero.sety(new_y)Students explain:
- "What does screen.listen() do?"
- "Why do we need four different functions for movement?"
- "What does screen.onkey(up, 'Up') mean?"
- "How would you add a 'jump' function on spacebar?"
-
Forgetting screen.listen()
# screen.listen() # Commented out screen.onkey(up, "Up")
- Shows: Keys don't work
- Fix: Must call screen.listen() before onkey()
-
Calling function instead of passing it
screen.onkey(up(), "Up") # Wrong! Has ()
- Shows: Error or function runs immediately
- Fix: Pass function name without parentheses: up
-
Wrong coordinate logic
def up(): hero.sety(hero.ycor() - STEP) # Wrong! Minus moves DOWN
- Shows: Up key moves turtle down
- Fix: Use + for up, - for down
-
Typo in key name
screen.onkey(up, "up") # Wrong! Should be "Up" with capital
- Shows: Key doesn't work
- Fix: Use exact key names: "Up", "Down", "Left", "Right"
-
Forgetting mainloop()
# screen.mainloop() # Forgot this- Shows: Window closes immediately
- Fix: Always end with screen.mainloop()
- Student can run program and move turtle with arrow keys
- Student can explain what screen.listen() does
- Student can modify STEP value to change speed
- Student can add a new key binding (like spacebar)
- Student understands connection between key press and function call
For students who need support:
- Start with just up/down (2 keys, not 4)
- Provide pre-written functions, focus on onkey() connections
- Use visual diagram showing key → function → movement
- Skip boundary checking initially
For advanced students:
- Add boundary checking (stay on screen)
- Implement smooth turning (face direction of movement)
- Add multiple turtles controlled by different keys
- Create simple obstacle (turtle changes color when touches it)
- Implement "boost" key that temporarily increases STEP
- Add trail effect (pendown when moving)
- Thonny IDE
- week09.py file
- Coordinate system diagram (handout or board)
- Optional: Keyboard layout diagram showing arrow keys
- Event: Something that happens (key press, click)
- Event handler: Function that responds to event
- Event listener: Code that watches for events
- Constant: Value that doesn't change (ALL_CAPS name)
- Coordinate: Position defined by X and Y
- xcor/ycor: Get current X or Y coordinate
- setx/sety: Set new X or Y coordinate
- Video games: All use event-driven programming
- Apps: Buttons are event handlers
- Websites: Click events trigger actions
- This is fundamental to interactive programs
- Add 4 more keys (WASD) for alternative controls
- Make turtle change color when it moves
- Add a "home" key (H) that returns turtle to center
- Create a simple maze: turtle turns red if it hits certain positions
- Research: What other key names can we use? ("space", "Return", etc.)