Barnsley Fern

Barnsley Fern

Log in to post a comment.

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(-1);

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

let point = new Point(0, 100);

// The walk function will be called until it returns false.
function walk(i) {
    let nx = map(
        point.x,
        -2.1820,
        2.6558,
        -90,
        90
    );

    let ny = map(
        point.y,
        0,
        9.9983,
        100,
        -90
    );
    
    draw_cross(nx, ny);
    
    point = get_next_point(point);

    return i < 400000;
}

function draw_cross(x, y) {
   turtle.penup();
    
   turtle.goto(x - 0.01, y - 0.01);
   turtle.pendown();
   turtle.goto(x + 0.01, y + 0.01);
   turtle.penup();
   
   turtle.goto(x + 0.01, y - 0.01,);
   turtle.pendown();
   turtle.goto(x - 0.01, y + 0.01);
   turtle.penup();
}

function map(num, in_min, in_max, out_min, out_max) {
    return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

function get_next_point (point) {
    let chance = Math.random();

    if(chance <= 0.01) {
        return new Point(0, 0.16 * point.y);
    } else if(chance <= 0.86) {
        return new Point(
            0.85 * point.x + 0.04 * point.y,
            -0.04 * point.x + 0.85  * point.y + 1.6
        );
    } else if (chance <= 0.93) {
        return new Point(
            0.2 * point.x - 0.26 * point.y,
            0.23 * point.x + 0.22 * point.y + 1.6
        );
    } else {
        return new Point(
            -0.15 * point.x + 0.28 * point.y,
            0.26 * point.x + 0.24 * point.y + 0.44
        );
    }
}

function Point(x, y){
	this.x = x || 0;
	this.y = y || 0;
}