LSystem Plant
http://en.wikipedia.org/wiki/L-system#Example_8:_Fractal_plant
/**
* Copyright Nek ( http://wonderfl.net/user/Nek )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/cg2X
*/
// forked from Nek's flash on 2009-5-24
// http://en.wikipedia.org/wiki/L-system#Example_8:_Fractal_plant
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.*;
public class LSystem extends Sprite {
private const VARIABLES:String = "XF";
private const CONSTANTS:String = "+-";
private var start:String = "X";
private var rules:Array = [];
private var iterations:int = 6;
private const STEP_LENGTH:Number = 1.5;
private const ANGLE:Number = 25*Math.PI/180;
private var penX:Number = 0;
private var penY:Number = 0;
private var penA:Number = 65*Math.PI/180;
private var _penX:Number;
private var _penY:Number;
private var _penA:Number;
private var canvas:MovieClip;
private var storage:Array = [];
public function LSystem () {
canvas = new MovieClip();
addChild(canvas);
canvas.x = 50;
canvas.y = 450;
canvas.rotation = 180+45;
rules["X"] = "F-[[X]+X]+F[+FX]-X";
rules["F"] = "FF";
canvas.graphics.lineStyle(0,0x82D50F);
addEventListener(Event.ENTER_FRAME, loop);
}
public function loop(e:Event = null):void {
start = start.split("X").join(rules["X"]);
start = start.split("F").join(rules["F"]);
--iterations;
if (iterations == 0) {removeEventListener(Event.ENTER_FRAME, loop);draw();};
}
public function draw():void {
canvas.graphics.moveTo(penX,penY);
var step:String;
while (start.length >0)
{
step = start.substr(0,1);
start = start.substr(1);
drawStep(step);
}
}
public function drawStep(s:String):void {
switch (s) {
case "F": stepF(); break;
case "+": turnL(); break;
case "-": turnR(); break;
case "[": store(); break;
case "]": restore(); break;
case "X": break;
default: return;
}
}
public function stepF():void {
penX = penX+STEP_LENGTH*Math.cos(penA);
penY = penY+STEP_LENGTH*Math.sin(penA);
canvas.graphics.lineTo(penX , penY);
}
public function store():void {
storage.push({x:penX,y:penY,a:penA});
}
public function restore():void {
var c:Object = storage.pop();
penX = c.x;
penY = c.y;
penA = c.a;
canvas.graphics.moveTo(penX,penY);
}
public function turnL():void {
penA += ANGLE;
}
public function turnR():void {
penA -= ANGLE;
}
}
}