2014-01-30

Drawing a "tree burst" iteratively and recursively.


This week in class we examined a program that used turtles (in the Logo turtle graphics sense) to draw a simple fractal pattern we referred to as a tree burst. The goal was to get a better understanding of recursion by engaging it in a visual way. It worked well and I was able to intuitively grasp how the recursion was going to work a little faster than in a previous example using nested list objects.

The program (tree_burst.py) is available from the course website and its visual output is roughly similar to the image below.


After looking at it for a while it struck me that, since each line is drawn by its own turtle and that turtle remains at the end of the line until it's needed in the next level of recursion, it shouldn't be too difficult to get the same result using iteration. I gave it a shot and found that I was right. My iterative solution is somewhat less elegant than the recursive example but still concise enough to post here in full.

tree_burst_iterative.py

import turtle COLORS = ('red', 'green', 'blue') def tree_burst_iterative(level, length, turtle): '''Use copies of turtle to draw a symmetrical ternary tree fractile to the specified level of detail starting with initial lines of specified length. ''' turtle_list = [] turtle_list.append(turtle) for _ in range(level): new_turtles = [] for t in turtle_list: # Turn all existing turtles East and make them red. t.setheading(0) t.color(COLORS[0]) # For each existing turtle create two recolored clones facing NW # and SW respectivly. for i in range(1, 3): new_turtles.append(t.clone()) new_turtles[-1].setheading(120 * i) new_turtles[-1].color(COLORS[i]) # Add new clones to existing turtles and move all turtles forward. turtle_list.extend(new_turtles) for t in turtle_list: t.forward(length) # Halve the length of travel for the next round of moves. length = length / 2 if __name__ == '__main__': t = turtle.Turtle() t.speed('slow') t.color('red') tree_burst_iterative(4, 128, t)

Turtle image CC by jovian_dreams

No comments:

Post a Comment