簡體   English   中英

Python Turtles,我在這里做什么錯的?

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

所以...我幾乎是烏龜模塊的初學者,我想同時移動所有烏龜,但是可能是因為它們永遠不會停止移動,所以我不能移動兩個以上,我該怎么辦改善嗎? 這是代碼:(解決問題后,我確實打算制作更多“顏色”)

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()

使用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()

如果增加打開計時器的時間,您的代碼也將起作用。

 wn.ontimer(movgreen, 20)

將為3只海龜工作。 您需要更多時間來放置更多對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM