// An implementation of an L-system that generates a Koch snowflake. // // This L-system is defined by: // // Alphabet: // F, +, - // Axiom: // F--F--F // Rules of production: // F -> F+F--F+F // // Where "F" is interpretted as drawing forward, and "+" and "-" are interpretted // as rotating clockwise and counterclockwise, respectively. void setup() { size(500, 500); background(0); noStroke(); stroke(255); strokeWeight(20); String axiom = "F--F--F"; // Iteratively apply the production rules. for (int i = 0; i < 5; i++) { axiom = axiom.replace("F", "F+F--F+F"); } translate(width / 2, height / 2); // Zoom out so the entire drawing is visible. scale(.02); drawPath(axiom); } // Accepts a String representing a drawing path, and draws the path according // to the following interpretation of characters within the String: // F: draw a 40 pixel line to the right and move forward by 40 pixels // +: rotate clockwise by PI/3 radians (60 degrees) // -: rotate counterclockwise by PI/3 radians (60 degrees) void drawPath(String path) { for (int i = 0; i < path.length(); i++) { char c = path.charAt(i); if (c == 'F') { line(0, 0, 40, 0); translate(40, 0); } else if (c == '+') { rotate(PI/3); } else { rotate(-PI/3); } } }