LSystem lsystem;
void setup(){
size(500, 500);
float d = 1.5;
float delta = 60;
String string = "B";
HashMap<Character, String> rules = new HashMap<Character, String>();
rules.put('A', "B+A+B");
rules.put('B', "A-B-A");
float iniDir = 0;
PVector iniPos = new PVector(-200, 200);
lsystem = new LSystem(d, delta, string, rules, iniDir, iniPos);
}
void draw(){
println("step: " + frameCount);
lsystem.draw();
lsystem.step();
}
class LSystem{
float d;
float delta;
String string;
HashMap<Character, String> rules;
float iniDir;
PVector iniPos;
LSystem(float d, float delta, String string,
HashMap<Character, String> rules,
float iniDir, PVector iniPos){
this.d = d;
this.delta =delta;
this.string = string;
this.rules =rules;
this.iniDir = iniDir;
this.iniPos = iniPos;
}
void step(){
String nextString = "";
for(int i = 0; i < string.length(); i++){
char c = string.charAt(i);
if(rules.containsKey(c)){
nextString += rules.get(c);
} else {
nextString += c;
}
}
string = nextString;
}
void draw(){
background(0);
stroke(255);
translate(width / 2, height / 2);
translate(iniPos.x, iniPos.y);
rotate(radians(iniDir));
for(int i = 0; i < string.length(); i++){
char c = string.charAt(i);
switch(c){
case 'A':
case 'B':
case 'F':
line(0, 0, d, 0);
translate(d, 0);
break;
case 'X':
case 'Y':
case 'f':
translate(d, 0);
break;
case '+':
rotate(radians(-delta));
break;
case '-':
rotate(radians(delta));
break;
}
}
}
}