Tesseract & friends

Multidimensional turtle

Log in to post a comment.

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

const dimensions = 4 //min=0, max=10, step=1
const size = 25 //min=5, max=40, step=1

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

// The walk function will be called until it returns false.

function size_of_dim(n) {
    if (n < 3) {
        return size;
    }
    if (n == 3) {
        return 0.5 * Math.sqrt(2) * size;
    }
    else {
        return size * (n - 2);
    }
}

function walk(i) {
    turtle.penup();
    draw_dim(turtle, dimensions);
    return false
}

function draw_dim(t, n) {
    if (n == 0) {
        marker(t);
        return [t.position()];
    }
    
    const [x, y] = turtle.position();
    const angle = 360 / Math.pow(2, n);
    
    const s = size_of_dim(n);
    t.seth(angle);
    t.forward(s/2);
    const a = draw_dim(t, n - 1);
    t.seth(angle)
    t.backward(s);
    const b = draw_dim(t, n - 1);
    t.goto(x, y);
    
    for (var i = 0; i < a.length; i++) {
        turtle.jump(...a[i]);
        turtle.pendown();
        turtle.goto(...b[i]);
        turtle.penup();
    }
    t.goto(x, y);
    return [...a, ...b];
}

function marker() {
    turtle.penup();
    turtle.forward(1);
    turtle.right(90);
    turtle.pendown();
    turtle.circle(1);
    turtle.penup();
    turtle.left(90);
    turtle.backward(1);
}