递归彩虹色的圆圈围绕着彼此

2024-03-29 07:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图改变屏幕上显示的圆圈的颜色。到目前为止,我已经知道如何在递归模式中使所有这些颜色都不同,但我需要帮助找出如何添加更多颜色。依附是我所拥有的和我需要实现的。你知道吗

我的代码

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


Tags: import颜色defredfillcolorrecursivecolors
1条回答
网友
1楼 · 发布于 2024-03-29 07:39:55

import colorsys但从不使用它这是一个线索,你应该生成基于角度的颜色,而不是一个固定的颜色列表。导入的原因是基于turtle的RGB的颜色对于我们的需求来说是错误的模型,因此我们需要一个更合适的模型,比如HSV(我们只关心H/色调),并让它将这些值转换为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()之前设置海龟的头部

相关问题 更多 >