1) What do I need to do?
๐ฏ Your mission: Fly the hero
Make a hero you can fly around with all 4 arrow keys.
Bonus: give it a pen trail in your favourite colour so it draws as it flies!
2) What do I need to know?
Listening to the keyboard
screen.onkey(function_name, "Up") says: when Up is pressed, run this function. Don't put brackets after the function name here!
screen.listen() tells the screen to start listening. turtle.done() keeps the program running.
Run the example, then click on the drawing screen and press the arrow keys! Press โ STOP when finished.
๐งฐ Your toolkit for this mission
Everything you need to know to finish this lesson on your own:
screen
The drawing window, which can listen for keys.
How to write it: screen = turtle.Screen() then screen.listen().
screen = turtle.Screen() screen.listen()
Key functions
A small function that runs when a key is pressed.
How to write it: def up(): with a move inside.
def up():
t.setheading(90)
t.forward(20)screen.onkey(function, key)
Connect a key to a function.
How to write it: Key names: "Up", "Down", "Left", "Right". No brackets after the function name!
screen.onkey(up, "Up")
setheading
Point the turtle a direction.
How to write it: 0 = right โข 90 = up โข 180 = left โข 270 = down.
t.setheading(180)
screen.ontimer(function, ms)
Run a function after a delay. Calling it again inside makes animation.
How to write it: Milliseconds: 1000 = 1 second.
def move():
t.forward(2)
screen.ontimer(move, 20)
move()distance & goto
Check how close two turtles are, and jump somewhere.
How to write it: t.distance(star) < 30 is True when close โข star.goto(x, y) jumps there.
if t.distance(star) < 30:
score = score + 1
star.goto(random.randint(-200, 200), random.randint(-200, 200))global
Lets a function change a variable made outside it.
How to write it: Write global score as the first line inside the function.
def check():
global score
score = score + 1Think about it
Look at this code. What happens next, and why? Say it in your own words.
screen.listen() turtle.done()
Watch & explore โถ
Power-up: Listening to the keyboard
See it happen
1 / 3def up():
hero.forward(10)First make a small function that moves your hero.
3) Run the code & terminal output
Press โถ RUN and your program's messages appear here!


Captain Py
Our next adventure is yours to create.
