โ† All missions

๐ŸŽฎ Hero Controller

๐ŸŽจ Reusable Code & Art

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 + 1

Think 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 / 3
def up():
    hero.forward(10)
up()
move 10

First make a small function that moves your hero.

3) Run the code & terminal output

Code Lab ๐ŸPlayground โ€” experiment freely!
Hero Terminal

Press โ–ถ RUN and your program's messages appear here!

Power Workshop
Power Workshop
Your superhero companion

Captain Py

Our next adventure is yours to create.