// Program to draw the Sierpinski Triangle fractal to a given depth import java.awt.*; import java.util.*; public class Sierpinski { public static final int PANEL_SIZE = 600; public static void main(String[] args) { // set up DrawingPanel DrawingPanel panel = new DrawingPanel(PANEL_SIZE, PANEL_SIZE); panel.setBackground(Color.CYAN); Graphics g = panel.getGraphics(); // prompt for depth Scanner console = new Scanner(System.in); System.out.print("Depth? "); int depth = console.nextInt(); // calculate triangle height and begin drawing int triHeight = (int)Math.round(Math.sqrt(3.0) * PANEL_SIZE / 2.0); sierpinski(new Point(PANEL_SIZE / 2, PANEL_SIZE - triHeight), new Point(0, PANEL_SIZE), new Point(PANEL_SIZE, PANEL_SIZE), depth, g); } // pre: depth >= 1 // g is a valid Graphics object from a DrawingPanel // // draws a sierpinski triangle to the given depth inside a triangle // with vertices at p1, p2, and p3 public static void sierpinski(Point p1, Point p2, Point p3, int depth, Graphics g) { if (depth == 1) { // base case - draw a triangle drawTriangle(p1, p2, p3, g); } else { // recursive case - calculate the midpoints of the sides and draw // three smaller triangles Point mid12 = midpoint(p1, p2); Point mid23 = midpoint(p2, p3); Point mid31 = midpoint(p3, p1); sierpinski(p1, mid12, mid31, depth - 1, g); sierpinski(mid12, p2, mid23, depth - 1, g); sierpinski(mid31, mid23, p3, depth - 1, g); } } // pre: g is a valid Graphics object from a DrawingPanel // // draws a triangle with vertices at p1, p2, and p3 private static void drawTriangle(Point p1, Point p2, Point p3, Graphics g) { Polygon tri = new Polygon(); tri.addPoint(p1.getX(), p1.getY()); tri.addPoint(p2.getX(), p2.getY()); tri.addPoint(p3.getX(), p3.getY()); g.drawPolygon(tri); } // returns the midpoint of p1 and p2 private static Point midpoint(Point p1, Point p2) { return new Point((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2); } }