← Teacher guides

Teacher guide: Objects with turtles

Build a falling-stars game with many turtles, and tidy it step by step: from separate variables to lists, dictionaries and classes.

Open the student course · How the ideas build

Each lesson works two ways. Students can work through the online tutorial at their own pace (it checks their answers and saves their progress in their browser), or you can teach it to the whole class from the slides, then send students into the tutorial for the Modify and Make steps.

Every lesson guide has plain-language notes, the answers to every check, a solution for every task, and slides and a worksheet for Waypoints Prepare. These guide pages are not linked from student pages, but they are not secret either: keep printed Teacher editions for answers you do not want students to find.

Strategies for getting unstuck: Say what it should do, Test a small piece, Read the error, Trace it. A student who is stuck can try one before asking for a hint. The optional course How you learn best introduces them, and a few lesson decks have a short teach, show or nudge slide for one. (Each lesson page links to the cards from its first hint.)

Whole-course cheat sheet: Open to print (every command, grouped by unit: a handout for the final challenge)

Many things on screen

Many turtles at once, then lists and dictionaries to keep track of them.

Many things on screen in 5 minutes (read before teaching this unit)

The idea in plain words

Turtle() makes another turtle. Give it a name, star = Turtle(), and put the name and a dot in front of a command to give the command to that turtle: star.forward(50). Each turtle is an object: it keeps its own position, heading and colour. A command with no name in front goes to the default turtle, the one students used in the turtle course.

Once there are many objects, the program needs a way to keep track of them:

  • Separate variables (s1, s2, s3) work for three and cost the same block of code for every new one.
  • A list of turtles plus a loop handles any number. What each star needs to remember (speed, points) goes in more lists beside it, matched by place number. These lists side by side must always be changed together.
  • A dictionary keeps everything about one star together: {"turtle": s, "speed": 5, "points": 1}, read as star["speed"]. A list of dictionaries is a table: one row per star.

Why programmers use them

  • Games, simulations and apps are full of objects: enemies, bullets, buttons, messages.
  • Lists make the count a number: 4 stars or 400 is the same code.
  • Dictionaries keep a record together, so nothing falls out of step. Most data is stored this way, from spreadsheets to databases.

An everyday picture, and where it breaks

Lists side by side are like a class roll and a separate list of phone numbers, matched by row. They work until someone joins the class and only one list is updated. A dictionary is a contact card: the name and the number stay on the same card.

Try it yourself (5 minutes)

  1. Run Lesson 1's game, then count the lines that mention s1.
  2. In Lesson 2, change range(4) to range(8) and run it.
  3. In Lesson 3, add "colour": "orange" to the dictionary and colour each star with star["turtle"].color(star["colour"]).

Questions students ask

  • Why is there sometimes an extra turtle in the middle? A command without a name in front used the default turtle, so Python drew it.
  • Can a turtle be in a dictionary? Yes. A dictionary can hold any value, including a turtle.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Classes

Make your own kind of object with class, then give it methods: one line adds another star.

Classes in 5 minutes (read before teaching this unit)

The idea in plain words

A class describes a new kind of object. class Star: says what every star stores and what every star can do. Star(100) makes one star; make four and you have four separate stars from one pattern.

  • __init__ (say "init") runs each time a star is made. Inside it, self is the star being made, and self.speed = 5 stores a speed in that star.
  • Read an object's values with its name and a dot: star.speed, like a turtle's own commands.
  • A method is a function inside the class, with self as its first parameter: def move(self):. star.move() runs it for that star. Methods put each kind of object's behaviour in one place.

This course stops there: no inheritance, getters and setters, or class diagrams.

Why programmers use them

  • Many things of the same kind: one class, any number of objects.
  • Behaviour lives with the data: change how a star moves in one place and every star follows.
  • Programs read like the problem: star.move() and rock.touches(player) say what they mean.

An everyday picture, and where it breaks

A class is a cookie cutter and each object is a cookie: same shape, but each one can have its own icing (its own values). Methods are like a vending machine's buttons: you press "give drink" and the machine knows how.

Where it breaks: the cookie cutter does not make cookies by itself. A class does nothing until Star(...) makes an object, and its methods do nothing until they are called.

Try it yourself (5 minutes)

  1. In Lesson 4's Predict, change Pet("Rex", 4) to another pet and print its name.
  2. Remove self. from self.speed = ... in Lesson 4's game and run it: read the AttributeError.
  3. In Lesson 5, add print("caught") inside a new method catch(self) and call it when a star is caught.

Questions students ask

  • Why self? Python passes the object to every method. self is the name for "the star this method was called on".
  • Why two underscores in __init__? Python's names for special methods have them. __init__ is the one Python runs when an object is made.

Cheat sheet: Open to print (A4, with a picture of what each command draws) · Open in Print · Markdown

Open projects

Self-paced briefs students can pick up (after the lesson named on each, where one is named). Students tick their own milestones and claim a badge; the page lights the skills their code uses. Badges stay in the student's browser: ask them to press Show your teacher. Open the projects page

A turtle race (after objects-lists; making an object (t = Turtle(), e = Enemy(5)), a list ([1, 2]), for item in a list, the random module)

Hold a turtle race: line up some turtles, move each one a random amount every turn, and stop when one crosses the finish line. Then say who won.

Milestones:

  • At least four turtles line up, each a different colour.
    1. Make each racer with Turtle(), and keep them all in a list.
    2. Use a loop with a counter to place each one a bit lower than the last, and pick its colour from a list.
    Students can earn this piece (reveal on): for i in range(4):
    t = Turtle()
    t.shape("turtle")
    t.color(colours[i])
    t.penup()
    t.goto(-200, 90 - i * 60)
    t.pendown()
    t.pensize(4)
    racers.append(t)
  • Every turtle moves a random amount each turn, from one loop over the list.
    1. A loop over the racers moves each one once. Wrap it in another loop for the turns.
    2. Use random.randint(a, b) for how far each one moves.
    Students can earn this piece (reveal on): for r in racers:
    r.forward(random.randint(5, 20))
  • The race stops when one crosses the line, and the page says which.
    1. Check each racer's xcor() against the finish line inside the loop.
    2. Remember who crossed first in a variable, and stop the outer loop when it is set.
    3. Say who won with write() on another turtle placed beside the winner.
    Students can earn this piece (reveal on): winner = None
    while winner == None:
    for r in racers:
    r.forward(random.randint(5, 20))
    if r.xcor() > 180 and winner == None:
    winner = r

Builds on Many turtles (a turtle each) and Lists of stars (one loop over them all). The stopping rule is the hard part: students who check for a winner after the whole loop finish one turn late, which is a good conversation about where a check goes. winner == None is a recipe here; None comes properly in Deeper Python. The turtle shape always draws in the same green, so the example gives each racer a coloured trail; circles take a colour if students want coloured racers.

One possible solution
from turtle import *
import random

speed(0)
penup()
goto(180, 120)
pendown()
right(90)
forward(240)          # the finish line
hideturtle()

colours = ["red", "blue", "green", "orange"]
racers = []
for i in range(4):
    t = Turtle()
    t.shape("turtle")
    t.color(colours[i])
    t.penup()
    t.goto(-200, 90 - i * 60)
    t.pendown()
    t.pensize(4)
    racers.append(t)

winner = None
while winner == None:
    for r in racers:
        r.forward(random.randint(5, 20))
        if r.xcor() > 180 and winner == None:
            winner = r

sign = Turtle()
sign.hideturtle()
sign.penup()
sign.goto(150, winner.ycor() + 18)
sign.write("Winner!", False, "left", ("Arial", 14, "bold"))
An aquarium (after objects-methods; class (with __init__ and self), a method (def inside a class, with self), an object's own value (e.speed, self.speed), making an object (t = Turtle(), e = Enemy(5)))

Fill an aquarium with fish that swim by themselves. Each fish is an object made from a class you write, with its own colour and speed and a method that moves it.

Milestones:

  • My Fish class makes a fish with its own colour and speed.
    1. Start with class Fish: and an __init__ that takes the colour.
    2. Store what each fish keeps with self., such as self.speed, and make its turtle in __init__.
    Students can earn this piece (reveal on): class Fish:
    def __init__(self, colour, y):
    self.turtle = Turtle()
    self.turtle.shape("circle")
    self.turtle.color(colour)
    self.turtle.penup()
    self.turtle.goto(random.randint(-200, 200), y)
    self.speed = random.randint(2, 6)
  • A swim method moves a fish and turns it at the walls.
    1. A method is a def inside the class, with self as the first name.
    2. Move forward by self.speed, then check xcor() against each wall and turn if it is past.
    Students can earn this piece (reveal on): def swim(self):
    self.turtle.forward(self.speed)
    if self.turtle.xcor() > 230 or self.turtle.xcor() < -230:
    self.turtle.left(180)
  • A timer swims every fish in the tank, again and again.
    1. Keep the fish in a list, such as tank.
    2. Write a tick function that loops over the tank calling swim, then asks ontimer to run it again.
    Students can earn this piece (reveal on): def tick():
    for f in tank:
    f.swim()
    ontimer(tick, 50)

The same shape as Stars that move themselves: a class with __init__ and one method, a list of objects, and a timer that calls the method on each. Ask students where they'd change how every fish swims (the method) and where they'd add one more fish (the list).

One possible solution
from turtle import *
import random

bgcolor("lightblue")
hideturtle()

class Fish:
    def __init__(self, colour, y):
        self.turtle = Turtle()
        self.turtle.shape("circle")
        self.turtle.color(colour)
        self.turtle.penup()
        self.turtle.goto(random.randint(-200, 200), y)
        self.speed = random.randint(2, 6)

    def swim(self):
        self.turtle.forward(self.speed)
        if self.turtle.xcor() > 230 or self.turtle.xcor() < -230:
            self.turtle.left(180)

tank = []
for i in range(5):
    tank.append(Fish(random.choice(["orange", "gold", "red", "purple"]), -150 + i * 70))

def tick():
    for f in tank:
        f.swim()
    ontimer(tick, 50)

tick()
mainloop()