''' 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" START_SIZE = 380 # Space between iterations SPACING = 6 def draw_square(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(size) # Draw square iteratively for side in range(4): 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(size) size -= 10 def draw_rec_squares(size): ''' Draws shrinking squares recursively ''' #base case: if (size <= 1): return # Recursive case: # Draw a single square draw_square(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) # Recursive Case: draw all 4 inner squares using # this same function, just update the position and # size. size = (size - 3*SPACING)/2 # Draw first square (x,y) = turtle.pos() x1 = x + SPACING y1 = y + SPACING turtle.pu() turtle.setpos(x1,y1) turtle.pd() draw_quads(size) turtle.pu() turtle.setpos(x,y) # Draw second square (x,y) = turtle.pos() x2 = x + SPACING*2 + size y2 = y + SPACING turtle.pu() turtle.setpos(x2,y2) turtle.pd() draw_quads(size) turtle.pu() turtle.setpos(x,y) # Draw third square (x,y) = turtle.pos() x3 = x + SPACING y3 = y + SPACING*2 + size turtle.pu() turtle.setpos(x3,y3) turtle.pd() draw_quads(size) turtle.pu() turtle.setpos(x,y) # Draw forth square (x,y) = turtle.pos() x4 = x + SPACING*2 + size y4 = y + SPACING*2 + size turtle.pu() turtle.setpos(x4,y4) turtle.pd() draw_quads(size) turtle.pu() turtle.setpos(x,y) 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") turtle.pu() turtle.setpos(-WINDOW_WIDTH/2+20, -WINDOW_HEIGHT/2+20) # 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()