# David Kauchak # # A few functions for drawing recursive structures # using turtle graphics. from turtle import * def spiral(length, levels): """ draws a spiral with 'levels' segments recursively, with first segment of length 'length' """ if levels == 0: dot() else: forward(length) left(30) spiral(0.95 * length, levels-1) # draw rest of spiral def broccoli(x, y, length, angle): # draw a line pu() goto(x,y) pd() setheading(angle) pencolor("dark green") forward(length) new_x = xcor() new_y = ycor() if length < 10: # put a dot down dot("yellow") else: # recurse three more times broccoli(new_x, new_y, length * 0.75, angle - 20) broccoli(new_x, new_y, length * 0.75, angle) broccoli(new_x, new_y, length * 0.75, angle + 20) def broccoli_demo(): """ Generate a good looking broccoli""" #tracer(False) # turn off animation 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)