gpt4 book ai didi

python - 相互围绕的递归彩虹色圆圈

转载 作者:行者123 更新时间:2023-12-01 08:10:09 25 4
gpt4 key购买 nike

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

我的代码

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

最佳答案

导入 colorsys 但从未使用它 - 这是您应该根据角度而不是固定颜色列表生成颜色的线索。导入的原因是 turtle 基于 RGB 的颜色对于我们的需求来说是错误的模型,因此我们需要一个更合适的模型,例如 HSV (我们只关心关于H/色调),并将这些值转换为RGB

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

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

我故意保持 Nib 以简化我的示例,因此仅显示圆圈的填充部分。将周围的轮廓放回原处,作为练习留给您。

中心圆的颜色不正确。解决这个问题很简单,只需在首次调用 draw_recursive_circles()

之前设置 turtle 的航向即可

关于python - 相互围绕的递归彩虹色圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55310414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com