一风多龟

2024-05-21 05:34:08 发布

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

我想做两个以上的海龟当我运行模块。 所以我在turtle上声明了两个变量,但我只能看到一个turtle。 我的代码怎么了?你知道吗

import turtle
t1=turtle.Turtle()
t2=turtle.Turtle()

colors = ["red", "blue", "green"]
turtle.bgcolor("yellow")
t1.speed(3)
t1.width(5)
length1 = 10
t2.speed(3)
t2.width(5)
length2 = 10

while length1 < 500:
    t1.fd(length1)
    t1.pencolor(colors[length1%3])
    t1.right (89)
    length1 += 3 #length1 = length1 + 3

while length2 < 500:
    t2.fd(length2)
    t2.pencolor(pink)
    t2.left (89)
    length2 += 4 #length2 = length2 + 4

input()

Tags: 模块声明widthspeedt1海龟colorsturtle
2条回答

你的乌龟一只一只地移动。第一个while循环使用t1执行任务,完成后,第二个while将处理t2。就像“t1,迈出第一步。然后,t1,做第二个。(重复这个过程直到length1不再小于500。)现在t1完成了,所以t2,迈出第一步。t2,你的第二步。(而且还在继续。)”

相反,你希望他们轮流走每一步。就像“t1,迈出第一步。然后,t2,做你的第一个。t1,迈出第二步。t2,轮到你迈出第二步了。(而且还在继续。)”

所以你的while循环应该是这样的:

t1.pencolor(colors[length1 % 3])
t2.pencolor("pink")

while length1 < 500 or length2 < 500:
    if length1 < 500:
        t1.fd(length1)
        t1.right(89)
        length1 += 3  # length1 = length1 + 3
    if length2 < 500:
        t2.fd(length2)
        t2.left(89)
        length2 += 4  # length2 = length2 + 4

(注意,不必每次移动海龟时都设置铅笔颜色。)

there's only one turtle I can see

是真的只有一只乌龟,还是你已经没有耐心等待第一只乌龟在第二只乌龟开始之前完成(由于没有加引号的“粉色”而中断)?如果这是想看到两个海龟同时行动,就像大家总结的那样,我的方法是:

除了使用线程之外,我还使用生成器让这两个turtle以一种类似于coroutine的方式运行。好处是海龟可以共享完全相同的代码,如果他们愿意的话,或者他们可以使用完全不同的代码。但它避免了在同一while循环中重复代码或保持不相关的代码:

from turtle import Screen, Turtle

screen = Screen()
screen.bgcolor("yellow")

t1 = Turtle()
t1.pencolor('blue')

t2 = Turtle()
t2.pencolor('pink')

def pattern(turtle, increment, angle):
    turtle.speed('fast')
    turtle.width(5)
    length = 10

    while length < 500:
        turtle.forward(length)
        turtle.right(angle)
        length += increment
        yield 0

generator1 = pattern(t1, 3, 89)
generator2 = pattern(t2, 4, -89)

while next(generator1, 1) + next(generator2, 1) < 2:
    pass

screen.exitonclick()

相关问题 更多 >