Fourth Python Project: Turtle Racing Game

Requirements:


1. At the start, the user is prompted to place a bet on which turtle will win by entering the turtle's color.
2. The turtles are represented in rainbow colors.
3. When the race begins, all the turtles are aligned at the starting position and 

    race towards the right edge of the screen.
4. Once a turtle crosses the finish line, the user is informed whether they won or 

    lost the bet and which turtle was the winner.

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_position = [-70, -40, -10, 20, 50, 80]
all_turtles = []

for turtle_index in range(0 ,6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[turtle_index])
    new_turtle.penup()
    new_turtle.goto(x=-230, y=y_position[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:
                turtle.write(f"You've won! The {winning_color} turtle is the winner!", align="right", font=("Arial", 12, "normal"))
            else:
                turtle.write(f"You've lost! The {winning_color} turtle is the winner!", align="right", font=("Arial", 12, "normal"))
                
        random_distance = random.randint(0,10)
        turtle.forward(random_distance)

screen.exitonclick()

 

 

Issue:

In my initial code

while is_race_on:   
    for turtle in all_turtles:
        random_speed = random.randint(0,10)
        turtle.speed = random_speed
        turtle.forward(10)

I assigned a random speed to each turtle object and had them race.

However, this caused an issue where the turtle's speed was fixed at the moment of creation. 

As a result, there was no possibility of a comeback during the race; the turtle that started fast would always win.

 

 

To address this issue, instead of using a random speed, I made the turtles move by a random distance each time.

while is_race_on:
    for turtle in all_turtles:
        random_distance = random.randint(0,20)
        turtle.forward(random_distance)


This change allowed the turtles to move by varying distances randomly, 

creating the possibility for slower turtles at the beginning to catch up and overtake others later in the race.