// CSE 142 Lecture 12 // Random, boolean // Draws shapes like the Sierpinski triangle generated using the chaos game. // If you think this is cool, you may be a computer scientist... // (or a mathematician) import java.awt.*; // for Graphics import java.util.*; // for Random public class Chaos { // The size of the drawing, half the DrawingPanel width and height. public static final int SIZE = 250; // How many points our polygon should have. public static final int POINTS = 3; // When calculating the next point, how much weight the last point should have. public static final double ORIGINAL_WEIGHT = 1; // When calculating the next point, how much weight the point on our polygon should have. public static final double NEW_WEIGHT = 1; // For POINTS, ORIGINAL_WEIGHT, NEW_WEIGHT try: // 3, 1, 1 <-- Sierpinski triangle // 4, 2, 3 // 5, 1, 2 // 5, 3, 5 // 6, 1, 2 // 6, 1, 3 public static void main(String[] args) { DrawingPanel p = new DrawingPanel(SIZE * 2, SIZE * 2); Graphics g = p.getGraphics(); showPolygon(p, g); runChaosGame(p, g); } // Show where the polygon is that we use for the chaos game for 3 seconds. public static void showPolygon(DrawingPanel p, Graphics g) { g.setColor(Color.BLUE); for (int i = 0; i < POINTS; i++) { g.drawLine(findPointX(i), findPointY(i), findPointX(i + 1), findPointY(i + 1)); } p.sleep(3000); g.setColor(Color.WHITE); g.fillRect(0, 0, SIZE * 2, SIZE * 2); } // Run the chaos game for a million steps public static void runChaosGame(DrawingPanel p, Graphics g) { Random r = new Random(); int x = SIZE; int y = SIZE; // Run the chaos game g.setColor(Color.BLACK); for (int i = 0; i < 1000000; i++) { int rand = r.nextInt(POINTS); // x becomes the weighted average of x and the x coordinate of a point on our polygon x = (int)((x * ORIGINAL_WEIGHT + findPointX(rand) * NEW_WEIGHT) / (ORIGINAL_WEIGHT + NEW_WEIGHT)); // y becomes the weighted average of y and the y coordinate of a point on our polygon y = (int)((y * ORIGINAL_WEIGHT + findPointY(rand) * NEW_WEIGHT) / (ORIGINAL_WEIGHT + NEW_WEIGHT)); g.fillRect(x, y, 1, 1); // Uncomment the next line to see the shapes drawn. // p.sleep(1); } } // Among POINTS evenly spaces points on a circle of radius SIZE centered at (SIZE, SIZE), // returns the y location of the nth point. public static int findPointX(int n) { return SIZE + (int)(SIZE * Math.cos((double)n * 2 * Math.PI / POINTS - Math.PI / 2)); } // Among POINTS evenly spaces points on a circle of radius SIZE centered at (SIZE, SIZE), // returns the x location of the nth point. public static int findPointY(int n) { return SIZE + (int)(SIZE * Math.sin((double)n * 2 * Math.PI / POINTS - Math.PI / 2)); } }