l-systems in Python - code

Grab the python code HERE

Python makes implemention easy in a couple of ways. First up is the turtle module. This is a module that gives us standard Turtle commands we can use to draw our figures.

The underlying l-system is just a set of variables and constants, the axiom and a dictionary containing the rules. To allow for Stochastic or randomly applied rules, the rules can be assigned a probability as in:

self.addAxiom('F')
self.addRule('F','F[>.8+F]F[>.8-F]F',33.3)
self.addRule('F','F[>.8+F]F',33.3)
self.addRule('F','F[>.8-F]F',33.4)
S-OL Weed

One of the three rules will be randomly applied to replace F at each step. The result is a fairly random weed (example from The Algorithmic Beauty of Plants, section 1.7)




The other symbols the program understands are defined below.

SymbolAction
Fdraw forward
fmove forward
-turn left
+turn right
@+ length
#- length
>* length
</ length
(- angle
)+ angle
^* angle
_/ angle
/+ width
\- width
W* width
w/ width
|Rotate 180
&negate angle
!swap meaning of + and -
[push state on stack
]pop state from stack
CChange color



New variables can be added with a call to the addvars function.

Lace DOL
self.addVars('A X Y Z')
self.addAxiom('A')
self.addRule('A','+++X--F--ZFX+')
self.addRule('X','---A++F++YFA-')
self.addRule('Y','+ZFX--F--Z+++')
self.addRule('Z','-YFA++F++Y---')



Passing True to the function makes it draw as it moves.

Hiway Dragon
self.addVars('x y',True)
self.addAxiom('Fx')
self.addRule('x','Fx+Fy')
self.addRule('y','Fx-Fy')
self.addRule('F','')



Length, angle and width symbols are followed by a number (decimal points are allowed).

Weed

self.addVar('x')
self.addAxiom('x')
self.addRule('x','F[>.5+++++++++x]-F[>.4-----------!x]>.6x')



The Stack commands '[' and ']' are used for branching. The position, heading, angle, width, length and color are all stored before the '['. Any symbols within the brakets are processed and the settings are restored when the ']' symbol is processed.

TriGrid
self.addVars('x y',True)
self.addAxiom('x')
self.addRule('x','y[+y][--y]y')
self.addRule('y','x[++x][-x]x')





Next >>