科赫曲线和ArrayList技术

2022-07-29  本文已影响0人  大龙10

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
第8章目录

8.4 科赫曲线和ArrayList技术

1、科赫曲线规则

另一个有名的分形图案,它是由瑞典数学家海里格·冯·科赫于1904年提出的,下面列出了它的规则。(它的初始状态和康托尔集一样,都是一条线段。)

它的结果如下:


2、“怪物”曲线

3、对象实现

4、科赫曲线实现

class KochLine {
  PVector a;   线段的起点和终点
  PVector b;

  KochLine(PVector start, PVector end) {
    a = start.get();
    b = end.get();
  }

  void display() {
    stroke(0);
    line(a.x, a.y, b.x, b.y);    在起点和终点之间画一条线段
  }

5、setup()函数

void setup() {
    size(600, 300);
    lines = new ArrayList<KochLine>(); 创建ArrayList对象
    PVector start = new PVector(0, 200); 屏幕的左边
    PVector end = new PVector(width, 200); 屏幕的右边
    lines.add(new KochLine(start, end)); 第一个KochLine对象
}

6、draw()函数

void draw() {
    background(255);
    for (KochLine l : lines) {
        l.display();
    }
}

这就是代码框架,回顾一下到目前为止我们实现了什么。

7、实现科赫规则和递归过程

你还记得生命游戏中细胞自动机的实现吗?

void generate() {
    ArrayList next = new ArrayList<KochLine>();   创建下一代ArrayList对象……
    for (KochLine l : lines) {   ……对当前的每一个线段
        next.add(new KochLine(???, ???));   添加4条新线段(我们必须计算这些新线段的位置)
        next.add(new KochLine(???, ???));
        next.add(new KochLine(???, ???));
        next.add(new KochLine(???, ???));
    }
    lines = next;   现在我们只关心新的ArrayList
}
void generate() {
    ArrayList next = new ArrayList<KochLine>();
    for (KochLine l : lines) {
        PVector a = l.kochA();   KochLine对象有5个函数,每个函数都返回一个根据科赫规则产生
        PVector b = l.kochB();
        PVector c = l.kochC();
        PVector d = l.kochD();
        PVector e = l.kochE();
        next.add(new KochLine(a, b));
        next.add(new KochLine(b, c));
        next.add(new KochLine(c, d));
        next.add(new KochLine(d, e));
    }
    lines = next;
}
PVector kochB() {
    PVector v = PVector.sub(end, start); 从起点到终点的PVector向量
    v.div(3); 将长度缩短为1/3
    v.add(start); 向量加上起点,得到新的点
    return v;
}
PVector kochD() {
    PVector v = PVector.sub(end, start);
    v.mult(2/3.0); 和前面的计算步骤一样,但我们需要移动2/3的长度
    v.add(start);
    return v;
}
PVector kochC() {
    PVector a = start.get(); 从起点开始
    PVector v = PVector.sub(end, start);
    v.div(3); 移动1/3长度到点B
    a.add(v);
    v.rotate(-radians(60)); 将以上向量旋转60度
    a.add(v); 沿着这个向量移动到点C
    return a;
}

8、结果

上一篇 下一篇

猜你喜欢

热点阅读