← Python functions and events

Catch the turtle

Build a game that uses everything so far. The turtle hops along a path; catch it before it hides.

Every game is a few rules, some data and a loop. You already know all three.

The turtle hops around a path. You will turn it into a game: catch the turtle before it hides, score as many as you can in 30 seconds. You will build it in three milestones, with less help each time.

Behind the code: the turtle is both the target and the pen. penup() stops it drawing lines, and speed(0) makes every move instant.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

catch.py
from turtle import *

speed(0)
penup()

xs = [-120, 0, 120, 120, 0, -120]
ys = [60, 110, 60, -50, -100, -50]
place = 0


def hop():
    global place
    goto(xs[place], ys[place])
    place = (place + 1) % len(xs)
    ontimer(hop, 1000)


hop()
mainloop()

hop() moves the turtle to the next spot in the two lists, then asks the timer to run hop again in 1000 milliseconds.

The turtle starts at place 0. Where is it after its fourth hop?

RunRun it and compare the result with your prediction.

Run

Run it and watch a full lap. Press Stop when you are done.

catch.py
from turtle import *

speed(0)
penup()

xs = [-120, 0, 120, 120, 0, -120]
ys = [60, 110, 60, -50, -100, -50]
place = 0


def hop():
    global place
    goto(xs[place], ys[place])
    place = (place + 1) % len(xs)
    ontimer(hop, 1000)


hop()
mainloop()
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

catch.py
from turtle import *

speed(0)
penup()

xs = [-120, 0, 120, 120, 0, -120]
ys = [60, 110, 60, -50, -100, -50]
place = 0


def hop():
    global place
    goto(xs[place], ys[place])
    place = (place + 1) % len(xs)
    ontimer(hop, 1000)


hop()
mainloop()

Follow place through a lap.

How would you add a spot?

The score from Events, with one line missing.

Fill in place after each hop. The lists have 6 spots.

hopplace usedplace after
101
21
65
71

You want the turtle to visit a seventh spot. What do you change?

Every click should add a point, but the first click stops with an error. Click the line where it goes wrong.

ModifyChange the code on purpose and check the result.

Milestone 1: catch it

The turtle now remembers where it is in tx and ty. Fill in clicked so that a click on the turtle adds a point. Run it and try to catch the turtle.

Try it yourselfYour edits are saved in this browser.
Need a hint?

Use the same check as Build a button: if inside(x, y, tx - 20, ty - 20, 40, 40):

Another hint

Inside the if: score = score + 1, then show_score().

Click the turtle to score.

    Run your program. This ticks when your code does all of the above.

    ModifyChange the code on purpose and check the result.

    Milestone 2: now you see it

    Too easy? Now the turtle only shows for 0.7 seconds. showing is True while it is there and False when it is gone. Follow the three comments that start with Milestone 2.

    Try it yourselfYour edits are saved in this browser.
    Need a hint?

    In hop: showturtle(), then showing = True, then ontimer(hide, 700).

    Another hint

    In hide: if showing: then misses = misses + 1, showing = False and hideturtle().

    Another hint

    In clicked: add showing to the if (if showing and inside(...)), and inside it set showing = False and hideturtle().

    The turtle blinks: it shows, then hides, and a missed turtle counts.

      Run your program. This ticks when your code does all of the above.

      MakeBuild something new using what you have learned. Expect a few tries; that is normal.

      Milestone 3: game on

      Make it a real game: a Start button, a 30 second timer, and a score that resets each game. The comment at the top lists the five parts. If you get stuck, the hints show one part at a time.

      Try it yourselfYour edits are saved in this browser.
      Need a hint?

      Start with time_left = 30 and playing = False. Every function that changes them needs them in its global line. Show the time like the score, at goto(150, 160).

      Another hint

      In clicked: if playing == False and inside(x, y, -60, -180, 120, 40): start(). Draw the Start button only when playing == False.

      Another hint

      tick(): if playing: take 1 from time_left; if it reaches 0 set playing = False, else ontimer(tick, 1000).

      A Start button, a 30-second timer, and the game stops at 0.

        Run your program. This ticks when your code does all of the above.

        ModifyChange the code on purpose and check the result.

        Path or random?

        Play a few games. Do you start moving to the next spot before the turtle arrives? Then try random spots instead. random is a module someone else wrote, just like your ui.py. random.randint(-150, 150) picks a whole number from -150 up to 150, a new one each time it runs, so the turtle lands somewhere new on every hop. The first number is the lowest it can pick and the second is the highest. Swap the first two lines of hop() for the two lines above. Copy import random to the top and random. before randint as they are for now; a later lesson explains how they work. Then change the numbers so the turtle only appears in the top half of the screen.

        catch.py
        import random
        
        # Random spots instead of the path: replace the first two lines of hop() with these.
        tx = random.randint(-150, 150)
        ty = random.randint(-120, 120)
        
        Why can a good player beat the turtle on a path, but not at random?

        For teachers

        The final challenge. Students build a game in three milestones, each with less help, using everything from the course; the turtle hops along a path and players catch it before it hides. About 60 minutes.

        Open the teacher guide: answers, solutions, slides and a worksheet.

        Students will be able to

        Before class

        Play the finished game (the Milestone 3 solution below) for a minute, then read the three milestone starters. Milestone 1 gives most of the code, milestone 2 an outline, milestone 3 only the goals: that fading support is deliberate. The two new words are True and False: a variable like showing remembers whether the turtle is on screen right now. Finishing this lesson and Power-ups marks the course "Challenge complete".

        Running the lesson

        1. Predict and Investigate: the path is two lists (xs and ys) and place says where we are. % wraps place back to 0 at the end of a lap.
        2. The bug task is the missing global line from Events: Python stops on score = score + 1 with UnboundLocalError. Every milestone needs global in each function that changes score, showing or time_left, so point back to it when a student meets this error.
        3. Milestone 1: the catch is the hit test from Build a button, with the box centred on the turtle (tx - 20, ty - 20).
        4. Milestone 2: showing is True while the turtle is visible. Clicks only count when showing is True, and a turtle that hides uncaught is a miss.
        5. Milestone 3: students work from the five goals in the comment. Encourage one goal at a time, running after each.
        6. Path or random: let students play both. A path can be predicted; random spots can only be reacted to.

        The hard part (on purpose)

        Every variable a function changes needs global, and % wraps the path. When the score doesn't change, ask which variables the function changes.

        When students get stuck

        Stretch and support

        Stretch: Make the path draw a picture (each spot a corner of a shape) and reveal it with the pen down at game over.

        Support: Pair students for Milestone 3, one reading the goals and the other typing, swapping after each goal.

        Where it leads

        Power-ups (next) adds lives, a status bar, a gold turtle and an upgrade. Then two optional lessons: Control panel (towards Gradio and web pages) and Game levels (towards MakeCode Arcade and microStudio). Creative option: students design their own path, such as their initials.

        What each step is for

        Now you can
        Next lesson10. Power-upsAdd lives, a status bar, a gold turtle and an upgrade you buy with points.