Monday, January 25, 2010

Cowabunga!

A while back in my Turtle Power! post I mentioned some fractals that I thought suitable for use teaching beginning programmers. I thought that I would present the code written to generate one of them, specifically the Levy C Curve. The code specifies the fractal as a L-system. Basically you start with a string of symbols then use certain rules recursively expand the string. Each symbol in the string becomes an instruction and the string itself a program for drawing the fractal. The Dragon Curve is generated in the same way. It simply has a slightly different formula.

The structure of an an L-system lends itself to implementation with very basic structures. The code below uses only two non-nested loops and a mulitway branch to do all its work. So I feel that it (and any L-system fractal) make good teaching material for control structures.

The C Curve's formula is this:

Start: "F"
Rules: "F" becomes "+F--F+"
Symbol meanings:
F - draw forward
+ - turn clockwise 45 degrees
- - turn counter-clockwise 45 degrees

And the required python code is:

import turtle 

SEGMENT_LENGTH = 2 
WINDOW_WIDTH = 772 
WINDOW_HEIGHT = 501 

if __name__ == "__main__": 

    move_list = "F" 

    for i in range(15): 
        move_list = move_list.replace("F", "+F--F+") 

    turtle.setup(width=WINDOW_WIDTH, height=WINDOW_HEIGHT) 
    turtle.tracer(False) 
    turtle.up() 
    turtle.goto(-180, -135) 

    turtle.down() 

    for i in move_list: 
        if i == "F": 
            turtle.forward(SEGMENT_LENGTH) 

        elif i == "+": 
            turtle.left(45) 

        else: 
            turtle.right(45) 

    turtle.Tkinter.mainloop()

Which is amazingly short for the complex beauty of the drawing it produces. That code was produced before the last major version number update of python and has not been upgraded. I think it will run with a new python installation but it might not.

Any numbers not mentioned in the curve formula are "Magic" (i.e. I fiddled with them until they produced a good looking picture). The structure should be obvious the first thing I do is produce the "program" to draw the curve using nothing but iteration and sub-string replacement. The rest of the program is the mini interpreter that takes the program and draws the picture. Remember the more times you iterate the string replace the more complex the fractal becomes. So go ahead and play with that a little and see what you think.

No comments:

Post a Comment