Turtle Race in Python

Python game 17 of 20

Easyโฑ 25 min๐Ÿ“„ 50 lines of Pythonโ˜… 3 challenges๐Ÿข Draws in your browser

The turtle race is the most fun way to meet Python's turtle module: draw a track, line up five coloured turtles, and move each one forward a random distance until somebody crosses the finish line. You pick the winner before the race starts.

Press Play, choose a colour, and the race is drawn right on this page. The same code runs in a window on your own computer.

Play Turtle Race

turtle_race.py ยท real Python in your browser
Press โ–ถ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (50 lines)

How to play

  • Choose red, blue, green, orange or purple.
  • Each turn every turtle moves forward a random 1-10 steps.
  • The first turtle past the finish line wins. Did you pick it?

The complete Turtle Race code

Here is the whole program (50 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.

import random
import turtle

COLORS = ["red", "blue", "green", "orange", "purple"]
FINISH = 200

print("TURTLE RACE  -  who will win?")
bet = input("Pick a colour (red, blue, green, orange, purple): ").strip().lower()
while bet not in COLORS:
    bet = input("Choose one of: " + ", ".join(COLORS) + ": ").strip().lower()

screen = turtle.Screen()
screen.setup(520, 360)
screen.bgcolor("lightgreen")

# draw the finish line
line = turtle.Turtle()
line.hideturtle()
line.speed(0)
line.penup()
line.goto(FINISH, 140)
line.pendown()
line.pensize(4)
line.goto(FINISH, -140)
line.penup()
line.goto(FINISH - 20, 150)
line.write("FINISH", font=("Arial", 12, "bold"))

racers = []
for i, color in enumerate(COLORS):
    t = turtle.Turtle()
    t.shape("turtle")
    t.color(color)
    t.penup()
    t.goto(-220, 100 - i * 50)
    t.pendown()
    racers.append(t)

winner = None
while winner is None:
    for t in racers:
        t.forward(random.randint(1, 10))
        if t.xcor() >= FINISH:
            winner = t
            break

champ = COLORS[racers.index(winner)]
print(f"The {champ} turtle wins!")
print("Your turtle won! Great pick." if champ == bet else f"Your {bet} turtle didn't win this time.")
turtle.done()

How the Turtle Race game works, step by step

01Ask for a bet first

The game reads your colour with input() before drawing anything. A while loop keeps asking until the answer is in the list.

while bet not in COLORS:
    bet = input("Choose one of: ...")

02Draw the track

A hidden turtle draws the finish line: lift the pen with penup(), move with goto(), put it down, draw, and write a label.

line.goto(FINISH, 140)
line.pendown()
line.goto(FINISH, -140)

03Make five racers in a loop

enumerate() gives the index and the colour, and the index spaces the turtles 50 pixels apart. Each new turtle goes into a list so we can move them all later.

for i, color in enumerate(COLORS):
    t = turtle.Turtle()
    t.goto(-220, 100 - i * 50)
    racers.append(t)

04Race until someone finishes

Each lap moves every turtle by random.randint(1, 10). As soon as one's x position reaches the finish we remember it and break.

for t in racers:
    t.forward(random.randint(1, 10))
    if t.xcor() >= FINISH:
        winner = t
        break

What you'll learn

  • Drawing with the turtle module
  • Lists of objects
  • enumerate()
  • random.randint()
  • Loops that stop on a condition

Python concepts in this game:

Turtle Race coding challenges

Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).

1/3

Line them up

Write start_positions(n) that returns a list of n y positions starting at 100 and going down by 50: start_positions(3) is [100, 50, 0].

challenge 1 ยท edit, Run, then Check
Hint

A list comprehension: [100 - i * 50 for i in range(n)].

Show a solution
def start_positions(n):
    return [100 - i * 50 for i in range(n)]

print(start_positions(5))
2/3

Race without graphics

Write race(steps_per_lap, finish). steps_per_lap is a list of laps; each lap lists how far each racer moves. Racers start at 0 and move in order; return the index of the first racer to reach finish or more.

challenge 2 ยท edit, Run, then Check
Hint

Two loops: over laps, then over racers with enumerate(). Return as soon as a position reaches the finish.

Show a solution
def race(steps_per_lap, finish):
    pos = [0] * len(steps_per_lap[0])
    for lap in steps_per_lap:
        for i, step in enumerate(lap):
            pos[i] += step
            if pos[i] >= finish:
                return i
    return None

print(race([[5, 8, 2], [6, 1, 9]], 12))
3/3

Draw a square track

Use turtle to draw a square with sides of 100: repeat 4 times forward(100) then left(90). Then print done. (Press Run to see your drawing.)

challenge 3 ยท edit, Run, then Check
Hint

for side in range(4): then indent t.forward(100) and t.left(90).

Show a solution
import turtle

t = turtle.Turtle()
for side in range(4):
    t.forward(100)
    t.left(90)

print("done")

Make it your own

Once your challenges pass, try one of these upgrades:

  • Let the player bet points and keep a bank across races.
  • Give each turtle a different top speed.
  • Add obstacles that slow turtles down.
  • Show a podium with first, second and third place.

Frequently asked questions

How do you make a turtle race in Python?

Create several turtles with turtle.Turtle(), line them up with goto(), then loop: move each one forward a random distance with random.randint() until one passes the finish line's x position.

Can I run turtle code online?

Yes, on this page. Press Play and the drawing appears below the code. On your computer, turtle opens its own window.

Why does the turtle window close straight away?

Add turtle.done() (or screen.mainloop()) at the end so the window stays open after the race.

More games like this