如何在Python乌龟竞赛中宣布获胜者

时间:2019-03-02 11:34:42

标签: python turtle-graphics

我正在使用Python模块'turtle'创建一个基本的turtle程序。我遇到的唯一问题是如何宣布获胜者。

我将尝试解释我的程序:我首先制作了一些垂直线和最后的“完成线”。然后我使用了3种形状,并使用randint()将这些海龟向前移动以进行比赛。这是代码:

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))

这是问题所在:我想宣布赢得比赛的形状。但是,当我查看Turtle库时,没有内置函数可以这样做。有什么办法宣布这场比赛的冠军吗?

1 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。您需要做的两件事是终点线(200)的x坐标和乌龟turtle.xcor()的x坐标。以下是一个简单的解决方案,其中第一只重心在终点线上的乌龟就变成了金,以求胜利:

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()