'''lecture_28_koch_lsystem.py Draw a Koch snowflake using an L-system Oliver W. Layton CS 151: Computational Thinking: Visual Media Spring 2021 ''' import turtle def drawString(turt, string, dist, angle): '''Have `turt` draw the L-system string, where `turt` moves forward with a distance `dist` and turns at an angle `angle` degrees ''' for char in string: if char == 'F': turt.forward(dist) elif char == '+': turt.left(angle) elif char == '-': turt.right(angle) def replace(string, findStr, repStr): '''Make a new string that applies the L-system replacement rules: Replace each occurence of `findStr` in `string` with `repStr` Returns: --------- The new string with the replacement rules applied to `string` ''' # findStr: 'F' # repStr: 'F-F++F-F' newString = '' for char in string: # first time around, char = 'F' if char == findStr: # findStr is 'F' here # if findStr matches currString newString = newString + repStr else: # otherwise copy over current char to our result as-is newString = newString + char return newString if __name__ == '__main__': # Make a screen, turn off animations so snowflake draws fast screen = turtle.Screen() screen.setup(600, 600) screen.tracer(False) # Make a turtle turt = turtle.Turtle() # Set up L-system rules baseString = 'F++F++F' findString = 'F' replaceString = 'F-F++F-F' # Set up distance and angle for Koch snowflake d = 0.4 theta = 60 # Apply the L-system replacement rules some number of times (iterations) lSysString = baseString # start with initial shape (triangle) nIter = 7 for i in range(nIter): lSysString = replace(lSysString, findString, replaceString) # print('l sys string:', lSysString) print('l sys string (length):', len(lSysString)) # Draw the L-system drawString(turt, lSysString, d, theta) screen.update() screen.exitonclick()