import math;

# let's start with a nice background:
Rectangle(color=['#acf', '#cef', '#fff'])
Circle(x=50, y=100, width=200, height=40, color='#350')

# "tree" is a function -- a reusable piece of code
# In this case it's a _recursive_ function; that is, it calls itself.
# With recursion, it is possible to build complex behavior from a
# relatively simple base.
def tree(x, y, angle, length):
    # calculate the end point with trigonometry:
    end_x = int(x + length * math.cos(angle))
    end_y = int(y + length * math.sin(angle))
    # draw one line:
    Line([(x, y), (end_x, end_y)], color="tan")    
    # we need to stop at some point; only draw further if line length is over 5.
    if length > 5:
        # this call will draw one branch off our line
        tree(end_x, end_y, angle+0.3, length*2/3)
        # and this will draw the other line
        tree(end_x, end_y, angle-0.65, length*2/3)
    if length < 10:
        # we need some green at the top:
        Circle(x=end_x, y=end_y, width=10, height=10, color=["green", "darkgreen"])

# this single function call will draw the whole tree
tree(60, 100, math.radians(270), 30)

Recursion: fractal tree

by snild

Created 5 years, 11 months ago.