""" A few functions for drawing recursive structures using turtle graphics. """ # David Kauchak # 11/14/2011 from turtle import * def spiral(length, levels): """ draws a spiral with 'levels' segments recursively, with first segment of length 'length' """ # implicit base case: if levels == 0, do nothing if levels > 0: forward(length) left(30) spiral(0.95 * length, levels-1) # draw rest of spiral def broccoli(x, y, length, angle): """ Draw a recursive broccoli at x, y with starting stem length, length at angle Returns the number of lines drawn to create the broccoli """ # draw a line pu() goto(x,y) pd() setheading(angle) pencolor("green") forward(length) new_x = xcor() new_y = ycor() if length < 10: # put a dot down dot("yellow") return 1 # we only drew one line for the base case else: # recurse three more times c1 = broccoli(new_x, new_y, length * 0.75, angle - 20) c2 = broccoli(new_x, new_y, length * 0.75, angle) c3 = broccoli(new_x, new_y, length * 0.75, angle + 20) # we drew 1 line, then add in the number of lines # drawn by each of the recursive cases return 1 + c1 + c2 + c3 def broccoli_demo(): """ Generate a good looking broccoli""" tracer(False) # turn off animation print broccoli(0, 0, 70, 90) exitonclick() def pyramid(x, y, height, length = 20): """ Draw a recursive pyramid of triangles. Note that this is not very efficient and many of the inner triangles are repeatedly drawn """ if height > 0: # draw another another triangle (left_x, left_y, right_x, right_y) = draw_triangle(x, y, length) # draw another pyramid to the left pyramid(left_x, left_y, height-1, length) # and to the right pyramid(right_x, right_y, height-1, length) def draw_triangle(x, y, length): """ Draw an equilateral triangle with the point up at x, y with side length, length. The function returns the x, y coordinates of the bottom left and bottom right corner. (probably should return all three corners) """ # move to top coordinates pu() goto(x,y) pd() # draw the triangle setheading(240) forward(length) left_x = xcor() left_y = ycor() left(120) forward(length) right_x = xcor() right_y = ycor() left(120) forward(length) return (left_x, left_y, right_x, right_y)