简体   繁体   English

Python Turtles,我在这里做什么错的?

[英]Python Turtles , what am i doing wrong here?

So... i'm pretty much a beginner in the turtle module and i want to move all the turtles at the same time, but probably because they never stop moving, i can't move more than two, what can i do to improve that? 所以...我几乎是乌龟模块的初学者,我想同时移动所有乌龟,但是可能是因为它们永远不会停止移动,所以我不能移动两个以上,我该怎么办改善吗? Here's the code: (i do plan to make more "colors" after the problem is solved) 这是代码:(解决问题后,我确实打算制作更多“颜色”)

from turtle import Turtle, Screen
wn = Screen()
wn.bgcolor('black')

speed = 4


def game():

    def red(coordred):

        redg = Turtle()
        redg.hideturtle()
        redg.shape('circle')
        redg.color('red')
        redg.penup()
        redg.shapesize(2.5, 2.5, 2.5)
        redg.setheading(270)
        redg.goto(-280, 320 + coordred * 50)
        redg.showturtle()

        def movred():
            redg.forward(speed)
            wn.ontimer(movred, 1)

        movred()


    def green(coordgreen):
        greeng = Turtle()
        greeng.hideturtle()
        greeng.shape('circle')
        greeng.color('green')
        greeng.penup()
        greeng.shapesize(2.5, 2.5, 2.5)
        greeng.setheading(270)
        greeng.goto(-100, 320 + coordgreen * 50)
        greeng.showturtle()

        def movgreen():
            greeng.forward(speed)
            wn.ontimer(movgreen, 1)

        movgreen()

    red(0)
    green(1)
    green(2)


game()
wn.mainloop()

The typical way of using a while True does work: 使用while True的典型方法确实有效:

from turtle import Turtle, Screen
wn = Screen()
wn.bgcolor('black')
speed = 4

turtles = [('red', 270),
           ('blue', 260),
           ('green', 250),
           ('yellow', 240),
          ]

def game():
    myTurtles = []
    for (color, heading) in turtles:
        t = Turtle()
        t.shape('circle')
        t.color(color)
        t.shapesize(2.5, 2.5, 2.5)
        t.setheading(heading)
        t.showturtle()
        myTurtles.append(t)

    while True:
        for t in myTurtles:
            t.forward(speed)

game()
wn.mainloop()

Your code also will work if you increase the ontimer time. 如果增加打开计时器的时间,您的代码也将起作用。

 wn.ontimer(movgreen, 20)

will work for 3 turtles. 将为3只海龟工作。 You need more time for more objects. 您需要更多时间来放置更多对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM