我刚刚做了一个代码,画一个圆,然后在里面再画 6 个圆,然后在每个圆里再画 6 个圆……等等。
def krug(x,y,r):
if r < 3: return
for n in range(6):
x1 = x + round(2*r*math.cos(n*(3.14/3)))
y1 = y + round(2*r*math.sin(n*(3.14/3)))
turtle.up()
turtle.goto(x1,y1-r)
turtle.down()
turtle.circle(r)
krug(x1,y1,r // 3)
有一项任务是为每个尺寸的元素涂上相同的颜色(例如,半径 5 的圆必须涂成红色,半径 15 的圆必须涂成粉红色……)。
我尝试添加一个获取随机值的变量,并根据该值使乌龟的笔颜色,但正如预期的那样没有给我需要的结果。
def krug(x,y,r):
if r < 3: return
col = random.randint(1,3)
if col == 1: turtle.color('red')
elif col == 2: turtle.color('green')
elif col == 3: turtle.color('blue')
for n in range(6):
x1 = x + round(2*r*math.cos(n*(3.14/3)))
y1 = y + round(2*r*math.sin(n*(3.14/3)))
turtle.up()
turtle.goto(x1,y1-r)
turtle.down()
turtle.circle(r)
krug(x1,y1,r // 3)
知道怎么做吗?谢谢!
你需要像对待半径信息一样对待你的颜色信息,在每次递归时调整它。
我的回答类似于@mozway的,但使用简单的
list
而不是int
索引dict
的颜色加设置,并取消设置循环周围的颜色而不是在循环内部设置它:
import turtle
from math import pi, cos, sin
COLORS = ['red', 'green', 'blue', 'magenta', 'cyan', 'yellow'] # color levels
def krug(x, y, radius, col=0):
if radius < 3:
return
old_color = turtle.pencolor() # save previous color
turtle.pencolor(COLORS[col % len(COLORS)]) # set color for this level
for n in range(6):
x1 = x + radius*2 * cos(n * pi/3)
y1 = y + radius*2 * sin(n * pi/3)
turtle.penup()
turtle.goto(x1, y1 - radius)
turtle.pendown()
turtle.circle(radius)
krug(x1, y1, radius/3, col+1)
turtle.pencolor(old_color) # restore previous color
krug(0, 0, 100)
turtle.done()
你可以在你的函数中使用一个额外的参数来传递递归深度,结合颜色字典:
colors = dict(enumerate(['red', 'green', 'blue']))
def krug(x, y, r, depth=0):
if r < 3: return
for n in range(6):
turtle.color(colors.get(depth, 'black'))
x1 = x + round(2*r*math.cos(n*(math.pi/3)))
y1 = y + round(2*r*math.sin(n*(math.pi/3)))
turtle.up()
turtle.goto(x1,y1-r)
turtle.down()
turtle.circle(r)
krug(x1, y1, r // 3, depth+1)
krug(0, 0, 70)
输出: