Python turtle and tkinter
Turtle Race
Line up four racing turtles, let random numbers decide who wins, and guess the winner first.
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
whileloop until something happens - Make a decision with
ifandelse
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
Step 1: Start a new file
Click New and save the file as
race.py.import randomgives you Python's random numbers, which you will need later.1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7turtle.done()A green field with an arrow in the middle: the turtle every program starts with. Step 2: Draw the finish line
A turtle called
judgedraws 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.
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18turtle.done()A black finish line on the right. 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.
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18red = turtle.Turtle()19red.shape("turtle")20red.color("red")21red.penup()22red.goto(-250, 100)23red.pendown()24 25turtle.done()A red turtle waits at the start. 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
racerswithappend. Replace the red turtle's lines with the loop.New: lines 18 to 28.
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18colours = ["red", "blue", "orange", "purple"]19racers = []20 21for i in range(4):22 racer = turtle.Turtle()23 racer.shape("turtle")24 racer.color(colours[i])25 racer.penup()26 racer.goto(-250, 100 - i * 60)27 racer.pendown()28 racers.append(racer)29 30turtle.done()Four turtles on their marks, one above the other. 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.
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18colours = ["red", "blue", "orange", "purple"]19racers = []20 21for i in range(4):22 racer = turtle.Turtle()23 racer.shape("turtle")24 racer.color(colours[i])25 racer.penup()26 racer.goto(-250, 100 - i * 60)27 racer.pendown()28 racers.append(racer)29 30for racer in racers:31 racer.forward(random.randint(1, 10))32 33turtle.done()One hop each, all slightly different. Step 6: Race to the finish
A
whileloop repeats for as long as its condition is true.winnerstarts asNone, which means nobody yet. Every turtle hops, and as soon as one reaches x = 200, the finish line, it becomes the winner.breakstops theforloop there, and becausewinneris no longerNone, thewhileloop ends too. Replace the one hop loop with this.New: lines 30 to 36.
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18colours = ["red", "blue", "orange", "purple"]19racers = []20 21for i in range(4):22 racer = turtle.Turtle()23 racer.shape("turtle")24 racer.color(colours[i])25 racer.penup()26 racer.goto(-250, 100 - i * 60)27 racer.pendown()28 racers.append(racer)29 30winner = None31while winner is None:32 for racer in racers:33 racer.forward(random.randint(1, 10))34 if racer.xcor() >= 200:35 winner = racer36 break37 38turtle.done()The race runs until one turtle crosses the line. Step 7: Announce the winner
pencolor()tells you the winner's colour. The judge writes it above the race.New: lines 38 to 42.
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18colours = ["red", "blue", "orange", "purple"]19racers = []20 21for i in range(4):22 racer = turtle.Turtle()23 racer.shape("turtle")24 racer.color(colours[i])25 racer.penup()26 racer.goto(-250, 100 - i * 60)27 racer.pendown()28 racers.append(racer)29 30winner = None31while winner is None:32 for racer in racers:33 racer.forward(random.randint(1, 10))34 if racer.xcor() >= 200:35 winner = racer36 break37 38colour = winner.pencolor()39judge.penup()40judge.goto(0, 170)41judge.write("The " + colour + " turtle wins!", align="center", font=("Arial", 20, "bold"))42 43turtle.done()The judge names the winner at the top. Step 8: Place your bet
Before the race, ask the player to guess.
inputwaits for them to type in the Shell. After the race,ifchecks whether the guess was right, andelsecovers every other case.New: lines 30, 31 and 45 to 49.
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18colours = ["red", "blue", "orange", "purple"]19racers = []20 21for i in range(4):22 racer = turtle.Turtle()23 racer.shape("turtle")24 racer.color(colours[i])25 racer.penup()26 racer.goto(-250, 100 - i * 60)27 racer.pendown()28 racers.append(racer)29 30guess = input("Which colour will win? red, blue, orange or purple: ")31 32winner = None33while winner is None:34 for racer in racers:35 racer.forward(random.randint(1, 10))36 if racer.xcor() >= 200:37 winner = racer38 break39 40colour = winner.pencolor()41judge.penup()42judge.goto(0, 170)43judge.write("The " + colour + " turtle wins!", align="center", font=("Arial", 20, "bold"))44 45if guess == colour:46 print("You guessed right!")47else:48 print("Better luck next time.")49 50turtle.done()NewLoadSaveRunDebugStep overStep intoStep outResumeStoprace.py28 racers.append(racer)29 30guess = input("Which colour will win? red, blue, orange or purple: ")31 32winner = None33while winner is None:34 for racer in racers:35 racer.forward(random.randint(1, 10))36 if racer.xcor() >= 200:37 winner = racer38 break39 40colour = winner.pencolor()41judge.penup()Shell>>> %Run race.pyWhich colour will win? red, blue, orange or purple: redYou guessed right!>>>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:Blueis not the same asblue.
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.
Five racers
Add a green turtle to the race.
Show a hint
Add
"green"to the list, looprange(5), and space the turtles 50 steps apart instead of 60 so they fit.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 withwinner.right(10)36 times spins it all the way round.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)andpendown()each racer. Keep the wins in a list of four numbers, or a dictionary.Show one answer
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18colours = ["red", "blue", "orange", "purple"]19racers = []20 21for i in range(4):22 racer = turtle.Turtle()23 racer.shape("turtle")24 racer.color(colours[i])25 racer.penup()26 racer.goto(-250, 100 - i * 60)27 racer.pendown()28 racers.append(racer)29 30wins = [0, 0, 0, 0]31 32for race in range(3):33 for i in range(4):34 racers[i].penup()35 racers[i].goto(-250, 100 - i * 60)36 racers[i].pendown()37 winner = None38 while winner is None:39 for racer in racers:40 racer.forward(random.randint(1, 10))41 if racer.xcor() >= 200:42 winner = racer43 break44 wins[racers.index(winner)] += 145 46for i in range(4):47 print(colours[i], "won", wins[i], "races")48 49turtle.done()
The finished code
Show the whole program
1import turtle2import random3 4turtle.bgcolor("lightgreen")5turtle.title("Turtle Race")6 7# the finish line8judge = turtle.Turtle()9judge.hideturtle()10judge.speed(0)11judge.penup()12judge.goto(200, 150)13judge.right(90)14judge.pendown()15judge.pensize(4)16judge.forward(300)17 18colours = ["red", "blue", "orange", "purple"]19racers = []20 21for i in range(4):22 racer = turtle.Turtle()23 racer.shape("turtle")24 racer.color(colours[i])25 racer.penup()26 racer.goto(-250, 100 - i * 60)27 racer.pendown()28 racers.append(racer)29 30guess = input("Which colour will win? red, blue, orange or purple: ")31 32winner = None33while winner is None:34 for racer in racers:35 racer.forward(random.randint(1, 10))36 if racer.xcor() >= 200:37 winner = racer38 break39 40colour = winner.pencolor()41judge.penup()42judge.goto(0, 170)43judge.write("The " + colour + " turtle wins!", align="center", font=("Arial", 20, "bold"))44 45if guess == colour:46 print("You guessed right!")47else:48 print("Better luck next time.")49 50turtle.done()Notes for the teacher
Timing
- 10 minutes: steps 1 to 3.
- 20 minutes: steps 4 to 6. The
whileloop is the big idea of the day; talk it through before they type it. - 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
random.randint(1, 10)withoutimport random: NameError: name 'random' is not defined.if racer.xcor() >= 200with the wrong indent: it must be inside theforloop, under the line that moves the racer.- 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.
- 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.