Tuesday, 25 February 2014

Dargon Curve Python

The dragon curve fractal can be defined in a Lindenmayer System. The method can be easily acquire in the math websites or in wikipedia. Here is a sample:

  • angle 90°
  • initial string FX
  • string rewriting rules
    • XX+YF+
    • Y ↦ −FXY 

     This can be describe as:
    • start with a base segment
    • replace each segment by 2 segment with a right angle and a rotation of 45 degrees


    Here is a further explanation 
    • + = turn right
    • - = turn left 
    • F = go forward 
    • FX = initial string 
    • X = X+YF+
    • Y = -FX-Y

    In our python we will control the generation through some inputs
    •  length, =  is the distance the turtle function will travel (the drawn line)
    •  angle, = angle of the turtles rotation
    • level, = this is the iteration level
    • first_state = this is the L-systems starting description basically FX
    •  tar1, =character to replace the each iteration
    • tar2,  = character to replace the each iteration
    • replace, = the character/value to replace with
    • replace2 = the character/value to replace with


     Here we start an initial state of FX. Remember we a rule that states that every X in the list is replace with X+YF+. We get F(X+YF+) or FX+YF+. This basically means Move Forward -> Turn Right -> Move Forward -> Turn Right. This creates a corner 

    In the next iteration we replace all Y characters with -FX-Y.
     our first corner was FX+YF++-FX-Y.F+

    Here is a value in 5 level:
    FX+YF++-FX-YF++-FX+YF+--FX-YF++-FX+YF++-FX-YF+--FX+YF+--FX-YF++-FX+YF++-FX-YF++-FX+YF+--FX-YF+--FX+YF++-FX-YF+--FX+YF+--FX-YF+

    Here is a piece of the code :
    # this means all the names in the turtle module will be available to us
    from turtle import *

    # in here we try and state the varaibles which are going to be used for our loops
    def DragonCurve(length, angle, level,first_state, tar1,replace, tar2, replace2):

    constant = first_state

    for count in range(level):
    constant2 = ''
    for char in constant:
    if char == tar1:
    constant2 +=replace
    elif char == tar2:
    constant2 +=replace2
    else:
    constant2 +=char
    constant = constant2


    # this will try and draw our dragon curve based on the value taken from previous loop
    for char in constant:
    if char =='F':
    forward(length)
    elif char == '+':
    right(angle)
    elif char =='-':
    left(angle)
    # this is a turtle command that takes the speed of our drawing
    speed(50)
    hideturtle()
    # this will start up our commands
    DragonCurve(10,90,10,'FX+FX+','X','X+YF','Y','FX-Y')

No comments:

Post a Comment