'''lecture_27_koch_lsystem.py Draw a Koch snowflake using an L-system Oliver W. Layton CS 151: Computational Thinking: Visual Media Fall 2020 ''' 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) if char == '+': turt.left(angle) if 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` ''' newString = '' for char in string: if char == findStr: newString += repStr else: 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 baseStr = 'F++F++F' findStr = 'F' replaceStr = 'F-F++F-F' # Set up distance and angle for Koch snowflake distance = 100 angle = 60 # Apply the L-system replacement rules some number of times (iterations) numIterations = 2 string = baseStr for i in range(numIterations): string = replace(string, findStr, replaceStr) # Draw the L-system drawString(turt, string, distance, angle) print(string) screen.update() screen.exitonclick()