# CS111 Lab 7 Recursion in turtleworld # Task 2 from turtle import * # This version (added 10/19/14) does not contain any for loops def boxes(size, shrinkFactor, minsize, color): print ('boxes(',str(size),',',str(shrinkFactor),',',str(minsize),',',str(color),')') pencolor(color) count = 0 length = 0 if size > minsize: print ('size > minsize, drawing smaller box') # draw smaller boxes # the largest box is drawn implicitly # as the turtle moves around to draw the smaller corner boxes count += 1 # add one to the value in count length += size*4 # for the four sides of the box shortlen = size*shrinkFactor # draw the lower left box littleboxes, miles = boxes(shortlen,shrinkFactor,minsize,color) count += littleboxes length += miles fd(size) lt(90) # draw the lower right box littleboxes, miles = boxes(shortlen,shrinkFactor,minsize,color) count += littleboxes length += miles fd(size) lt(90) # draw the upper right box littleboxes, miles = boxes(shortlen,shrinkFactor,minsize,color) count += littleboxes length += miles fd(size) lt(90) # draw the upper left box littleboxes, miles = boxes(shortlen,shrinkFactor,minsize,color) count += littleboxes length += miles # return to the starting location (lower left corner, facing East) # maintaining the position and heading invariant fd(size) lt(90) return count,length # return two values # This version contains a for loop which repeats the four recursive calls def boxes(size, shrinkFactor, minsize, color): print ('boxes(',str(size),',',str(shrinkFactor),',',str(minsize),',',str(color),')') pencolor(color) count = 0 length = 0 if size > minsize: print ('size > minsize, drawing smaller box') # draw smaller boxes # the largest box is drawn implicitly # as the turtle moves around to draw the smaller corner boxes count += 1 # add one to the value in count length += size*4 # for the four sides of the box shortlen = size*shrinkFactor # Although a for loop is used here, you could also # write the code out and repeat the block below 4 times for box in range(4): littleboxes, miles = boxes(shortlen,shrinkFactor,minsize,color) count += littleboxes length += miles fd(size) lt(90) return count,length # return two values # initialize turtle on canvas before drawing def initialize_turtle(): setup(800,600) # Create a turtle window reset() # Show turtle window and turtle shape("turtle") # Make turtle shape a turtle (as opposed to arrow) #Turtle starts roughly in center of canvas # Put turtle in bottom left cornerish pu() setx(-200) sety(-200) pd() def run(): initialize_turtle() count, len = boxes(400,0.4,100,'magenta') print ('count = ', str(count),' length = ', str(len))