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 making some vertical lines and a final "Finish Line". Then I used 3 shapes and with use of randint()
I move these turtles forward to run the race. Here's the code:
from turtle import *
from random import randint
speed(0)
penup()
goto(-100,200)
for step in range(15):
write(step, align='center')
right(90)
forward(10)
pendown()
forward(160)
penup()
backward(170)
left(90)
forward(20)
goto(200,250)
write("Finish Line", align='center')
pendown()
right(90)
forward(300)
vince = Turtle()
vince.color('red')
vince.shape('turtle')
vince.penup()
vince.goto(-120,160)
vince.pendown()
lawliet = Turtle()
lawliet.color('blue')
lawliet.shape('turtle')
lawliet.penup()
lawliet.goto(-120,130)
lawliet.pendown()
boyka = Turtle()
boyka.color('green')
boyka.shape('turtle')
boyka.penup()
boyka.goto(-120,100)
boyka.pendown()
for turn in range(100):
speed(0)
vince.forward(randint(1,5))
lawliet.forward(randint(1,5))
boyka.forward(randint(1, 5))
Here's the problem: I want to declare the shape which won the race. But when I looked in the Turtle library there is no built-in function to do so. Is there any way to declare the winner for this race?
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.