xxxxxxxxxx
// Lindenmayer systems
var thestring = '';
var therules = [];
var numproductions, t, d;
// curves
thestring = 'F-F-F-F'; // the starting string ("axiom")
therules[0] = ['F', 'F-F+F+FF-F-F+F'];
//therules[0] = ['F', 'FF-F-F-F-FF'];
numproductions = 4;
t = 90; // turn amount
d = 5;
var ptr = 0;
var Asnd, Bsnd, Csnd;
// graphics stuff:
// a simple version of Papert's turtle
var x = [];
var y = [];
var a = [];
var lpf = 1; // letters per frame
function preload()
{
Asnd = loadSound('A.mp3');
Bsnd = loadSound('B.mp3');
Csnd = loadSound('C.mp3');
}
function setup() {
createCanvas(windowWidth, windowHeight);
init();
// triple loop:
var outstring = thestring;
for(let i = 0;i<numproductions;i++)
{
outstring = '';
for(let j = 0;j<thestring.length;j++)
{
for(let k = 0;k<therules.length;k++)
{
var ismatch = 0;
if(thestring.charAt(j)==therules[k][0]) // MATCH
{
outstring+=therules[k][1]; // copy of the second half
ismatch=1;
break;
}
}
if(ismatch==0) outstring+=thestring.charAt(j);
}
thestring=outstring;
}
//console.log(thestring);
//frameRate(12);
strokeWeight(1);
}
function draw() {
var c;
for(let i = 0;i<lpf;i++)
{
c = thestring.charAt(ptr);
if(ptr<thestring.length) doTurtle(c);
ptr = ptr+1;
}
}
function init() {
background(255);
x = [];
y = [];
a = [];
x[0] = width/2;
y[0] = height/2;
a[0] = PI*3/2;
}
function doTurtle(k) {
if(k=='c') init();
if(k=='F') // draw forward
{
let x1 = x[x.length-1] + d*cos(a[a.length-1]);
let y1 = y[y.length-1] + d*sin(a[a.length-1]);
line(x[x.length-1], y[y.length-1], x1, y1);
x[x.length-1] = x1;
y[y.length-1] = y1;
Asnd.play();
}
if(k=='+') // turn right
{
a[a.length-1]+=radians(t);
Bsnd.play();
}
if(k=='-') // turn left
{
a[a.length-1]-=radians(t);
Csnd.play();
}
if(k=='[') // start branch
{
x.push(x[x.length-1]);
y.push(y[y.length-1]);
a.push(a[a.length-1]);
}
if(k==']') // end branch
{
x.pop();
y.pop();
a.pop();
}
}