I’ve created a sierpinski triangle code. But i want to shade the triangles according to how many triangles the code makes. In my case i only print triangles that are not shaded. I want something similar like this!
http://en.wikipedia.org/wiki/File:Sierpinski_triangle_evolution.svg
Group 2: Kulplex
Student:Henry Dang
What should i do?
import java.applet.*;
import java.awt.*;
public class Sierpinski extends Applet {
/**
*
*/
private static final long serialVersionUID = 1L;
Graphics g;
Point a1,b1,c1, a2,b2,c2, a3,b3,c3;
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.drawPolygon(px, py, 3);
paintTriangle(g, new Point(20,400),new Point(400,400),new Point(210,20), deep);
}
public void paintTriangle(Graphics g, Point a, Point b, Point c, int lvl) {
if (lvl==0) return;
lvl -= 1;
// 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.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);
}
}
Shouldn’t you only use the call to
g.drawPolygon(px, py, 3);when you are at the bottom of your recursive call?The way the code looks to me right now you will always draw the big triangle of the first level, which will obscure the drawing you do of the smaller layers.
What I’m trying to say is that you should only do the call to
g.drawPolygon()if the level is zero, for all lower levels just recurse to produce smaller triangles. This is if you’re trying to draw the black triangles, instead of drawing the white spaces. It’s a bit unclear what you want to accomplish.Edit: Based on your comment what you really want to is to FILL the polygons, am I right? In that case replace
drawPolygonwithfillPolygonand the triangles will be filled in.