本文介绍了设置海龟可以走的最大距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置海龟可以移动的最大距离.使用下面的代码,我希望第一个向前移动距离 x 的海龟停止所有海龟:

I want to set a maximum distance that a turtle can travel. Using the code below, I want the first turtle who moves distance x forward to stop all the turtles:

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

推荐答案

您只需要比目前更多的基础设施.为了更容易,我们需要使用海龟列表的单个元素而不是每个海龟的单个变量.然后我们可以通过执行以下操作来测试乌龟是否已经越过终点线:

You need just a bit more infrastructure than you currently have. To make it easier we'll need to work with individual elements of a list of turtles instead of individual variables for each turtle. Then we can test if a turtle has crossed the finish line by doing:

any(turtle.xcor() > 300 for turtle in turtles)

这是一个极简主义的示例实现:

Here's an minimalist, example implementation:

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

这篇关于设置海龟可以走的最大距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 20:15