java使用Turtle的方法编写一个递归来绘制一个反向的科赫雪花(一个雪花由三份科赫曲线组成,在正三角形的边上尖端向内构建)
时间: 2024-06-10 17:04:02 浏览: 78
好的,下面是Java使用Turtle绘制反向科赫雪花的递归代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class KochSnowflake extends JPanel {
private static final long serialVersionUID = 1L;
private int level = 0;
public KochSnowflake(int level) {
this.level = level;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 背景颜色
g.setColor(Color.WHITE);
Rectangle r = g.getClipBounds();
g.fillRect(0, 0, r.width, r.height);
// 设置画笔颜色和粗细
g.setColor(Color.BLACK);
g.setLineWidth(1);
// 顶点坐标
int x1 = 0, y1 = (int) (Math.sqrt(3) / 2 * r.height);
int x2 = r.width / 2, y2 = 0;
int x3 = r.width, y3 = (int) (Math.sqrt(3) / 2 * r.height);
// 构建三角形
Polygon p = new Polygon(new int[] {x1, x2, x3}, new int[] {y1, y2, y3}, 3);
g.drawPolygon(p);
// 初始的三分科赫曲线
drawKochLine(p.xpoints[0], p.ypoints[0], p.xpoints[1], p.ypoints[1], level, g);
drawKochLine(p.xpoints[1], p.ypoints[1], p.xpoints[2], p.ypoints[2], level, g);
drawKochLine(p.xpoints[2], p.ypoints[2], p.xpoints[0], p.ypoints[0], level, g);
}
/**
* 绘制科赫曲线
*
* @param x1 起点横坐标
* @param y1 起点纵坐标
* @param x2 终点横坐标
* @param y2 终点纵坐标
* @param level 当前绘制的递归层级
* @param g 绘制所使用的画笔
*/
private void drawKochLine(int x1, int y1, int x2, int y2, int level, Graphics g) {
if (level == 0) {
// 到达递归终点
g.drawLine(x1, y1, x2, y2);
return;
}
int deltaX = x2 - x1;
int deltaY = y2 - y1;
// 计算三等分点坐标
int x1_3 = x1 + deltaX / 3, y1_3 = y1 + deltaY / 3;
int x2_3 = x1 + deltaX * 2 / 3, y2_3 = y1 + deltaY * 2 / 3;
int x_control = (int) ((x1 + x2) / 2.0 - Math.sqrt(3) * (y2 - y1) / 6);
int y_control = (int) ((y1 + y2) / 2.0 - Math.sqrt(3) * (x2 - x1) / 6);
// 递归绘制
drawKochLine(x1, y1, x1_3, y1_3, level - 1, g);
drawKochLine(x1_3, y1_3, x_control, y_control, level - 1, g);
drawKochLine(x_control, y_control, x2_3, y2_3, level - 1, g);
drawKochLine(x2_3, y2_3, x2, y2, level - 1, g);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Koch Snowflake");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KochSnowflake panel = new KochSnowflake(5); // 设置递归层数
frame.getContentPane().add(panel);
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
阅读全文