Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to color one size elements the same color in Python Turtle?

I just did a code that draws a a circle, then draws 6 more circles in it, then draws 6 more circles in every circle... et cetera.

image

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)

There is a task to color every one size element the same color (for example, radius 5 circles must be colored red, radius 15 circles must be colored pink...).

I tried adding a variable that gets random value and makes the turtle's pen color based on that value, but as expected that didn't gave me needed result.

image

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)

The parameters used in this example are x = 0; y = 0; r = 50. Everything is drawn like that:

krug(xxx,yyy,rad) # 0 0 50
turtle.up(); turtle.goto(xxx,yyy-rad*3); turtle.down()
turtle.circle(rad*3)

Any idea how could that be done? Thanks!

like image 882
Alex Sokolov Avatar asked May 14 '26 04:05

Alex Sokolov


1 Answers

You need to treat your color information similar to your radius information, adjust it on each recursion.

My answer is similar to @mozway's but using a simple list instead of an int indexed dict for the colors plus setting, and unsetting the color around the loop instead inside of setting it inside the loop:

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()

enter image description here

like image 91
cdlane Avatar answered May 15 '26 18:05

cdlane