重新运行乌龟程序

问题描述

我制作了一个简单的 python 程序,它使用乌龟模块创建随机生成的螺旋线。我对 python 还是很陌生,我想知道如何在乌龟离中心很远并且螺旋完成后重新启动程序。这是我的代码

import turtle
import random

root = turtle.Screen()
turtle = turtle.Turtle()

colors = ["yellow","gold","orange","red","maroon","violet","magenta","purple","navy","blue","skyblue","cyan","turquoise","lightgreen","green","darkgreen","chocolate","brown","gray","white"]

def spiral():
    endColors = [random.choice(colors),random.choice(colors),random.choice(colors)]
    angle = random.randint(60,300)
    distance = turtle.distance(0,0)
    
    print("Colors used are:",endColors)
    print("The turning angle is: ",angle,"deg")
    print("The distance is: ",distance)

    turtle.speed(0)
    turtle.hideturtle()
    root.bgcolor("black")
    for i in range(2000):
        turtle.forward(i)
        turtle.right(angle)
        turtle.color(endColors[i%3])
    root.mainloop()
spiral()

我曾尝试在 if 语句中使用turtle.distance 函数,但没有奏效。

解决方法

您可以通过使用全局标志变量并安装一个调用函数的乌龟 timer 来实现,该函数通过查看变量定期检查螺旋是否已完成绘制 - 如果是,则重置事情并绘制另一个。在下面的代码中,执行此操作的函数名为 R>rep(df$x,df$y) [1] "a" "c" "c" 。我还在每个完成之后添加了一个短暂的停顿,以使其保持可见足够长的时间以供欣赏。 check_status()

;¬)
,

我的解决方案类似于@martineau 的解决方案,除了我使用 turtle.reset() 而不是 screen.reset() 和更简单的计时逻辑:

from turtle import Screen,Turtle
from random import choice,randint
from itertools import count

COLORS = [
    'yellow','gold','orange','red','maroon','violet','magenta','purple','navy','blue','skyblue','cyan','turquoise','lightgreen','green','darkgreen','chocolate','brown','gray','white'
]

RADIUS = 100

def spiral():
    turtle.hideturtle()
    turtle.speed('fastest')

    triColors = [choice(COLORS),choice(COLORS),choice(COLORS)]
    angle = randint(60,300)

    print("Colors used are:",triColors)
    print("The turning angle is: ",angle,"deg")
    print("The radius is: ",RADIUS)

    for distance in count():  # spiral forever until a specific radius is achieved
        turtle.pencolor(triColors[distance % 3])
        turtle.forward(distance)

        if turtle.distance(0,0) > RADIUS:
            break

        turtle.right(angle)

    turtle.reset()
    screen.ontimer(spiral)

screen = Screen()
screen.bgcolor('black')

turtle = Turtle()

spiral()

screen.mainloop()