Python-在上移动两个海龟对象

2024-05-16 19:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个程序,其中一个海龟对象移动到用户单击鼠标的位置,另一个海龟对象同时移动。我有第一部分,但我似乎不能让其余的工作。

任何帮助都将不胜感激。

这是我的密码。(第一部分的功劳归于@Cygwinnian)

from turtle import *
turtle = Turtle()
screen = Screen()
screen.onscreenclick(turtle.goto)
turtle.getscreen()._root.mainloop()

turtle2 = Turtle()
while True:
    turtle2.back(100)
    turtle2.forward(200)
    turtle2.back(100)

Tags: 对象用户fromimport程序密码back鼠标
1条回答
网友
1楼 · 发布于 2024-05-16 19:31:55

我决不是Python的turtle模块的专家,但这里有一些代码我认为可以满足您的需要。当第一只乌龟不在时,第二只乌龟会来回移动:

from turtle import *

screen = Screen() # create the screen

turtle = Turtle() # create the first turtle
screen.onscreenclick(turtle.goto) # set up the callback for moving the first turtle

turtle2 = Turtle() # create the second turtle

def move_second(): # the function to move the second turtle
    turtle2.back(100)
    turtle2.forward(200)
    turtle2.back(100)
    screen.ontimer(move_second) # which sets itself up to be called again

screen.ontimer(move_second) # set up the initial call to the callback

screen.mainloop() # start everything running

这段代码创建了一个函数,该函数将第二只乌龟从起始位置来回移动。它使用screenontimer方法来一遍又一遍地调度自己。一个稍微聪明一点的版本可能会检查一个变量,看看它是否应该退出,但我不介意。

这确实能让两只海龟移动,但它们实际上不会同时移动。在任何时刻都只能有一个人在移动。我不确定是否有任何方法可以解决这个问题,除了可能将移动分割成更小的部分(例如让海龟一次交替移动一个像素)。如果您想要更漂亮的图形,可能需要从turtle模块继续!

相关问题 更多 >