【问题标题】:Python - Make One Turtle Object Always Above AnotherPython - 使一个乌龟对象总是在另一个之上
【发布时间】:2016-12-10 03:09:45
【问题描述】:

我想创建一个程序,其中一个 Turtle 对象始终位于所有其他 Turtle 对象之上。我不知道这是否可能,但任何帮助都会受到赞赏。

这是我的代码:

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

【问题讨论】:

  • 切题:我能想到的龟的唯一目的是回忆标志时代。 :D 不是问题

标签: python turtle-graphics


【解决方案1】:

为什么不先画出“底部”乌龟呢?然后为“顶部”乌龟画图?这应该使顶部海龟始终可见。

【讨论】:

  • 这就是我正在做的。不过谢谢。问题是,每当我将“底部”海龟拖到某个地方时,它都会移动到顶部,并覆盖“顶部”海龟。
【解决方案2】:

我观察到的海龟分层规则:

  • 多只海龟移动到同一位置:最后到达的在顶部。

  • 多只海龟画的一样:没有规则!

为了说明我的第二点,请考虑以下代码:

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上方,它会暂时覆盖他,因为它是“最后到达”的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多