xxxxxxxxxx
136
//referenced rules//
// in the next generation the variables X and F will become the following rule that is mapped to a string//
let rules = {
"X": "F+[[Y]-X]-F[-FX]+X",
"Y": "-[XX]+",
"F": "FF"
}
//length of each line//
let len = 1;
// angle of rotation//
let ang= 25;
let drawRules;
//start point. axiom//
let word = "X";
let mybutton;
let myinput;
let myrule;
//setup for the screen and background.(full screen) //
function setup() {
createCanvas(windowWidth/2, windowHeight/1.5);
//user input//
myinput = createInput("");
myrule = createInput("");
mybutton = createButton("Generate");
mybutton.mouseClicked(drawFractal);
//draw the following rule for each character we encounter//
drawRules = {
"F": () => {
//brown colour//
stroke(100, 50, 0);
//start position 0,0 and upwards 0 on the x and negative length on the y, which means upward direction //
line(0, 0, 0, -len);
//continue from where we stopped//
translate(0, -len);
},
// 180 convert from degrees and radians//
"+": () => {
rotate(PI/180 * -ang);
},
"-": () => {
rotate(PI/180 * ang);
},
//pushes all the information into a save state//
"[": push,
//restore back to save point //
"]": () => {
//addind leaves and filling them with green colour//
noStroke();
fill(0, 100, 0);
//size of the leave//
ellipse(0, 0, 2 * len, 5 * len)
//adding flowers//
noStroke(255, 255, 255);
fill (255, 50, 255);
circle (0,0, len*2);
pop();
},
}
//to stop the drawing because the image will only change every time we click the mouse. only call the draw function once//
//noLoop();
}
function draw() {
background(220);
push();
// moving the starting point to the button of the screen, having the width/4, which is the initial quarter of the screen, and draw upward from the starting point//
translate(width/4, height);
//bending of the growth //
rotate(PI/180 * ang);
//execute the drawing function that corresponds that character//
for(let i = 0; i < word.length; i ++) {
let c = word[i];
if(c in drawRules) {
drawRules[c]();
}
}
pop();
}
// Clicking on the generate button & makes function grow//
function drawFractal() {
// Read the users values
ruleName = myinput.value()[0]; // Only use a single character for the rule name
myinput.value(ruleName); // Re-set the value to only use a single character
ruleValue = myrule.value();
// Set the rule into the rules
// NOTE: This can override existing rules!
// You could add a check to make sure you're only adding new rules,
// which would look something like this:
// if(!rules[ruleName]) { //put the line below in here! }
rules[ruleName] = ruleValue;
word = generate();
draw();
}
//function that generates the next generation of functions.Here is where the loop happens//
function generate() {
let next = ""
for(let i = 0; i < word.length; i ++) {
let c = word[i];
if(c in rules) {
next += rules[c];
} else {
next += c;
}
}
return next;
}