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.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)
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.
| Symbol | Action |
|---|---|
| F | draw forward |
| f | move 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 |
| C | Change color |
New variables can be added with a call to the addvars function.
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.
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).
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.
self.addAxiom('x')
self.addRule('x','y[+y][--y]y')
self.addRule('y','x[++x][-x]x')




