我有一个显示Sierpinski Triangle的java程序。每次单击小程序中的三角形时,它都会为每个三角形添加一个三角形。有没有办法可以绕过mouseDown
方法,只需硬编码三角形就可以显示我想要的任何迭代次数。让我们说我希望三角形显示图像,好像我点击了5次。我该怎么做?
public class SierpinskiTriangle extends Applet {
//private static final long serialVersionUID = 1L;
Graphics g;
int deep = 0;
public void paint() {
setBackground(new Color(255,255,255));
}
public boolean mouseDown(Event ev, int x, int y) {
if (!ev.metaDown()) deep += 1;
else if (deep>0) deep -= 1;
repaint();
return true;
}
public void paint(Graphics g) {
// Create triangle
int px[] = {20, 400, 210};
int py[] = {400, 400, 20};
g.setColor(Color.black);
g.fillPolygon(px, py, 3);
for(int i = 0; i < 5; i++)
{
paintTriangle(g, new Point(20,400),new Point(400,400),new Point(210,20), deep);
i++;
}
}
public void paintTriangle(Graphics g, Point a, Point b, Point c, int lvl) {
Point a1,b1,c1, a2,b2,c2, a3,b3,c3;
if (lvl==0) return;
lvl = 3;
// In the given triangle, amended to include an upside-down triangle
int px[] = {c.x, (c.x+b.x)/2, (a.x+c.x)/2};
int py[] = {b.y, (c.y+a.y)/2, (c.y+a.y)/2};
g.setColor(Color.white);
g.fillPolygon(px, py, 3);
g.setColor(Color.red);
g.drawPolygon(px, py, 3);
// 3 new triangles
a1 = a;
b1 = new Point(c.x, b.y);
c1 = new Point((a.x+c.x)/2, (c.y+a.y)/2);
paintTriangle(g, a1, b1, c1, lvl);
a2 = new Point(c.x, b.y);
b2 = b;
c2 = new Point((c.x+b.x)/2, (c.y+a.y)/2);
paintTriangle(g, a2, b2, c2, lvl);
a3 = new Point((a.x+c.x)/2, (c.y+a.y)/2);
b3 = new Point((c.x+b.x)/2, (c.y+a.y)/2);
c3 = c;
paintTriangle(g, a3, b3, c3, lvl);
}
}