/* The Koch Fractal is made up of a series of lines that we'll keep expanding to create the recursive fractal image. The ArrayList technique should be familiar at this point from working with Particle Systems. */ class KochFractal { /* The fractal will keep track of it's start and end points */ private Point start; private Point end; // The ArrayList to hold all of the fractal lines private ArrayList lines; // Keep track of how many times we've recursed over the fractal int depth; public KochFractal() { // Set default values for the fractal start = new Point(0, height - 20); end = new Point(width, height - 20); lines = new ArrayList(); restart(); } public KochFractal(Point s_, Point e_) { // Create the fractal based upon the parameters start = s_.copy(); end = e_.copy(); lines = new ArrayList(); restart(); } public void restart() { // the recursion depth is 0 depth = 0; // clear the array of lines lines.clear(); // add the first line lines.add(new KochLine(start, end)); } public int getDepth() { return depth; } public int getLineCount() { return lines.size(); } public void simulate() { render(); update(); } public void update() { // call the fractal recursion lines = iterate(lines); // keep track of how many iterations we've done depth++; } public void render() { // All we need to do is draw each line for (int i = 0; i < lines.size(); i++) { KochLine l = (KochLine)lines.get(i); l.render(); } } /* This is where the fractal really happens. By following a few basic steps we'll generate a recursive fractal each time we call update() 1. Create an empty ArrayList to store the new lines we'll generate 2. For each line in our current list we generate four new lines using the methods from KochLine 3. Store each of our new lines in the temporary arraylist 4. Return this new arraylist when we're done */ private ArrayList iterate(ArrayList source) { ArrayList fractal = new ArrayList(); for (int i = 0; i < source.size(); i++) { KochLine l = (KochLine)source.get(i); // Get the five points from our line using the KochLine methods Point pStart = l.getStart(); Point pLeft = l.getLeft(); Point pMiddle = l.getMiddle(); Point pRight = l.getRight(); Point pEnd = l.getEnd(); // create four new lines from these points fractal.add(new KochLine(pStart, pLeft)); fractal.add(new KochLine(pLeft, pMiddle)); fractal.add(new KochLine(pMiddle, pRight)); fractal.add(new KochLine(pRight, pEnd)); } return fractal; } }