Python Turtle Race: Create a Racing Game

I was working on a project where I needed to create an engaging way to teach Python programming to beginners. I found that using the Turtle module to create a racing game was not only fun but also an excellent way to demonstrate core programming concepts.

In this article, I’ll cover how to create a Python Turtle race game from scratch, with different methods and approaches. So let’s dive in!

What is Python Turtle?

Python’s Turtle module is a built-in library that allows us to create graphics by directing a virtual “turtle” around the screen. It’s based on the Logo programming language and is perfect for beginners because it provides immediate visual feedback.

For our racing game, we’ll use multiple turtles that race against each other on a track.

Method 1: Basic Turtle Race Using Random Movement

Let’s start with a simple approach where turtles move randomly toward the finish line.

import turtle
import random
import time

# Set up the screen
screen = turtle.Screen()
screen.title("Turtle Race")
screen.bgcolor("forestgreen")
screen.setup(width=700, height=500)

# Draw the finish line
finish_line = turtle.Turtle()
finish_line.penup()
finish_line.goto(250, 200)
finish_line.pendown()
finish_line.goto(250, -200)
finish_line.hideturtle()

# Create racing turtles
colors = ["red", "blue", "orange", "green", "purple", "yellow"]
y_positions = [100, 50, 0, -50, -100, -150]
all_turtles = []

for index in range(6):
    new_turtle = turtle.Turtle(shape="turtle")
    new_turtle.color(colors[index])
    new_turtle.penup()
    new_turtle.goto(-250, y_positions[index])
    new_turtle.pendown()
    all_turtles.append(new_turtle)

# Start the race
racing = True
while racing:
    for current_turtle in all_turtles:
        # Move each turtle a random distance
        distance = random.randint(1, 5)
        current_turtle.forward(distance)

        # Check if any turtle has reached the finish line
        if current_turtle.xcor() > 250:
            racing = False
            winner_color = current_turtle.color()[0]
            print(f"The {winner_color} turtle is the winner!")

screen.exitonclick()

I executed the above example code and added the screenshot below.

python turtle race

This code creates six turtles of different colors, positions them at the starting line, and moves them randomly until one reaches the finish line.

Read Python Turtle Input

Method 2: Use Classes for More Advanced Racing

For a more structured approach, we can use classes to organize our code better.

import turtle
import random
import time

class RaceTrack:
    def __init__(self, width=700, height=500):
        self.screen = turtle.Screen()
        self.screen.title("Turtle Race")
        self.screen.bgcolor("forestgreen")
        self.screen.setup(width=width, height=height)

        # Draw finish line
        self.finish_line = turtle.Turtle()
        self.finish_line.penup()
        self.finish_line.goto(250, 200)
        self.finish_line.pendown()
        self.finish_line.goto(250, -200)
        self.finish_line.hideturtle()

        # Draw starting line
        self.start_line = turtle.Turtle()
        self.start_line.penup()
        self.start_line.goto(-250, 200)
        self.start_line.pendown()
        self.start_line.goto(-250, -200)
        self.start_line.hideturtle()

    def get_screen(self):
        return self.screen

class RacingTurtle:
    def __init__(self, color, y_position):
        self.turtle = turtle.Turtle(shape="turtle")
        self.turtle.color(color)
        self.turtle.penup()
        self.turtle.goto(-250, y_position)
        self.turtle.pendown()

    def move(self):
        distance = random.randint(1, 5)
        self.turtle.forward(distance)

    def get_position(self):
        return self.turtle.xcor()

    def get_color(self):
        return self.turtle.color()[0]

    def celebrate(self):
        for _ in range(3):
            self.turtle.left(360)

def main():
    # Set up the race track
    track = RaceTrack()
    screen = track.get_screen()

    # Create racing turtles
    colors = ["red", "blue", "orange", "green", "purple", "yellow"]
    y_positions = [100, 50, 0, -50, -100, -150]
    racers = []

    for i in range(len(colors)):
        racers.append(RacingTurtle(colors[i], y_positions[i]))

    # Countdown
    countdown = turtle.Turtle()
    countdown.hideturtle()
    countdown.penup()
    countdown.goto(0, 150)

    for count in ["3", "2", "1", "GO!"]:
        countdown.clear()
        countdown.write(count, align="center", font=("Arial", 24, "bold"))
        time.sleep(1)
    countdown.clear()

    # Race
    racing = True
    while racing:
        for racer in racers:
            racer.move()

            if racer.get_position() >= 250:
                racing = False
                winner = racer
                break

    # Announce winner
    winner.celebrate()
    countdown.goto(0, 150)
    countdown.write(f"The {winner.get_color()} turtle wins!", align="center", font=("Arial", 20, "bold"))

    screen.exitonclick()

if __name__ == "__main__":
    main()

I executed the above example code and added the screenshot below.

turtle race python

This approach uses classes to organize the code better, adds a countdown before the race starts, and has the winning turtle celebrate with a spin.

Check out the Python Turtle Pen

Method 3: Add User Bet for Interactive Racing

To make our game more interactive, let’s add a betting feature where users can pick which turtle they think will win.

import turtle
import random
import time

def set_up_screen():
    screen = turtle.Screen()
    screen.title("Turtle Race")
    screen.bgcolor("forestgreen")
    screen.setup(width=700, height=500)
    return screen

def draw_track():
    # Draw finish line
    finish_line = turtle.Turtle()
    finish_line.speed(0)
    finish_line.penup()
    finish_line.goto(250, 200)
    finish_line.pendown()
    finish_line.goto(250, -200)
    finish_line.hideturtle()

    # Draw lane dividers
    divider = turtle.Turtle()
    divider.speed(0)
    divider.color("white")
    y_positions = [150, 100, 50, 0, -50, -100, -150]

    for y in y_positions:
        divider.penup()
        divider.goto(-300, y)

        for _ in range(30):
            divider.pendown()
            divider.forward(10)
            divider.penup()
            divider.forward(10)

    divider.hideturtle()

def create_turtles():
    colors = ["red", "blue", "orange", "green", "purple", "yellow"]
    y_positions = [125, 75, 25, -25, -75, -125]
    all_turtles = []

    for i in range(len(colors)):
        new_turtle = turtle.Turtle(shape="turtle")
        new_turtle.color(colors[i])
        new_turtle.penup()
        new_turtle.goto(-250, y_positions[i])
        all_turtles.append(new_turtle)

        # Make turtles do a little warm-up
        new_turtle.shapesize(1.5)
        for _ in range(2):
            new_turtle.left(90)
            new_turtle.right(90)

    return all_turtles, colors

def race(all_turtles):
    racing = True

    while racing:
        for current_turtle in all_turtles:
            # Move each turtle a random distance
            distance = random.randint(1, 5)
            current_turtle.forward(distance)

            # Check if any turtle has reached the finish line
            if current_turtle.xcor() > 250:
                racing = False
                winner = current_turtle
                return winner

def main():
    screen = set_up_screen()
    draw_track()
    all_turtles, colors = create_turtles()

    # User betting
    user_bet = ""
    while user_bet not in colors:
        user_bet = screen.textinput("Make your bet", 
                                     "Which turtle will win the race? (red/blue/orange/green/purple/yellow): ")
        user_bet = user_bet.lower() if user_bet else ""

    # Countdown
    countdown = turtle.Turtle()
    countdown.hideturtle()
    countdown.penup()
    countdown.goto(0, 180)

    for count in ["3", "2", "1", "GO!"]:
        countdown.clear()
        countdown.write(count, align="center", font=("Arial", 24, "bold"))
        time.sleep(0.75)
    countdown.clear()

    # Start the race
    winner = race(all_turtles)
    winner_color = winner.color()[0]

    # Display results
    result = turtle.Turtle()
    result.hideturtle()
    result.penup()
    result.goto(0, 180)

    if winner_color == user_bet:
        result.write(f"You won! The {winner_color} turtle is the winner!", align="center", font=("Arial", 18, "bold"))
    else:
        result.write(f"You lost! The {winner_color} turtle won, not the {user_bet} turtle.", align="center", font=("Arial", 18, "bold"))

    # Winner celebration
    winner.penup()
    winner.goto(0, 0)
    for _ in range(3):
        winner.right(360)

    screen.exitonclick()

if __name__ == "__main__":
    main()

I executed the above example code and added the screenshot below.

turtle race game

This version adds lane dividers for a more realistic racetrack, allows users to bet on a turtle, and provides feedback on whether they won or lost their bet.

Read Python Turtle Grid

Method 4: Create a Multi-Race Tournament

For a more extended gaming experience, let’s create a tournament with multiple races.

import turtle
import random
import time

def setup_tournament():
    screen = turtle.Screen()
    screen.title("Turtle Racing Tournament")
    screen.bgcolor("forestgreen")
    screen.setup(width=800, height=600)

    # Draw race track
    track = turtle.Turtle()
    track.speed(0)
    track.hideturtle()

    # Draw finish line
    track.penup()
    track.goto(300, 250)
    track.pendown()
    track.goto(300, -250)

    # Draw starting line
    track.penup()
    track.goto(-300, 250)
    track.pendown()
    track.goto(-300, -250)

    return screen

def create_scoreboard():
    scoreboard = turtle.Turtle()
    scoreboard.hideturtle()
    scoreboard.penup()
    scoreboard.goto(0, 260)
    return scoreboard

def create_turtles():
    colors = ["red", "blue", "orange", "green", "purple", "yellow"]
    turtles = []
    start_y = 200
    for i in range(len(colors)):
        racer = turtle.Turtle(shape="turtle")
        racer.color(colors[i])
        racer.penup()
        racer.goto(-300, start_y - i * 70)
        turtles.append(racer)
    return turtles

def reset_turtles(turtles):
    start_y = 200
    for i, turtle_ in enumerate(turtles):
        turtle_.goto(-300, start_y - i * 70)

def run_race(turtles):
    winner = None
    while not winner:
        for racer in turtles:
            distance = random.randint(1, 10)
            racer.forward(distance)
            if racer.xcor() >= 300:
                winner = racer.pencolor()
                break
    return winner

def display_scores(scoreboard, scores):
    scoreboard.clear()
    scoreboard.write("Tournament Scores", align="center", font=("Courier", 20, "bold"))
    y_pos = 230
    for turtle_color, score in scores.items():
        scoreboard.goto(0, y_pos)
        scoreboard.write(f"{turtle_color.capitalize()}: {score} wins", align="center", font=("Arial", 16, "normal"))
        y_pos -= 30

def tournament(num_races=5):
    screen = setup_tournament()
    scoreboard = create_scoreboard()
    turtles = create_turtles()
    scores = {t.pencolor(): 0 for t in turtles}

    for race_num in range(1, num_races + 1):
        winner = run_race(turtles)
        scores[winner] += 1
        display_scores(scoreboard, scores)
        time.sleep(2)
        reset_turtles(turtles)

    # Final display
    screen.textinput("Tournament Over", "Press Enter to close the tournament.")
    screen.bye()

# Run the tournament
tournament(num_races=5)

This multi-race turtle tournament showcases how Python’s Turtle module can be used to create fun, interactive games while practicing loops, functions, and object control.

The Python Turtle module makes coding fun and accessible, especially for visual learners. Through building a racing game, you can teach concepts like loops, conditionals, functions, classes, and even basic physics, all while creating something entertaining.

Whether you’re a teacher looking for an engaging classroom project or someone learning Python on your own, I encourage you to try building a turtle race. Start with the basic version and gradually add more features as your coding skills improve.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.