How To Declare Winner In Python Turtle Race
I'm creating a basic turtle program using the Python module 'turtle'. The only problem I come across is how to declare a winner. I will try to explain my program: I started with ma
Solution 1:
There are a number of ways to do this. Two things you need are the x coordinate of the finish line (200) and the x coordinate of the turtle, turtle.xcor()
. Below is a simple solution where the first turtle whose center of mass is over the finish line turns gold, for victory:
from turtle import Screen, Turtle
from random import randint, choice
track = Turtle(visible=False)
track.speed('fastest')
track.penup()
track.goto(-100, 200)
for step in range(15):
track.write(step, align='center')
track.right(90)
track.forward(10)
track.pendown()
track.forward(160)
track.penup()
track.backward(170)
track.left(90)
track.forward(20)
track.goto(200, 250)
track.write("Finish Line", align='center')
track.pendown()
track.right(90)
track.forward(300)
vince = Turtle('turtle')
vince.speed('fastest')
vince.color('red')
vince.penup()
vince.goto(-120, 160)
vince.pendown()
lawliet = Turtle('turtle')
lawliet.speed('fastest')
lawliet.color('blue')
lawliet.penup()
lawliet.goto(-120, 130)
lawliet.pendown()
boyka = Turtle('turtle')
boyka.speed('fastest')
boyka.color('green')
boyka.penup()
boyka.goto(-120, 100)
boyka.pendown()
screen = Screen()
while True:
turtle = choice([vince, lawliet, boyka])
turtle.forward(randint(1, 5))
if turtle.xcor() > 200:
break
turtle.color('gold')
screen.exitonclick()
Post a Comment for "How To Declare Winner In Python Turtle Race"