A random scribble L-system
Log in to post a comment.
// Using base L-System implementation from reinder
// Global code will be evaluated once.
Canvas.setpenopacity(1);
const turtle = new Turtle();
let distance = 1;
let angle = 90;
// l-system
function createLSystem(numIters, axiom) {
let s = axiom;
for (let i=0; i<numIters; i++) {
s = processString(s);
}
return s;
}
function processString(oldStr) {
let newstr = "";
for (let i=0; i<oldStr.length; i++) {
newstr += applyRules(oldStr[i]);
}
return newstr;
}
function applyRules(ch) {
switch (ch) {
case "A": return "B[BA-AB]B";
case "B": return "A*[F+A+AF+BFAF]FB";
default: return ch;
}
}
turtle.setheading(45);
const inst = createLSystem(7, "AB*BA"); // number of iterations and axiom
states = [];
// The walk function will be called until it returns false.
function walk(i) {
const cmd = inst[i];
switch (cmd) {
case "F": turtle.forward(distance);
break;
case "-": turtle.right(angle);
break;
case "+": turtle.left(angle);
break;
case "*": u = (Math.random() * 2.0 - 1.0) * 95;
v = (Math.random() * 2.0 - 1.0) * 95;
turtle.left(Math.random() * Math.PI * 0.5);
if (Math.random() > 0.75)
{
turtle.penup();
turtle.goto(u,v);
turtle.pendown();
}
case "[": states.push({
x: turtle.ycor(),
y: turtle.xcor(),
h: Math.PI - turtle.heading()
});
break;
case "]": const state = states.pop();
turtle.penup();
turtle.goto(state.x, state.y);
turtle.setheading(state.h);
turtle.pendown();
break;
}
return i < inst.length - 1;
}