![Creating a racing simulation game using Python's Turtle graphics](https://thepythonassignmenthelp.com/uploads/blog/2023-11-20-09-49-29rh4j02u8v3.png)
- 20th Nov 2023
- 20:19 pm
import turtle
import random
# Set up the screen
screen = turtle.Screen()
screen.title("Python Racing Simulation")
screen.bgcolor("lightgray")
screen.setup(width=600, height=400)
# Create racetrack border
border = turtle.Turtle()
border.penup()
border.speed(0)
border.goto(-250, 180)
border.pendown()
border.color("black")
border.goto(-250, -180)
border.goto(250, -180)
border.goto(250, 180)
border.goto(-250, 180)
border.hideturtle()
# Create racers
class Racer(turtle.Turtle):
def __init__(self, color, y):
super().__init__(shape="turtle")
self.color(color)
self.penup()
self.goto(-230, y)
# Initialize racers
racers = []
colors = ["red", "blue", "green", "yellow", "purple"]
start_y = 120
for color in colors:
racer = Racer(color, start_y)
racers.append(racer)
start_y -= 50
# Racing function
def race():
while True:
for racer in racers:
distance = random.randint(1, 10)
racer.forward(distance)
if racer.xcor() >= 230:
winner = colors[racers.index(racer)]
print(f"The {winner} turtle wins!")
return
# Start the race
race()
turtle.done()
This code sets up a simple racetrack using Turtle graphics and creates multiple turtles (racers) of different colors. The race()
function makes each turtle move forward by a random distance until one of them reaches the finish line (x-coordinate of 230). When a turtle reaches the finish line, the program announces the winner in the console.
About The Author - Shaoni Gupta
Seasoned programmer with 6 years of experience in designing, developing, and deploying software solutions. Strong problem-solving skills coupled with the ability to collaborate effectively in multidisciplinary teams. Continuously learning and adapting to new technologies and methodologies to drive innovation and deliver high-quality, user-centric solutions.