skip to main |skip to sidebar

2007-07-21

递归算法(1) - 科赫曲线

先来看一下效果:

KochCurve

实现代码:

/**
 *科赫曲线
 *@param g Graphics
 *@param p1 起始点
 *@param p2 结束点
 *@param p1 迭代次数
 */
function kochCurve(g:Graphics, p1:Point, p2:Point, n:int):void {
 if(n == 0) {
  g.moveTo(p1.x, p1.y)
  g.lineTo(p2.x, p2.y);
  return;
 }
 var p3:Point, p4:Point, p5:Point;
 //     p4
 //p1   /\   p2
 // ---/  \---
 //   p3  p5
 p3 = Point.interpolate(p2, p1, 1/3);
 p5 = Point.interpolate(p2, p1, 2/3);
 var p1_p3:Point = p3.subtract(p1);
 var angle:Number = Math.atan2(p1_p3.y, p1_p3.x)
 p4 = p3.add(Point.polar(p1_p3.length, angle + 1/3*Math.PI));
 kochCurve(g, p1, p3, n-1);
 kochCurve(g, p3, p4, n-1);
 kochCurve(g, p4, p5, n-1);
 kochCurve(g, p5, p2, n-1);
}

没有评论: