I REALLY need help with this java code. I accidentally posted thise ealier but I
ID: 3667298 • Letter: I
Question
I REALLY need help with this java code. I accidentally posted thise ealier but I said the wrong shape. I need to create the "Sierpinski TRIANGLE", using recursion. I need to use the methods fillPolygon(int[] xPoints, int[] yPoint, numberOfPoints) and setColor(Color aColor). My class extends Applet, so use things like Graphics g and stuff instead of JPanel or whatever. I know there's a few examples of this online but I don't really understand them. When you answer, please comment the code so I know what lines of code are doing what, and please don't use fancy methods or a lot of methods that already to all of the work.
Explanation / Answer
public class Sierpinski_triangle { public static final int SIZE = 512; // This is the height/width of DrawingPanel here. public static void main(String[] args) { // This is used to prompt for level at which we want the triangle Scanner console = new Scanner(System.in); System.out.print("What level do you want the triangle to be at? "); int levelone = console.nextInt(); // This is used to initialize drawing panel DrawingPanel p = new DrawingPanel(SIZE, SIZE); p.setBackground(Color.BLUE); Graphics g = p.getGraphics(); // This is used to compute the endpoints of triangle and begin recursion int triangleHeight = (int) Math.round(SIZE * Math.sqrt(6.0) / 4.0); Point l = new Point(0, triangleHeight); Point m = new Point(SIZE / 2, 0); Point n = new Point(SIZE, triangleHeight); drawFigurehere(levelone, g, l, m, n); } //This program is used to draw a Sierpinski fractal to the given level inside the triangle // The vertices vertices are (l, m, n). public static void drawFigurehere(int level, Graphics g, Point l, Point m, Point n) { if (level == 1) { // This is the base case whch includes a simple triangle Polygon p = new Polygon(); p.addPoint(l.x, l.y); p.addPoint(m.x, m.y); p.addPoint(n.x, n.y); g.fillPolygon(p); } else { // This is the recursive case where we split a single triangle split into 3 triangles Point p4 = midpoint(l, m); Point p5 = midpoint(m, n); Point p6 = midpoint(l, n); // we will recurse on 3 triangular areas in order to remove the middle triangle and create a sierpinski triangle drawFigure(level - 1, g, l, p4, p6); drawFigure(level - 1, g, p4, m, p5); drawFigure(level - 1, g, p6, p5, n); } } // returns the midpoint of l and m public static Point midpoint(Point l, Point m) { return new Point((l.x + m.x) / 2, (l.y + m.y) / 2); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.