Recursive triangles

Level 0 figure is 30-60-90 triangle.
Level n+1 figure has Level n figure on the two short sides.

Log in to post a comment.

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

// Global code will be evaluated once.
const turtle = new Turtle();
turtle.penup();
turtle.goto(-50,50);
turtle.pendown();

function triangle(l, depth) {
    const start_pos = turtle.position();
    const start_heading = turtle.heading();
    turtle.left(60);
    const first_pos = turtle.position();
    const first_heading = turtle.heading();
    turtle.forward(l/2);
    turtle.right(90);
    const second_pos = turtle.position();
    const second_heading = turtle.heading();
    turtle.forward(l/2*Math.sqrt(3));
    turtle.right(180-30);
    turtle.forward(l);
    const last_pos = turtle.position();
    const last_heading = turtle.heading();
    if (depth < 13) {
        move_and_turn(first_pos, first_heading);
        triangle(l/2, depth+1);
        move_and_turn(second_pos, second_heading);
        triangle(l/2 * Math.sqrt(3), depth+1);
        move_and_turn(last_pos, last_heading);
    }
}

function move_and_turn(position, heading) {
    turtle.penup();
    turtle.setx(position[0]);
    turtle.sety(position[1]);
    turtle.setheading(heading);
    turtle.pendown();
}


// The walk function will be called until it returns false.
function walk(i) {
    triangle(70, 0);
    return false;
}