0
import gpdraw.*;
import javax.swing.*;
import java.lang.Math;


public class Koch2 extends JFrame {

SketchPad paper;
DrawingTool pen;

public Koch2() {

    paper = new SketchPad(600, 600);
    pen = new DrawingTool(paper);

}


public void drawKoch(double sL, int level, double length) {

int x = level - 1;
double y = length / 3;

double z = -1.5 * sL;


if (level < 1) {
    pen.up();
    pen.move(z, 0);
    pen.down();
    pen.setDirection(0);
    pen.forward(sL);
}
else {
    pen.up();
    pen.move(z, 0);
    pen.down();
    pen.setDirection(0);
    pen.forward(length / (Math.pow(3, length)));
    pen.setDirection(60);
    pen.forward(length / (Math.pow(3, length)));
    pen.turnRight(120);
    pen.forward(length / (Math.pow(3, length)));
    pen.turnLeft(60);
    pen.forward(length / (Math.pow(3, length)));
    pen.setDirection(60);
    pen.forward(length / (Math.pow(3, length)));
    pen.turnRight(120);
    pen.forward(length / (Math.pow(3, length)));
    pen.turnRight(120);
    pen.forward(length / (Math.pow(3, length)));
    pen.setDirection(60);
    pen.forward(length / (Math.pow(3, length)));
    pen.turnRight(120);
    pen.forward(length / (Math.pow(3, length)));
    pen.turnLeft(60);
    pen.forward(length / (Math.pow(3, length)));
    pen.setDirection(60);
    pen.forward(length / (Math.pow(3, length)));
    pen.turnRight(120);
    pen.forward(length / (Math.pow(3, length)));


    /*pen.setDirection(0);
    pen.forward(length / (Math.pow(3, length)));
    */

    drawKoch((sL), (x) , (y));

}



}

public static void main(String[] args) {

    new Koch2().drawKoch(300, 6, 300);
}
}

这段代码的哪些部分有问题?我试图弄清楚如何生成单个模板曲线,然后重复多次以制作实际曲线。我还不需要制作真正的雪花,可以等到我弄清楚曲线之后。

4

1 回答 1

0

假设pen.forward(length / (Math.pow(3, length)));画一条直线:

科赫曲线的形成是递归的。要绘制 n 级 Koch 曲线,您需要绘制四级 (n-1) 曲线。绘制科赫曲线的伪代码如下:

drawKochCurve (length, level):
    if level = 0:
        drawStraightLine(length)
    else:
        drawKochCurve(length / 3, level - 1)
        turnLeft(60)
        drawKochCurve(length / 3, level - 1)
        turnRight(120)
        drawKochCurve(length / 3, level - 1)
        turnLeft(60)
        drawKochCurve(length / 3, level - 1)

在您的代码中,我看到有一个递归调用。您需要绘制较小的科赫曲线,而不是绘制直线。仅在基本情况下绘制直线。

于 2012-10-03T05:33:19.703 回答