xxxxxxxxxx
// L-SYSTEMS: https://en.wikipedia.org/wiki/L-system
// takes the turtle we created in the last project and automates the drawing based on a Lindenmayer or L system
// (1) take a look at the L-system implemented here, and see if you can expand upon it to do some automatic, cool, geometric drawing
// hint: google L-systems and you can use non-drawing symbols as symbolic placeholders to create really complex patterns
// TURTLE STUFF:
var xx, yy; // the current position of the turtle
var rightnowanglee = 0; // which way the turtle is pointing
var distancee = 45; // how much the turtle moves with each 'f'
var anglee = 90; // how much the turtle turns with a '-' or '+'
// LINDENMAYER STUFF (L-SYSTEMS)
var stringg = 'A'; // "axiom" or start of the string
var rulee = []; // array for rules
rulee[0] = ['A', 'f+Af-']; // first rule
// rulee[1] = ['B', '']; // second rule
var amountt = 5; // how many iterations of the L-system to pre-compute
var rightnowstringg = 0; // where in the L-system are we drawing right now
function setup()
{
createCanvas(750, 750);
background(255);
noStroke();
frameRate(15);
// start the xx and yy position at the center
xx = 0;
yy = 0;
// COMPUTE THE L-SYSTEM
for(var i = 0; i < amountt; i++) {
stringg = lsystemm(stringg); // do the stuff to make the string
}
}
function draw()
{
// draw the current character in the string:
draww(stringg.charAt(rightnowstringg));
// increment the point for where we're reading the string
// wrap around at the end
rightnowstringg++;
if(rightnowstringg>stringg.length-1) rightnowstringg = 0;
}
// interpret an L-system
function lsystemm(symboll)
{
var blankstringg = ''; // start a blank output string
// go through the string, doing rewriting as we go
// iterate through 'rulee' looking for symbol matches:
for(var i = 0; i < symboll.length; i++) // every symbol in 's'
{
var matchingg = 0; // by default which is no match
for(var j = 0; j < rulee.length; j++) // every rule in 'rulee'
{
if(symboll.charAt(i)==rulee[j][0]) // MATCH!
{
blankstringg+=rulee[j][1]; // write substitution
matchingg = 1; // we have a match, so do not copy over symbol
break; // get out of the for() loop
}
}
// if nothing matches in 'rulee' array, just copy the symbol over
if(matchingg===0) blankstringg+= symboll.charAt(i);
}
return(blankstringg); // send out the modified string
}
// a custom function that draws turtle commands
function draww(keyy)
{
if(keyy=='f') // draw forward
{
// polar to cartesian transformation based on distance and current angle:
var xx1 = xx + distancee*cos(radians(rightnowanglee));
var yy1 = yy + distancee*sin(radians(rightnowanglee));
// update the turtle's position:
xx = xx1;
yy = yy1;
}
else if(keyy=='+')
{
rightnowanglee+=anglee; // turn left
}
else if(keyy=='-')
{
rightnowanglee-=anglee; // turn right
}
fill(random(255)); // interior fill color
ellipse(xx, yy, 90, 90); // circle that chases the mouse
}