谢宾斯基三角形java
时间: 2023-12-13 10:33:51 浏览: 177
以下是Java语言实现谢尔宾斯基三角形的代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class SierpinskiTriangle extends JFrame {
private static final long serialVersionUID = 1L;
private int depth = 0;
public SierpinskiTriangle(int depth) {
super("Sierpinski Triangle");
setSize(600, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.depth = depth;
}
public void paint(Graphics g) {
super.paint(g);
int x1 = 300, y1 = 50, x2 = 50, y2 = 550, x3 = 550, y3 = 550;
drawSierpinskiTriangle(g, depth, x1, y1, x2, y2, x3, y3);
}
private void drawSierpinskiTriangle(Graphics g, int depth, int x1, int y1, int x2, int y2, int x3, int y3) {
if (depth == 0) {
g.drawLine(x1, y1, x2, y2);
g.drawLine(x2, y2, x3, y3);
g.drawLine(x3, y3, x1, y1);
} else {
int x12 = (x1 + x2) / 2;
int y12 = (y1 + y2) / 2;
int x23 = (x2 + x3) / 2;
int y23 = (y2 + y3) / 2;
int x31 = (x3 + x1) / 2;
int y31 = (y3 + y1) / 2;
drawSierpinskiTriangle(g, depth - 1, x1, y1, x12, y12, x31, y31);
drawSierpinskiTriangle(g, depth - 1, x12, y12, x2, y2, x23, y23);
drawSierpinskiTriangle(g, depth - 1, x31, y31, x23, y23, x3, y3);
}
}
public static void main(String[] args) {
SierpinskiTriangle sierpinskiTriangle = new SierpinskiTriangle(5);
sierpinskiTriangle.getContentPane().setBackground(Color.WHITE);
sierpinskiTriangle.setVisible(true);
}
}
```
这段代码使用Java的Swing库实现了谢尔宾斯基三角形的绘制。在`paint`方法中,定义了三个点的坐标,然后调用`drawSierpinskiTriangle`方法进行绘制。`drawSierpinskiTriangle`方法使用递归的方式进行绘制,每次递归深度减1,直到深度为0时绘制三角形。
阅读全文