// LL 2021

const grid_w = 30; // min=1 max=100 step=1
const grid_h = 40; // min=1 max=100 step=1
const displacement = 6; // min=0 max=100 step=0.1
const steps = 10; // min=1 max=100 step=1
const seed = 0; // min=0 max=100 step=1

const canvas_size = 180;

Canvas.setpenopacity(1);

const turtle = new Turtle();

var lines;

function walk(i) {
    if (i==0) {
        lines = [];
        const grid = [];
        
        for (var y=0; y<=grid_h; y++) {
            for (var x=0; x<=grid_w; x++) {
                const rand_x = (random() - 0.5) * displacement;
                const rand_y = (random() - 0.5) * displacement;
                const xx = -canvas_size/2 + canvas_size * x / grid_w + rand_x;
                const yy = -canvas_size/2 + canvas_size * y / grid_h + rand_y;
                grid.push([xx, yy]);
            }
        }

        for (var y=0; y<grid_h; y++) {
            for (var x=0; x<grid_w; x++) {
                const p1 = grid[(x+0) + (y+0) * (grid_w+1)];
                const p2 = grid[(x+1) + (y+0) * (grid_w+1)];
                const p3 = grid[(x+1) + (y+1) * (grid_w+1)];
                const p4 = grid[(x+0) + (y+1) * (grid_w+1)];
                
                for (var xx=0; xx<steps; xx++) {
                    const p10 = lerp(p1, p2, xx/steps);
                    const p11 = lerp(p4, p3, xx/steps);
                    lines.push([p10, p11]);
                }
                
                for (var yy=0; yy<steps; yy++) {
                    const p10 = lerp(p1, p4, yy/steps);
                    const p11 = lerp(p2, p3, yy/steps);
                    lines.push([p10, p11]);
                }
                
                if (x == grid_w-1) lines.push([p2, p3]);
                if (y == grid_h-1) lines.push([p4, p3]);
            }
        }
    }
    
    if (lines.length > 0) {
        const line = lines.shift();
        
        turtle.jump(line[0]);
        turtle.goto(line[1]);
    }
    
    return lines.length > 0;
}

function lerp(p1, p2, factor) {
    const px = p1[0] + (p2[0] - p1[0]) * factor;
    const py = p1[1] + (p2[1] - p1[1]) * factor;
    return [px, py];
}

// Random with seed
var rng;
function random() { if (rng === undefined) rng = new RNG(seed); return rng.nextFloat(); }
function RNG(t){return new class{constructor(t){this.m=2147483648,this.a=1103515245,this.c=12345,this.state=t||Math.floor(Math.random()*(this.m-1))}nextFloat(){return this.state=(this.a*this.state+this.c)%this.m,this.state/(this.m-1)}}(t)}