Fork: L System

Tweak the axiom and the rules to produce many kinds of L systems, or just play with the sliders to see what you get.

Log in to post a comment.

// Forked from "L System" by imakerobots
// https://turtletoy.net/turtle/861c59a15f

// L-system rules and initial state
axiom = "F";
rules = {"F": "F+G+FF-G+", "G": "-F+GG++G+F--G"};
const iterations = 7;  //min=1 max=7 step=1
const distance = 3;  //min=1 max=5 step=1
const angle =60;  //min=1 max=179 step=1

const xPos = 15;  //min=-100 max=100 step=1
const yPos = 14;  //min=-100 max=100 step=1
 
// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);

// Global code will be evaluated once.
const t = new Turtle();


t.penup();
t.goto(xPos,yPos);
t.pendown();
// Function to generate the L-system string
function generate_lsystem_string(axiom, rules, iterations) {
    current_string = axiom;
    for(i=0;i<iterations;++i ) {
        new_string = "";
        for( j=0;j<current_string.length;++j) {
            symbol = current_string[j];
            new_string += rules[symbol];
        }
        current_string = new_string;
    }
    return current_string;
}

// Function to draw the L-system with turtle graphics
function draw_lsystem(t, lsystem_string) {
    for( i=0;i<lsystem_string.length;++i ) {
        symbol = lsystem_string[i];
        if( symbol == "F" )
            t.forward(distance);
        else if( symbol == "G")
            t.forward(-distance);
        else if( symbol == "+")
            t.right(angle);
        else if( symbol == "-")
            t.left(angle);
    }
}

// Main drawing function
function walk(i) {
    // Generate L-system string
    lsystem_string = generate_lsystem_string(axiom, rules, iterations);

    // Set up turtle
    t.pendown();
    
    // Draw L-system
    draw_lsystem(t, lsystem_string);
    return false;
}