Public
Edited
Jul 25, 2023
Fork of L-System
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
sketch = function( p ) {
/* consoleHook is needed to ensure that the console hook is executed before this cell.
This is only relevant if you have to control the execution order on a page reload.
When playing around and debugging a notebook this is generally not necessary */
consoleHook;
// adapted from Daniel Shiffman
// variables: A B
// axiom: A
// rules: (A → AB), (B → A)

let button;
let clickCount = 0;
const axiom = "F";
let len = 250;
let angle;
let sentence = axiom;
var rules = [{
a: "F",
b: "FF+[+F-F-F]-[-F+F+F]"
}];

p.setup = () => {
p.createCanvas(p.windowWidth, 800);
p.background(0);
angle = p.radians(25);
p.createP(axiom);
turtle();
button = p.createButton('generate');
button.position(20, p.height-50 - 20);
button.style('width', '100px');
button.style('height','50px');
button.mousePressed(generate);
}

const generate = () => {
clickCount++;
if(clickCount>5) return;
p.strokeWeight(1);
len *= 0.5;
let nextSentence = "";
for (let i = 0; i < sentence.length; i++) {
let current = sentence.charAt(i);
let found = false;
for (let j = 0; j < rules.length; j++) {
if (current == rules[j].a) {
found = true;
nextSentence += rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
sentence = nextSentence;
// p.createP(sentence);
console.log(sentence);
turtle();
}

const turtle = () => {
p.background(51);
p.resetMatrix();
p.translate(p.width / 3, p.height);
p.stroke(255);
for (let i = 0; i < sentence.length; i++) {
let c = p.map(i, sentence.length, 0, 255, 100);
p.strokeWeight(1);
p.stroke(c);
var current = sentence.charAt(i);
if (current == "F") {
p.line(0, 0, 0, -len);
p.translate(0, -len);
} else if (current == "+") {
p.rotate(angle);
} else if (current == "-") {
p.rotate(-angle)
} else if (current == "[") {
p.push();
} else if (current == "]") {
p.pop();
}
}
}
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more