// Forked from "Ulam Spiral 🌀" by Jurgen
// https://turtletoy.net/turtle/1556682e50

const zoom = 8; //min=.2 max=20 step=.1
const continueTo = 840; //min=100 max=2300 step=1
const opacity = .05; //min=.01 max=1 step=.01
const powerOfOneOver = 2; //min=1 max=5 step=.1

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

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

function* step(s, steps = 0) {
    while(++steps) {
        for(let i = 0; i < 2; i++) {
            for(let j = 0; j < steps; j++) yield turtle.forward(s);
            turtle.left(90);
        }
    }
}

const stepIterator = step(zoom);

const grid = [];
turtle.up();
do {
    grid.push(turtle.pos());
    stepIterator.next();
} while(grid[grid.length-1][0] < continueTo)
turtle.down();

// The walk function will be called until it returns false.
function walk(i) {
    turtle.jump(grid[i]);
    const root = i**(1/powerOfOneOver);
    turtle.goto(lerp2(grid[root|0], grid[(root|0)+1], root - (root|0)));
    return i < grid.length - 1;
}

function lerp2(a,b,t) { return [a[0]*(1-t) + b[0]*t, a[1]*(1-t) + b[1]*t]; }