''' This program draws squares to the screen recursively using a decreasing size Author: acase@cs.nyu.edu ''' import turtle import random WINDOW_WIDTH = 600 WINDOW_HEIGHT = 420 TURTLE_SPEED = "fastest" # Space between iterations SPACING = 10 def draw_square(sides=4, size=100): ''' Draws a square with each side legth equal to size ''' # Base case, when to stop drawing if sides <= 0: return # do the drawing turtle.forward(size) turtle.left(90) # Recursive call approaching the base case sides = sides-1 draw_square(sides, size) # Draw square iteratively #for side in range(sides): # turtle.forward(size) # turtle.left(90) def draw_iter_squares(size): ''' Draws shrinking squares iteratively ''' for i in range(10): (x,y) = turtle.pos() turtle.setpos(x+5, y+5) draw_square(4, size) size -= 10 def draw_rec_squares(size): ''' Draws shrinking squares recursively ''' #base case: if (size <= 0): return # Recursive case: # Draw a single square draw_square(4,size) # approach the base case size = size-SPACING # re-position (x,y) = turtle.pos() turtle.setpos(x+SPACING/2, y+SPACING/2) # recursive call draw_rec_squares(size) def draw_quads(size): ''' Draws 4 squares inside of square (recursively) ''' # Base case: if (size <= 0): return # Draw a square draw_square(size=size) # Recursive Case: draw all 4 inner squares using # this same function, just update the position and # size. size = (size - 3*SPACING)/2 (x,y) = turtle.pos() x1 = x + SPACING y1 = y + SPACING turtle.pu() turtle.setpos(x1,y1) turtle.pd() draw_quads(size) # TODO: Set new position #draw_quads(size) # TODO: Set new position #draw_quads(size) # TODO: Set new position #draw_quads(size) def main(): ''' Main program driver, sets up the GUI and starts drawing ''' # Turtle init turtle.speed(TURTLE_SPEED) turtle.setup(WINDOW_WIDTH, WINDOW_HEIGHT) turtle.title("Recursive Graphics") # Draw some squares using various methods turtle.pd() #draw_square() #draw_iter_squares(START_SIZE) #draw_rec_squares(START_SIZE) draw_quads(START_SIZE) turtle.mainloop() # Run the program main()