【问题标题】:Recursive rainbow-colored circles around each other相互环绕的递归彩虹色圆圈
【发布时间】:2019-03-23 03:42:44
【问题描述】:

我正在尝试更改屏幕上显示的圆圈的颜色和#。到目前为止,我已经想出了如何以递归模式使所有这些颜色都变成不同的颜色,但我需要帮助找出如何添加更多颜色。附件是我所拥有的与我需要实现的。

我的代码

import turtle
import colorsys

def draw_circle(x,y,r,color):
    turtle.seth(0)
    turtle.up()
    turtle.goto(x,y-r)
    turtle.down()
    turtle.fillcolor(color)
    turtle.begin_fill()
    turtle.circle(r)
    turtle.end_fill()

def draw_recursive_circles(x,y,r,color,n):
    if n == 0:
        return
    draw_circle(x,y,r,color)
    colors = ['red','orange','yellow','green','blue','purple']
    i = 0
    for angle in range(30,360,60):
        turtle.up()
        turtle.goto(x,y)
        turtle.seth(angle)
        turtle.fd(r*2)
        draw_recursive_circles(turtle.xcor(),turtle.ycor(),r/3,colors[i],n-1)
        i += 1

turtle.tracer(0)
turtle.hideturtle()
turtle.speed(0)
draw_recursive_circles(0,0,100,'red',5)
turtle.update()

What I need to achieve

What I have so far

【问题讨论】:

    标签: python recursion turtle-graphics


    【解决方案1】:

    import colorsys 但从不使用它——这是一个线索,表明你应该根据角度生成颜色,不是一个固定的颜色列表。导入的原因是 turtle 的基于 RGB 的颜色模型不适合我们的需求,所以我们想要一个更合适的模型,比如 HSV(我们只真正关心关于 H/hue),并让它将这些值转换为 RGB

    卫星数量由您的range 调用决定:

    for angle in range(30,360,60):
    

    这幅画应该更像:

    for angle in range(0, 360, 30):
    

    由于有 12 颗卫星,360 / 30 是 12。最后,我们需要进行适当的计算,以便每当我们改变位置或航向时,为了进行递归绘图,我们需要在退出时恢复原始值。下面是我对这个问题的简化示例解决方案:

    from turtle import Screen, Turtle
    from colorsys import hsv_to_rgb
    
    def draw_circle(radius):
        y = turtle.ycor()  # save position & heading
        heading = turtle.heading()
    
        turtle.fillcolor(hsv_to_rgb(heading / 360, 1.0, 1.0))
    
        turtle.sety(y - radius)
        turtle.setheading(0)
    
        turtle.begin_fill()
        turtle.circle(radius)
        turtle.end_fill()
    
        turtle.sety(y)  # restore position & heading
        turtle.setheading(heading)
    
    def draw_recursive_circles(radius, n):
        if n == 0:
            return
    
        draw_circle(radius)
    
        if n > 1:
            heading = turtle.heading()  # save heading
    
            for angle in range(0, 360, 30):
                turtle.setheading(angle)
                turtle.forward(radius * 2)
    
                draw_recursive_circles(radius / 5, n - 1)
    
                turtle.backward(radius * 2)
    
            turtle.setheading(heading)  # restore heading
    
    screen = Screen()
    screen.tracer(False)
    
    turtle = Turtle(visible=False)
    turtle.penup()
    
    draw_recursive_circles(150, 4)
    
    screen.update()
    screen.tracer(True)
    screen.exitonclick()
    

    为了简化我的示例,我特意保持笔直,因此只显示了圆圈的填充部分。放回周围的轮廓我留给你作为练习。

    中心圆圈的颜色不正确。解决这个问题很简单,只需在初始调用 draw_recursive_circles() 之前设置海龟的航向即可

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多