Summary

Resources

Notes\ Code

image.png

Time to make our race and give them random movement. We also want to check when the race is won and if the user bet on the right turtle. Here’s how we accomplished this:

from turtle import Turtle, Screen
import random

is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-70, -40, -10, 20, 50, 80]
all_turtles = []

for turtle_index in range(0,6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.penup()
    new_turtle.color(colors[turtle_index])
    new_turtle.goto(x=-230, y=y_positions[turtle_index])
    all_turtles.append(new_turtle)

if user_bet:
    is_race_on = True

while is_race_on:
    for turtle in all_turtles:
        if turtle.xcor() > 230:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print("You win!")
            else:
                print("You lose.")
            print(f"The winning turtle was {winning_color}")

        random_distance = random.randint(0,10)
        turtle.forward(random_distance)

screen.exitonclick()

To get our turtle’s to move we wanted to use a random integer from 0 to 10, and we put this in a variable that set their forward movement.

random_distance = random.randint(0,10)
        turtle.forward(random_distance)

To get all the turtles to move we wrapped this in a for loop but we also needed to modify our turtle code as they didn’t really exist in anything. To do this when we create them we, we now append them to an empty list called all_turtles.

all_turtles = []

for turtle_index in range(0,6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.penup()
    new_turtle.color(colors[turtle_index])
    new_turtle.goto(x=-230, y=y_positions[turtle_index])
    all_turtles.append(new_turtle)

Now we can write our for loop for the turtles in all_turtles to move:

for turtle in all_turtles:
    random_distance = random.randint(0,10)
    turtle.forward(random_distance)