Code

p5.js

L-System

Advanced Lindenmayer system with rule X → F+[[X]-X]-F[-FX]+X. String rewriting produces recursive fractal plant geometry; turtle graphics (push/pop matrix stack) renders it. Wikipedia

const rules = {
  X: 'F+[[X]-X]-F[-FX]+X',
  F: 'FF',
};

// Expand axiom N times
function generate(s) {
  return s.split('').map(c => rules[c] ?? c).join('');
}

// Turtle interpretation
for (const c of sentence) {
  if (c === 'F') {
    // draw forward
    p.line(cx, cy, nx, ny);
    cx = nx; cy = ny;
  } else if (c === '+') angle += delta;
  else if (c === '-') angle -= delta;
  else if (c === '[') stack.push({ x:cx, y:cy, angle });
  else if (c === ']') {
    const s = stack.pop();
    cx = s.x; cy = s.y; angle = s.angle;
  }
}