【问题标题】:Set the maximum distance that a turtle can go设置乌龟可以走的最大距离
【发布时间】:2019-10-09 11:08:35
【问题描述】:
我想设置乌龟可以移动的最大距离。使用下面的代码,我希望第一个向前移动距离 x 的海龟停止所有海龟:
for i in range(130):
alex.forward(randint(5,10))
tess.forward(randint(5,10))
tim.forward(randint(5,10))
duck.forward(randint(5,10))
dog.forward(randint(5,10))
【问题讨论】:
标签:
python
python-3.x
turtle-graphics
【解决方案1】:
您只需要比目前更多的基础设施。为了更容易,我们需要处理海龟列表中的各个元素,而不是每个海龟的单独变量。然后我们可以通过以下方式测试乌龟是否已经越过终点线:
any(turtle.xcor() > 300 for turtle in turtles)
这是一个极简的示例实现:
from turtle import Screen, Turtle
from random import randint
COLORS = ["red", "green", "blue", "cyan", "magenta"]
for index, color in enumerate(COLORS):
turtle = Turtle('turtle')
turtle.color(color)
turtle.penup()
turtle.setposition(-300, -60 + index * 30)
screen = Screen()
turtles = screen.turtles()
while True:
for turtle in turtles:
turtle.forward(randint(5, 15))
if any(turtle.xcor() > 300 for turtle in turtles):
break
screen.mainloop()