Python - 一次移动两个海龟对象 [英] Python - Move Two Turtle Objects At Once

查看:78
本文介绍了Python - 一次移动两个海龟对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a program where one turtle object moves to where a user clicks their mouse, and a different turtle object moves at the same time. I have the first part, but I can't seem to get the rest to work.

任何帮助将不胜感激.

这是我的代码.(此部分的第一部分归功于@Cygwinnian)

This is my code. (Credit for the first part of this goes to @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)

推荐答案

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

I am by no means an expert at Python's turtle module, but here's some code that I think does what you want. The second turtle will be moving back and forth any time the first turtle is not:

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 方法一遍又一遍地调度自己.一个稍微聪明一点的版本可能会检查一个变量,看看它是否应该退出,但我没有打扰.

This code creates a function that moves the second turtle repeatedly back and forth from its starting position. It uses the ontimer method of the screen to schedule itself over and over. A slightly more clever version might check a variable to see if it is supposed to quit, but I didn't bother.

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

This does make both turtles move, but they don't actually move at the same time. Only one can be moving at any given moment. I'm not sure if there is any way of fixing that, other than perhaps splitting up the moves into smaller pieces (e.g. have the turtles alternate moving one pixel at a time). If you want fancier graphics you probably need to move on from the turtle module!

这篇关于Python - 一次移动两个海龟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆