flash on 2011-5-13
package
{
import com.bit101.components.PushButton;
import flash.display.Sprite;
import flash.geom.Point;
public class Main extends Sprite
{
private var angle:Number;
private var pos:Point;
private var stack:Array = [];
private const DATA:Array =
[
{
start:"F",
rules:{F:"F+F-F-F+F"},
length:5,
depth:4,
pos:new Point(0, stage.stageHeight / 1.5),
startAngle:0,
angle:90,
none:[]
},
{
start:"A",
rules:{A:"B-A-B", B:"A+B+A"},
length:5,
depth:6,
pos:new Point(0, stage.stageHeight / 1.5),
startAngle:0,
angle:60,
none:[]
},
{
start:"FX",
rules:{X:"X+YF", Y:"FX-Y"},
length:5,
depth:10,
pos:new Point(stage.stageWidth / 2, stage.stageHeight / 2),
startAngle:0,
angle:90,
none:["X", "Y"]
},
{
start:"X",
rules:{X:"F-[[X]+X]+F[+FX]-X", F:"FF"},
length:2.9,
depth:6,
pos:new Point(stage.stageWidth / 2, stage.stageHeight),
startAngle:-90,
angle:25,
none:["X"]
}
];
public function Main()
{
new PushButton(this, 365, 385, "Koch curve", function():void { draw(0); } );
new PushButton(this, 365, 405, "Sierpinski triangle", function():void { draw(1); } );
new PushButton(this, 365, 425, "Dragon curve", function():void { draw(2); } );
new PushButton(this, 365, 445, "Fractal plant", function():void { draw(3); } );
}
private function draw(index:int):void
{
var data:Object = DATA[index];
var command:String = data.start;
for (var i:int = 0; i < data.depth; i++)
{
command = addCommand(command, data.rules);
}
this.angle = data.startAngle * Math.PI / 180;
pos = data.pos;
graphics.clear();
graphics.lineStyle(2.0);
for (i = 0; i < command.length; i++)
{
switch(command.charAt(i))
{
case "+": rotate(-data.angle); break;
case "-": rotate(data.angle); break;
case "[": stack.push( { angle:angle, pos:pos } ); break;
case "]": var o:Object = stack.pop(); this.angle = o.angle, this.pos = o.pos; break;
default:
if (data.none.indexOf(command.charAt(i)) == -1) go(data.length);
break;
}
}
}
private function addCommand(src:String, rules:Object):String
{
var dest:String = "";
for (var i:int = 0; i < src.length; i++)
{
var pattern:String = rules[src.charAt(i)];
if (pattern) dest += pattern;
else dest += src.charAt(i);
}
return dest;
}
private function go(length:Number):void
{
var dest:Point = new Point();
dest.x = pos.x + Math.cos(angle) * length;
dest.y = pos.y + Math.sin(angle) * length;
graphics.moveTo(pos.x, pos.y);
graphics.lineTo(dest.x, dest.y);
pos = dest;
}
private function rotate(angle:Number):void
{
this.angle += angle * Math.PI / 180;
}
}
}