Koch Snowflake: Position in Center
in
Programming Questions
•
1 year ago
I am working on a fractal koch snowflake, but I am having trouble getting the image to stay in the middle of the screen. I guess it has something to do with my translate commands, but I can't figure out what's going wrong.
- int generations = 5;
- int sideLen = 400;
- String initiator = "F--F--F";
- String fRule = "F+F--F+F";
- float angle = PI/3;
- void setup()
- {
- size(600, 600);
- background(0);
- stroke(255);
- noLoop();
- }
- void draw()
- {
- // Move to starting position
- int startX = width/2 - (sideLen/2);
- int startY = height/2 + (sideLen/3);
- translate(startX, startY);
- String rules = generateState(initiator, 0);
- // Map string to graphics
- for (int i = 0; i < rules.length(); i++) {
- turtleGraphics(rules.charAt(i));
- }
- }
- // Take the initiator and number of generations and compute final state
- String generateState(String initial, int generations) {
- String state = initial;
- for (int i = 0; i < generations; i++) {
- state = substitue(state, fRule);
- sideLen = sideLen/3;
- }
- return state;
- }
- // Use the replacment rule to create new string
- String substitue(String s, String fRule)
- {
- String newString = "";
- for (int i = 0; i < s.length(); i++) {
- // Replace each instance of F
- if (s.charAt(i) == 'F') {
- newString += fRule;
- } else {
- newString += s.charAt(i);
- }
- }
- return newString;
- }
- // Map the string to turtle graphics commands
- void turtleGraphics(char c)
- {
- switch(c) {
- case 'F':
- line(0, 0, sideLen, 0);
- translate(sideLen, 0);
- break;
- case '+':
- rotate(angle);
- break;
- case '-':
- rotate(-angle);
- break;
- }
- }
1