mirror of
https://github.com/processing/processing4.git
synced 2026-02-18 04:45:37 +01:00
66 lines
1.6 KiB
Plaintext
66 lines
1.6 KiB
Plaintext
// The Nature of Code
|
|
// Daniel Shiffman
|
|
// http://natureofcode.com
|
|
|
|
/* LSystem Class */
|
|
|
|
// An LSystem has a starting sentence
|
|
// An a ruleset
|
|
// Each generation recursively replaces characteres in the sentence
|
|
// Based on the rulset
|
|
|
|
class LSystem {
|
|
|
|
String sentence; // The sentence (a String)
|
|
Rule[] ruleset; // The ruleset (an array of Rule objects)
|
|
int generation; // Keeping track of the generation #
|
|
|
|
// Construct an LSystem with a startin sentence and a ruleset
|
|
LSystem(String axiom, Rule[] r) {
|
|
sentence = axiom;
|
|
ruleset = r;
|
|
generation = 0;
|
|
}
|
|
|
|
// Generate the next generation
|
|
void generate() {
|
|
// An empty StringBuffer that we will fill
|
|
StringBuffer nextgen = new StringBuffer();
|
|
// For every character in the sentence
|
|
for (int i = 0; i < sentence.length(); i++) {
|
|
// What is the character
|
|
char curr = sentence.charAt(i);
|
|
// We will replace it with itself unless it matches one of our rules
|
|
String replace = "" + curr;
|
|
// Check every rule
|
|
for (int j = 0; j < ruleset.length; j++) {
|
|
char a = ruleset[j].getA();
|
|
// if we match the Rule, get the replacement String out of the Rule
|
|
if (a == curr) {
|
|
replace = ruleset[j].getB();
|
|
break;
|
|
}
|
|
}
|
|
// Append replacement String
|
|
nextgen.append(replace);
|
|
}
|
|
// Replace sentence
|
|
sentence = nextgen.toString();
|
|
// Increment generation
|
|
generation++;
|
|
}
|
|
|
|
String getSentence() {
|
|
return sentence;
|
|
}
|
|
|
|
int getGeneration() {
|
|
return generation;
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|