CSC111 FractalTree 2015.py
--D. Thiebaut (talk) 18:08, 19 April 2015 (EDT)
This program requires Zelle's graphics library.
fractalTree.py
# fractalTree.py # D. Thiebaut # Code taken from http://openbookproject.net/thinkcs/python/english3e/recursion.html # and adapted to work with graphics111.py. # # Draws a fractal tree on the graphic window. # from graphics import * import math import time import random # dimensions of the window MAXWIDTH = 800 MAXHEIGHT = 800 # recursive tree-drawing function # def draw_tree(win , # the canvas order, # the level of recursion. Starts positive. theta, # angle of new branch leaving this trunk sz, # size of this branch x, y, # coordinates of base of this branch heading, # angle of direction of this branch color # color ): trunk_ratio = 0.29 # How big is the trunk relative to whole tree? trunk = sz * trunk_ratio # length of trunk # compute x, y of end of the current branch delta_x = trunk * math.cos(heading) delta_y = trunk * math.sin(heading) x2, y2 = x + delta_x, y + delta_y # draw current branch branch = Line( Point( x, y), Point( x2, y2 ) ) branch.setFill( color ) branch.setWidth( 2 ) branch.setOutline( color ) branch.draw( win ) # if this branch has sub-branches, then recurse if order > 0: # make the recursive calls to draw the two subtrees newsz = sz*(1 - trunk_ratio) draw_tree(win, order-1, theta, newsz, x2, y2, heading-theta, color ) draw_tree(win, order-1, theta, newsz, x2, y2, heading+theta, color ) # draw 1 tree in the middle of the screen, shooting straight up. def main(): win = GraphWin("Fractal Tree", MAXWIDTH, MAXHEIGHT ) theta = 0.65 # use 0.02 for tall skinny trees, 0.7 for fat trees draw_tree(win, 9, theta, MAXWIDTH*0.9, MAXWIDTH//2, MAXHEIGHT-50, -math.pi/2, "brown" ) win.getMouse() win.close() main()