递归彩虹色的圆圈彼此相邻

问题描述 投票:0回答:1

我正在尝试更改屏幕上显示的颜色和圆圈数量。到目前为止,我已经想出如何以递归模式制作所有不同的颜色,但我需要帮助找出如何添加更多颜色。附件是我所拥有的与我需要达到的目标。

我的代码

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个回答
1
投票

import colorsys但从不使用它 - 这是一个线索,你应该根据角度而不是固定的颜色列表生成颜色。导入的原因是乌龟基于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()

enter image description here

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

中心圆不是正确的颜色。修复这个问题很简单,就是在初次调用draw_recursive_circles()之前设置龟的标题

© www.soinside.com 2019 - 2024. All rights reserved.