Python turtle and tkinter

Turtle Race

Line up four racing turtles, let random numbers decide who wins, and guess the winner first.

Day 4 50 to 60 minutes 8 steps Key Stage 3
Start step 1
Then the race runs, and this time red won. Every race is different!

Four turtles, one finish line, and nobody knows who will win, not even you. Each turtle moves forward a random number of steps at a time, so every race is different. Before the race starts, you will guess the winner.

You will learn

  • Make several turtles and keep them in a list
  • Use random numbers so every race is different
  • Repeat with a while loop until something happens
  • Make a decision with if and else

You will need

  • A computer with Thonny or IDLE, or this page's Run it here button

Words to know

random
Unpredictable. random.randint(1, 10) picks any whole number from 1 to 10.
while loop
A loop that repeats for as long as its condition is true.
condition
A question that is true or false, such as racer.xcor() >= 200.
None
Python's word for nothing at all, used here to mean there is no winner yet.

Step by step

  1. Step 1: Start a new file

    Click New and save the file as race.py. import random gives you Python's random numbers, which you will need later.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") turtle.done()
    A green field with an arrow in the middle: the turtle every program starts with.
  2. Step 2: Draw the finish line

    A turtle called judge draws the finish line, then hides. It goes to the top of the line, turns right to face down the window, and draws a thick line 300 steps long.

    New: lines 7 to 17.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) turtle.done()
    A black finish line on the right.
  3. Step 3: Your first racer

    Make a red turtle and walk it, without drawing, to the start on the left.

    New: lines 18 to 24.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) red = turtle.Turtle()red.shape("turtle")red.color("red")red.penup()red.goto(-250, 100)red.pendown() turtle.done()
    A red turtle waits at the start.
  4. Step 4: Four racers

    Four turtles could take four copies of that code. A loop is shorter. Each time round, it makes a turtle, gives it the next colour, puts it 60 steps lower than the last, and adds it to the list racers with append. Replace the red turtle's lines with the loop.

    New: lines 18 to 28.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) colours = ["red", "blue", "orange", "purple"]racers = [] for i in range(4):    racer = turtle.Turtle()    racer.shape("turtle")    racer.color(colours[i])    racer.penup()    racer.goto(-250, 100 - i * 60)    racer.pendown()    racers.append(racer) turtle.done()
    Four turtles on their marks, one above the other.
  5. Step 5: They're off!

    random.randint(1, 10) picks a whole number from 1 to 10. Loop through the list and move each racer forward that many steps. Run it a few times: the turtles only move once, but never quite the same.

    New: lines 30 to 32.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) colours = ["red", "blue", "orange", "purple"]racers = [] for i in range(4):    racer = turtle.Turtle()    racer.shape("turtle")    racer.color(colours[i])    racer.penup()    racer.goto(-250, 100 - i * 60)    racer.pendown()    racers.append(racer) for racer in racers:    racer.forward(random.randint(1, 10)) turtle.done()
    One hop each, all slightly different.
  6. Step 6: Race to the finish

    A while loop repeats for as long as its condition is true. winner starts as None, which means nobody yet. Every turtle hops, and as soon as one reaches x = 200, the finish line, it becomes the winner. break stops the for loop there, and because winner is no longer None, the while loop ends too. Replace the one hop loop with this.

    New: lines 30 to 36.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) colours = ["red", "blue", "orange", "purple"]racers = [] for i in range(4):    racer = turtle.Turtle()    racer.shape("turtle")    racer.color(colours[i])    racer.penup()    racer.goto(-250, 100 - i * 60)    racer.pendown()    racers.append(racer) winner = Nonewhile winner is None:    for racer in racers:        racer.forward(random.randint(1, 10))        if racer.xcor() >= 200:            winner = racer            break turtle.done()
    The race runs until one turtle crosses the line.
  7. Step 7: Announce the winner

    pencolor() tells you the winner's colour. The judge writes it above the race.

    New: lines 38 to 42.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) colours = ["red", "blue", "orange", "purple"]racers = [] for i in range(4):    racer = turtle.Turtle()    racer.shape("turtle")    racer.color(colours[i])    racer.penup()    racer.goto(-250, 100 - i * 60)    racer.pendown()    racers.append(racer) winner = Nonewhile winner is None:    for racer in racers:        racer.forward(random.randint(1, 10))        if racer.xcor() >= 200:            winner = racer            break colour = winner.pencolor()judge.penup()judge.goto(0, 170)judge.write("The " + colour + " turtle wins!", align="center", font=("Arial", 20, "bold")) turtle.done()
    The judge names the winner at the top.
  8. Step 8: Place your bet

    Before the race, ask the player to guess. input waits for them to type in the Shell. After the race, if checks whether the guess was right, and else covers every other case.

    New: lines 30, 31 and 45 to 49.

    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) colours = ["red", "blue", "orange", "purple"]racers = [] for i in range(4):    racer = turtle.Turtle()    racer.shape("turtle")    racer.color(colours[i])    racer.penup()    racer.goto(-250, 100 - i * 60)    racer.pendown()    racers.append(racer) guess = input("Which colour will win? red, blue, orange or purple: ") winner = Nonewhile winner is None:    for racer in racers:        racer.forward(random.randint(1, 10))        if racer.xcor() >= 200:            winner = racer            break colour = winner.pencolor()judge.penup()judge.goto(0, 170)judge.write("The " + colour + " turtle wins!", align="center", font=("Arial", 20, "bold")) if guess == colour:    print("You guessed right!")else:    print("Better luck next time.") turtle.done()
    Type your guess in the Shell and press Enter.
    Then the race runs, and this time red won. Every race is different!
    Watch out Type the colour exactly as it is written, all in small letters: Blue is not the same as blue.

Test it

Tick each one when it works. If one does not, look back at the step it comes from.

Stretch challenges

Finished early? Try these. Each one has a hint if you get stuck.

  1. Five racers

    Add a green turtle to the race.

    Show a hint

    Add "green" to the list, loop range(5), and space the turtles 50 steps apart instead of 60 so they fit.

  2. Victory spin

    Make the winner grow bigger and spin round to celebrate.

    Show a hint

    winner.shapesize(3) makes it three times bigger. A loop with winner.right(10) 36 times spins it all the way round.

  3. Best of three

    Run three races, put the turtles back at the start each time, and count each colour's wins.

    Show a hint

    Put the race in a for race in range(3): loop. Before each race, penup(), goto(-250, 100 - i * 60) and pendown() each racer. Keep the wins in a list of four numbers, or a dictionary.

    Show one answer
    race.pyPython
    import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) colours = ["red", "blue", "orange", "purple"]racers = [] for i in range(4):    racer = turtle.Turtle()    racer.shape("turtle")    racer.color(colours[i])    racer.penup()    racer.goto(-250, 100 - i * 60)    racer.pendown()    racers.append(racer) wins = [0, 0, 0, 0] for race in range(3):    for i in range(4):        racers[i].penup()        racers[i].goto(-250, 100 - i * 60)        racers[i].pendown()    winner = None    while winner is None:        for racer in racers:            racer.forward(random.randint(1, 10))            if racer.xcor() >= 200:                winner = racer                break    wins[racers.index(winner)] += 1 for i in range(4):    print(colours[i], "won", wins[i], "races") turtle.done()

The finished code

Show the whole program
race.pyPython
import turtleimport random turtle.bgcolor("lightgreen")turtle.title("Turtle Race") # the finish linejudge = turtle.Turtle()judge.hideturtle()judge.speed(0)judge.penup()judge.goto(200, 150)judge.right(90)judge.pendown()judge.pensize(4)judge.forward(300) colours = ["red", "blue", "orange", "purple"]racers = [] for i in range(4):    racer = turtle.Turtle()    racer.shape("turtle")    racer.color(colours[i])    racer.penup()    racer.goto(-250, 100 - i * 60)    racer.pendown()    racers.append(racer) guess = input("Which colour will win? red, blue, orange or purple: ") winner = Nonewhile winner is None:    for racer in racers:        racer.forward(random.randint(1, 10))        if racer.xcor() >= 200:            winner = racer            break colour = winner.pencolor()judge.penup()judge.goto(0, 170)judge.write("The " + colour + " turtle wins!", align="center", font=("Arial", 20, "bold")) if guess == colour:    print("You guessed right!")else:    print("Better luck next time.") turtle.done()
Notes for the teacher

Timing

  1. 10 minutes: steps 1 to 3.
  2. 20 minutes: steps 4 to 6. The while loop is the big idea of the day; talk it through before they type it.
  3. 15 minutes: steps 7 and 8, then the tests. Run a class race at the end: everyone guesses, then one student runs it on the board.

Mistakes to look out for

  1. random.randint(1, 10) without import random: NameError: name 'random' is not defined.
  2. if racer.xcor() >= 200 with the wrong indent: it must be inside the for loop, under the line that moves the racer.
  3. In Thonny, the race waits until the guess is typed in the Shell. Students sometimes look at the turtle window and think it has frozen.
  4. A guess typed with a capital letter is always wrong. A stretch: guess.lower() turns the answer into small letters.

Going further

Ask: is the race fair? Every turtle has the same chance of each number, but the first turtle in the list gets to hop first in every round, so it wins ties. A good discussion of how the order of code changes results.