Set the maximum distance that a turtle can go

泄露秘密 提交于 2021-01-29 10:17:33

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/58302802/set-the-maximum-distance-that-a-turtle-can-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!