问题
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