本文介绍了如何同时在python中运行两只乌龟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让两只海龟一起移动,而不是一个接一个移动.例如:

I'm trying to make two turtles move together instead of one moving subsequently after the other. For example:

a = turtle.Turtle()
b = turtle.Turtle()

a.forward(100)
b.forward(100)

但这只会让他们一个接一个地移动.有没有办法让它们同时移动?

But this only makes them move one after the other.Is there a way to make them move together simultaneously?

推荐答案

我们希望做的最好的事情就是让它们看起来同时移动.下面是解决这个问题的三种日益复杂的方法.但首先,让我们建立我们的基线代码,两只海龟互相朝向并在它们在原点相遇时停止:

The best we can hope to do is make them appear to move simultaneously. Below are three increasingly complex approaches to this problem. But first, let's establish our baseline code, two turtles heading at each other and stopping when they meet at the origin:

from turtle import Screen, Turtle

screen = Screen()

a = Turtle('square', visible=False)
a.speed('slow')
a.color('red')
a.penup()
a.setx(-300)
a.setheading(0)
a.pendown()
a.showturtle()

b = Turtle('circle', visible=False)
b.speed('slow')
b.color('green')
b.penup()
b.setx(300)
b.setheading(180)
b.pendown()
b.showturtle()

### Subsequent variations start here ###

a.forward(300)
b.forward(300)

### Subsequent variations end here ###

screen.mainloop()

当一只乌龟移动然后另一只乌龟移动时,上面的内容没有做我们想要的.对于我们的第一个变体,我们只是将运动分成更小的单位并交替进行:

The above doesn't do what we want as one turtle moves and then the other. For our first variation, we simply chop up the motion into smaller units and alternate:

###

for _ in range(300):
    a.forward(1)
    b.forward(1)

###

我们的下一个变体使用定时器事件来控制两只海龟的运动:

Our next variation uses timer events to control the motion of the two turtles:

###

def move(turtle):
    turtle.forward(1)

    if turtle.distance(0, 0) > 1 :
        screen.ontimer(lambda t=turtle: move(t), 50)

move(a)
move(b)

###

我们的最终变体使用线程来独立控制两只海龟.每个海龟都是一个线程,还有第三个主线程处理海龟线程的所有图形操作.这是必要的,因为乌龟在 tkinter 上运行,它在处理来自辅助线程的图形时存在问题:

Our final variation uses threading to independently control the two turtles. Each turtle is a thread and there's a third, main thread that handles all the graphics operations for the turtle threads. This is needed as turtle operates atop tkinter which has issues handling graphics from secondary threads:

###

from threading import Thread, active_count
from queue import Queue

QUEUE_SIZE = 1

def process_queue():
    while not actions.empty():
        action, *arguments = actions.get()
        action(*arguments)

    if active_count() > 1:
        screen.ontimer(process_queue, 100)

actions = Queue(QUEUE_SIZE)  # a thread-safe data structure

def move(turtle):
    while turtle.distance(0, 0) > 1:
        actions.put((turtle.forward, 1))

Thread(target=move, args=[a], daemon=True).start()
Thread(target=move, args=[b], daemon=True).start()

process_queue()

###

这篇关于如何同时在python中运行两只乌龟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 15:28