'Randomizing colours of each recursion
I have a working fractal H tree here that randomizes the color in terms of the whole tree at once being a randomized color.
However, I wanted to try and get each individual fractal (each recursion) to be a random color. I am not sure how to do this and have tried to find solutions but have come up short.
I am kinda new to some of this stuff so sorry if this is a silly problem
import turtle
import time
import random
SPEED = 10
BG_COLOR = "white"
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
DRAWING_WIDTH = 700
DRAWING_HEIGHT = 700
PEN_WIDTH = 4
TITLE = "Fractal H tree"
FRACTAL_DEPTH = 3
color = [random.randint(0,255), random.randint(0,255), random.randint(0,255)]
def draw_line(tur, pos1, pos2):
# print("Drawing from", pos1, "to", pos2)
tur.penup()
tur.goto(pos1[0], pos1[1])
tur.pendown()
tur.goto(pos2[0], pos2[1])
def recursive_draw(tur, x, y, width, height, count):
time.sleep(0.5)
draw_line(tur, [x + width * 0.25, height // 2 + y],[x + width * 0.75, height // 2 + y],)
draw_line(tur,[x + width * 0.25, (height * 0.5) // 2 + y],[x + width * 0.25, (height * 1.5) // 2 + y],)
draw_line(tur,[x + width * 0.75, (height * 0.5) // 2 + y],[x + width * 0.75, (height * 1.5) // 2 + y],)
if count <= 0:
return
else: # The recursive part
count -= 1
# Top left
recursive_draw(tur, x, y, width // 2, height // 2, count)
# Top right
recursive_draw(tur, x + width // 2, y, width // 2, height // 2, count)
# Bottom left
recursive_draw(tur, x, y + width // 2, width // 2, height // 2, count)
# Bottom right
recursive_draw(tur, x + width // 2, y + width // 2, width // 2, height // 2, count)
if __name__ == "__main__":
# Screen setup
screen = turtle.Screen()
screen.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
screen.title(TITLE)
screen.bgcolor(BG_COLOR)
screen.colormode(255)
# Turtle (pen) setup
tur = turtle.Turtle()
tur.hideturtle()
tur.pencolor(color)
tur.pensize(PEN_WIDTH)
tur.speed(SPEED)
# Initial call to recursive draw function
recursive_draw(tur, - DRAWING_WIDTH / 2, - DRAWING_HEIGHT / 2, DRAWING_WIDTH, DRAWING_HEIGHT, FRACTAL_DEPTH)
turtle.done()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
