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);
}
}
此代码的哪些部分有问题?我试图找出如何生成单个模板曲线,然后重复多次以生成实际曲线。我还不需要制作实际的雪花,可以等到我计算出曲线之后。
答案 0 :(得分:0)
假设pen.forward(length / (Math.pow(3, length)));
画一条直线:
Koch曲线的形成是递归的。要绘制水平n Koch曲线,您需要绘制四条水平(n-1)曲线。绘制Koch曲线的伪代码如下:
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)
在你的代码中,我看到有一个递归调用。您需要绘制较小的Koch曲线,而不是绘制直线。仅在基本情况下绘制直线。