Python - 让一个海龟对象始终在另一个上方
我想创建一个程序,让一个乌龟对象总是位于其他所有乌龟对象的上方。我不确定这是否可行,但任何帮助都会很感激。
这是我的代码:
from turtle import *
while True:
tri = Turtle()
turtle = Turtle()
tri.pu()
tri.pencolor("white")
tri.color("black")
tri.shape("turtle")
tri.bk(400)
turtle = Turtle()
turtle.pu()
turtle.pencolor("white")
turtle.shape("square")
turtle.color("white")
turtle.pu()
turtle.speed(0)
tri.speed(0)
turtle.shapesize(100,100,00)
setheading(towards(turtle))
while tri.distance(turtle) > 10:
turtle.ondrag(turtle.goto)
tri.setheading(tri.towards(turtle))
tri.fd(5)
clearscreen()
2 个回答
0
我观察到的关于海龟图层的规则:
多个海龟移动到同一个地方:最后到达的在最上面。
多个海龟画同样的东西:没有规则可言!
为了说明我的第二点,看看这段代码:
from turtle import Turtle, Screen
a = Turtle(shape="square")
a.color("red")
a.width(6)
b = Turtle(shape="circle")
b.color("green")
b.width(3)
b.goto(-300, 0)
b.dot()
a.goto(-300, 0)
a.dot()
a.goto(300, 0)
b.goto(300, 0)
screen = Screen()
screen.exitonclick()
运行它,看看结果。在我的系统上,最后一个goto()
会在红色线条上画一条长长的绿色线,但这条绿色线在画完后会立刻消失。把两个dot()
的调用注释掉,再观察一次。现在绿色线会一直留在红色线的上面。接着把dot()
改成stamp()
或者circle(5)
,再观察一下,想想你能得出什么规则……
现在回到你的例子,实际上有很大的问题(你在操作三个海龟,而不是两个!)这是我简化后的版本:
from turtle import Turtle, Screen
tri = Turtle(shape="turtle")
tri.color("black")
tri.pu()
turtle = Turtle(shape="square")
turtle.shapesize(4)
turtle.color("pink")
turtle.pu()
def drag_handler(x, y):
turtle.ondrag(None)
turtle.goto(x, y)
turtle.ondrag(drag_handler)
turtle.ondrag(drag_handler)
tri.bk(400)
while tri.distance(turtle) > 10:
tri.setheading(tri.towards(turtle))
tri.fd(5)
screen = Screen()
screen.mainloop()
你可以通过拖动粉色方块来逗弄tri
,直到tri
追上它。最终,只要方块在tri
追上时没有移动,tri
就会在最上面。如果你把方块拖到tri
上面,它会暂时遮住tri
,因为它是“最后到达的”。
1
为什么不先把“底部”海龟的所有图形都画好呢?然后再画“顶部”海龟的图形?这样一来,顶部的海龟就总是能看得见了。