const blackOnWhite = .7 //min=-.7 max=.7 step=1.4 (No, Yes)
const gridSize = 8; //min=5 max=20 step=1
const cellMargin = 0; //min=-30 max=50 step=1
const runs = 200; //min=1 max=4000 step=1
const wallCountThreshold = .5; //min=.25 max=1 step=.01
const drawOffset = .4; //min=0 max=1.5 step=.1
const spawnRmin = 5; //min=1 max=30 step=1
const spawnRfactor = 10; //min=0 max=30 step=1
const spawnCmin = 5; //min=1 max=30 step=1
const spawnCfactor = 50; //min=0 max=100 step=1
const noiseLayers = 5; //min=1 max=10 step=1
const noiseZoomWide = 1000; //min=1 max=1000 step=1
const noiseZoomFine = 1; //min=.01 max=10 step=.01

const noiseZoom = noiseZoomWide * noiseZoomFine;

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

// Global code will be evaluated once.
const turtle = new Turtle();
const grid = (new Grid(gridSize, 0, 200 - cellMargin - cellMargin));

const segments = [];
for(let i = 0; i < gridSize**2 - 1; i++) {
    const row = (i / gridSize) | 0;
    const col = i % gridSize;

    if(row < gridSize - 1)
        segments.push([grid.getCellByCoord(col, row), grid.getCellByCoord(col, row + 1)]);
    if(col < gridSize - 1)
        segments.push([grid.getCellByCoord(col, row), grid.getCellByCoord(col + 1, row)]);
}

const startLength = segments.length;
while(segments.length / startLength > wallCountThreshold) {
    const idx = (Math.random() * segments.length) | 0;
    const exp = (seg) => seg.map(c => !(0 < c.row && c.row < gridSize - 1 && 0 < c.column && c.column < gridSize - 1))
        .reduce((p,c) => p&&c, true)
    if(!exp(segments[idx])) {
        segments.splice(idx, 1);
    }
}

const lines = segments.map(s => [s[0].center, sub2(s[1].center, s[0].center)]);

const firstCell = grid.getCellByIndex(0);
const drawLimits = [firstCell.center, grid.getCellByIndex(gridSize**2-1).center];
const drawLimitOffset = [
    add2(firstCell.center, scale2([firstCell.size, firstCell.size], drawOffset)),
    sub2(grid.getCellByIndex(gridSize**2-1).center, scale2([firstCell.size, firstCell.size], drawOffset))
];

const upd = new UniformPointDistributor(...drawLimits);
const iterator = upd.getPointIterator();

const SimplexLayers = Array.from({length: noiseLayers}).map(i => new Simplex().createNoise2D()).map(i => (x, y) => (i(x, y) + 1) * 2 * Math.PI);

const gridIterator = grid.iterator();

function walk(i) {
    const point = iterator.next().value;
    
    const r = spawnRmin + Math.random() * spawnRfactor;
    const layerIdx = (Math.random() * SimplexLayers.length) | 0;
    const newLines = [];
    Array.from({length: Math.random() * spawnCfactor + spawnCmin})
         .map(i => clamp2(
            [Math.random()**.5].map(rf =>
                add2(point, [Math.random()*2*Math.PI].map(a => scale2([Math.sin(a), Math.cos(a)], r * rf)).pop())
            ).pop(),
            ...drawLimitOffset
         ))
         .forEach(pt => {

            const direction = [SimplexLayers[layerIdx](...pt.map(i => (i+100)/noiseZoom))].map(r => [Math.sin(r), Math.cos(r)]).pop();
        
            const intersections = lines.map(l => intersect_info2(...l, pt, direction)).filter(i => i !== false && 0 <= i[0] && i[0] <= 1);
            const smallestPositive = intersections.filter(i => i[1] >= 0).sort((a, b) => a[1] < b[1]? 1: -1).pop();
            const biggestNegetive = intersections.filter(i => i[1] <= 0).sort((a, b) => a[1] < b[1]? -1: 1).pop();
        
            newLines.push([smallestPositive[2], sub2(biggestNegetive[2], smallestPositive[2])]);
            turtle.jump(smallestPositive[2]);
            turtle.goto(biggestNegetive[2]);

    });
    newLines.forEach(l => lines.push(l));

    return i < runs;
}

function drawCell(cell) {
    [[-.5,-.5],[.5,-.5],[.5,.5],[-.5,.5]].map(pt => scale2(pt, cell.size)).forEach((pt, i, a) => {
        turtle.jump(add2(cell.center, pt));
        turtle.goto(add2(cell.center, a[(i+1)%a.length]));
    });
}


////////////////////////////////////////////////////////////////
// Square Grid utility code - Created by Jurgen Westerhof 2023
// https://turtletoy.net/turtle/4633bef396
////////////////////////////////////////////////////////////////
function Grid(size, spacing, canvasSize = 200, location = [0, 0], cellProperties = {}) {
    function add2(a, b) { return [a[0]+b[0], a[1]+b[1]]; }
    class Grid {
        constructor(size, spacing, canvasSize, location, cellProperties) {
            this.size = size;this.spacing = spacing;this.cellProperties = cellProperties;this.iterateMax = this.size**2 - 1;
            this.canvasSize = canvasSize;this.location = location;this.cellSize = (Math.max(0.1, (canvasSize - (size-1)*spacing)) / size);
        }
        getCellByIndex(i) {const col = i % this.size;const row = i / this.size | 0;return this.getCellByCoord(col, row);}
        getCellByCoord(col, row) {const vertice = (i) => (i + .5) * this.cellSize + i * this.spacing - this.canvasSize / 2;return {center: add2(this.location, [vertice(col), vertice(row)]),column: col,row: row,index: row * this.size + col,size: this.cellSize,spacing: this.spacing,properties: this.cellProperties,};}
        *iterator() {
            for(let i = 0; i <= this.iterateMax; i++) {
                yield this.getCellByIndex(i);
            }
        }
    }
    return new Grid(size, spacing, canvasSize, location, cellProperties);
}

////////////////////////////////////////////////////////////////
// 2D Vector Math utility code - Created by several Turtletoy users
////////////////////////////////////////////////////////////////
function norm2(a) { return scale2(a, 1/len2(a)); }
function add2(a, b) { return [a[0]+b[0], a[1]+b[1]]; }
function sub2(a, b) { return [a[0]-b[0], a[1]-b[1]]; }
function mul2(a, b) { return [a[0]*b[0], a[1]*b[1]]; }
function scale2(a, s) { return mul2(a, [s,s]); }
function lerp2(a,b,t) { return [a[0]*(1-t) + b[0]*t, a[1]*(1-t) + b[1]*t]; }
function lenSq2(a) { return a[0]**2+a[1]**2; }
function len2(a) { return Math.sqrt(lenSq2(a)); }
function rot2(a) { return [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a)]; }
function trans2(m, a) { return [m[0]*a[0]+m[2]*a[1], m[1]*a[0]+m[3]*a[1]]; } //Matrix(2x1) x Matrix(2x2)
function dist2(a,b) { return Math.hypot(...sub2(a,b)); }
function dot2(a,b) { return a[0]*b[0]+a[1]*b[1]; }
function cross2(a,b) { return a[0]*b[1] - a[1]*b[0]; }
function multiply2(a2x2, a) { return [(a[0]*a2x2[0])+(a[1]*a2x2[1]),(a[0]*a2x2[2])+(a[1]*a2x2[3])]; } //Matrix(2x2) x Matrix(1x2)
function intersect_info2(as, ad, bs, bd) {
    const d = [bs[0] - as[0], bs[1] - as[1]];
    const det = bd[0] * ad[1] - bd[1] * ad[0];
    if(det === 0) return false;
    const res = [(d[1] * bd[0] - d[0] * bd[1]) / det, (d[1] * ad[0] - d[0] * ad[1]) / det];
    return [...res, add2(as, scale2(ad, res[0]))];
}
function intersect_ray2(a, b, c, d) {
    const i = intersect_info2(a, b, c, d);
    return i === false? i: i[2];
}
function segment_intersect2(a,b,c,d, inclusive = true) {
    const i = intersect_info2(a, sub2(b, a), c, sub2(d, c));
    if(i === false) return false;
    const t = inclusive? 0<=i[0]&&i[0]<=c&&0<=i[1]&&i[1]<=1: 0<i[0]&&i[0]<1&&0<i[1]&&i[1]<1;
    return t?i[2]:false;
}
function eq2(a,b) { return a[0]==b[0]&&a[1]==b[1]; }
function clamp2(a, tl, br) { return [Math.max(Math.min(br[0], a[0]), tl[0]), Math.max(Math.min(br[1], a[1]), tl[1])]; }

////////////////////////////////////////////////////////////////
// Uniform Point Distribution code - Created by Jurgen Westerhof 2023
////////////////////////////////////////////////////////////////
function UniformPointDistributor(leftTop = [-100, -100], rightBottom = [100, 100]) {
    class UniformPointDistributor {
        constructor(leftTop = [-100, -100], rightBottom = [100, 100]) {
            this.leftTop = leftTop;
            this.rightBottom = rightBottom;
            this.width = rightBottom[0]-leftTop[0];
            this.height = rightBottom[1]-leftTop[1];
            this.maxDist = (this.width**2+this.height**2)**.5;
            this.pts = [];
        }
    
        *getPointIterator(radiusFunction = null, candidates = 20, maxTries = 1000) {
            if(radiusFunction == null) radiusFunction = (x, y, maximum) => 0;
            
            const randomPoint = () => [Math.random()*this.width+this.leftTop[0],Math.random()*this.height+this.leftTop[1]];
            
            this.pts.push([randomPoint()].map(pt => [...pt, radiusFunction(...pt)])[0]);
            yield this.pts[this.pts.length - 1];
            
            while(true) {
                let pt = [0,0,-1];
                let tries = 0;
                while(pt[2] < 0 && tries < maxTries) {
                    tries++;
                    //using [length] candidate points
                    pt = Array.from({length: candidates})
                         //which are random points
                         .map(i => randomPoint())
                         //then add the distance to that candidate minus the radius of each point it is compared to
                         .map(i => [i[0], i[1], this.pts.map(j => [j[0], j[1], Math.hypot(i[0]-j[0], i[1]-j[1]) - j[2]])
                                                   //so that it is the smallest distance from the
                                                   //candidate to any of the already chosen points
                                                   .reduce((prev, current) => (current[2] < prev[2])? current: prev, [0,0,this.maxDist])[2]
                            ])
                         //then pick the candidate that has the largest minimum distance from the group of candidates
                         .reduce((prev, current) => prev == null? current: ((current[2] > prev[2])? current: prev), null)
                         //and set the 3rd position to its own radius instead of the distance to the nearest point
                         .map((v, i, arr) => i < 2? v: radiusFunction(arr[0], arr[1], v))
                         ////and remove the distance before promoting the candidate
                         //.filter((i, k) => k < 2)
                }
                if(tries == maxTries) return false;
                //add a point to the list
                this.pts.push(pt);
                yield pt;
            }
        }
    }
    return new UniformPointDistributor(leftTop, rightBottom);
}

//https://www.npmjs.com/package/simplex-noise?activeTab=code
/*
A fast javascript implementation of simplex noise by Jonas Wagner
Based on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. Which is based on example code by Stefan Gustavson (stegu@itn.liu.se). With Optimisations by Peter Eastman (peastman@drizzle.stanford.edu). Better rank ordering method by Stefan Gustavson in 2012. Adoption for use in TurtleToy by Jurgen Westerhof in 2023
Copyright (c) 2022 Jonas Wagner
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
function Simplex(){
    const F2=.5*(3**.5-1),G2=(3-3**.5)/6,F3=1/3,G3=1/6,F4=(5**.5-1)/4,G4=(5-5**.5)/20,grad2=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]),grad3=new Float64Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),grad4=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);
    function buildPermutationTable(t){const n=512,r=new Uint8Array(n);for(let t=0;t<256;t++)r[t]=t;for(let n=0;n<255;n++){const e=n+~~(t()*(256-n)),o=r[n];r[n]=r[e],r[e]=o}for(let t=256;t<n;t++)r[t]=r[t-256];return r}
    class Simplex {
        createNoise2D(t=Math.random){const n=buildPermutationTable(t),e=new Float64Array(n).map((t=>grad2[t%12*2])),a=new Float64Array(n).map((t=>grad2[t%12*2+1]));return function(t,o){let r=0,c=0,l=0;const i=(t+o)*F2,s=t+i|0,u=o+i|0,f=(s+u)*G2,G=t-(s-f),d=o-(u-f);let m,F;G>d?(m=1,F=0):(m=0,F=1);const b=G-m+G2,g=d-F+G2,p=G-1+2*G2,w=d-1+2*G2,y=255&s,A=255&u;let h=.5-G*G-d*d;if(h>=0){const t=y+n[A];h*=h,r=h*h*(e[t]*G+a[t]*d)}let D=.5-b*b-g*g;if(D>=0){const t=y+m+n[A+F];D*=D,c=D*D*(e[t]*b+a[t]*g)}let M=.5-p*p-w*w;if(M>=0){const t=y+1+n[A+1];M*=M,l=M*M*(e[t]*p+a[t]*w)}return 70*(r+c+l)}}
        createNoise3D(e=Math.random){const t=buildPermutationTable(e),n=new Float64Array(t).map((e=>grad3[e%12*3])),a=new Float64Array(t).map((e=>grad3[e%12*3+1])),r=new Float64Array(t).map((e=>grad3[e%12*3+2]));return function(e,l,o){let s,c,G,i;const f=(e+l+o)*F3,u=e+f|0,d=l+f|0,m=o+f|0,F=(u+d+m)*G3,g=e-(u-F),p=l-(d-F),w=o-(m-F);let y,A,b,h,D,M;g>=p?p>=w?(y=1,A=0,b=0,h=1,D=1,M=0):g>=w?(y=1,A=0,b=0,h=1,D=0,M=1):(y=0,A=0,b=1,h=1,D=0,M=1):p<w?(y=0,A=0,b=1,h=0,D=1,M=1):g<w?(y=0,A=1,b=0,h=0,D=1,M=1):(y=0,A=1,b=0,h=1,D=1,M=0);const N=g-y+G3,P=p-A+G3,T=w-b+G3,j=g-h+2*G3,k=p-D+2*G3,q=w-M+2*G3,v=g-1+3*G3,x=p-1+3*G3,z=w-1+3*G3,B=255&u,C=255&d,E=255&m;let H=.6-g*g-p*p-w*w;if(H<0)s=0;else{const e=B+t[C+t[E]];H*=H,s=H*H*(n[e]*g+a[e]*p+r[e]*w)}let I=.6-N*N-P*P-T*T;if(I<0)c=0;else{const e=B+y+t[C+A+t[E+b]];I*=I,c=I*I*(n[e]*N+a[e]*P+r[e]*T)}let J=.6-j*j-k*k-q*q;if(J<0)G=0;else{const e=B+h+t[C+D+t[E+M]];J*=J,G=J*J*(n[e]*j+a[e]*k+r[e]*q)}let K=.6-v*v-x*x-z*z;if(K<0)i=0;else{const e=B+1+t[C+1+t[E+1]];K*=K,i=K*K*(n[e]*v+a[e]*x+r[e]*z)}return 32*(s+c+G+i)}}
        createNoise4D(e=Math.random){const t=buildPermutationTable(e),a=new Float64Array(t).map((e=>grad4[e%32*4])),n=new Float64Array(t).map((e=>grad4[e%32*4+1])),r=new Float64Array(t).map((e=>grad4[e%32*4+2])),l=new Float64Array(t).map((e=>grad4[e%32*4+3]));return function(e,o,G,s){let c,i,f,d,m;const u=(e+o+G+s)*F4,F=e+u|0,g=o+u|0,p=G+u|0,w=s+u|0,y=(F+g+p+w)*G4,A=e-(F-y),b=o-(g-y),h=G-(p-y),D=s-(w-y);let M=0,N=0,P=0,T=0;A>b?M++:N++,A>h?M++:P++,A>D?M++:T++,b>h?N++:P++,b>D?N++:T++,h>D?P++:T++;const j=M>=3?1:0,k=N>=3?1:0,q=P>=3?1:0,v=T>=3?1:0,x=M>=2?1:0,z=N>=2?1:0,B=P>=2?1:0,C=T>=2?1:0,E=M>=1?1:0,H=N>=1?1:0,I=P>=1?1:0,J=T>=1?1:0,K=A-j+G4,L=b-k+G4,O=h-q+G4,Q=D-v+G4,R=A-x+2*G4,S=b-z+2*G4,U=h-B+2*G4,V=D-C+2*G4,W=A-E+3*G4,X=b-H+3*G4,Y=h-I+3*G4,Z=D-J+3*G4,$=A-1+4*G4,_=b-1+4*G4,ee=h-1+4*G4,te=D-1+4*G4,ae=255&F,ne=255&g,re=255&p,le=255&w;let oe=.6-A*A-b*b-h*h-D*D;if(oe<0)c=0;else{const e=ae+t[ne+t[re+t[le]]];oe*=oe,c=oe*oe*(a[e]*A+n[e]*b+r[e]*h+l[e]*D)}let Ge=.6-K*K-L*L-O*O-Q*Q;if(Ge<0)i=0;else{const e=ae+j+t[ne+k+t[re+q+t[le+v]]];Ge*=Ge,i=Ge*Ge*(a[e]*K+n[e]*L+r[e]*O+l[e]*Q)}let se=.6-R*R-S*S-U*U-V*V;if(se<0)f=0;else{const e=ae+x+t[ne+z+t[re+B+t[le+C]]];se*=se,f=se*se*(a[e]*R+n[e]*S+r[e]*U+l[e]*V)}let ce=.6-W*W-X*X-Y*Y-Z*Z;if(ce<0)d=0;else{const e=ae+E+t[ne+H+t[re+I+t[le+J]]];ce*=ce,d=ce*ce*(a[e]*W+n[e]*X+r[e]*Y+l[e]*Z)}let ie=.6-$*$-_*_-ee*ee-te*te;if(ie<0)m=0;else{const e=ae+1+t[ne+1+t[re+1+t[le+1]]];ie*=ie,m=ie*ie*(a[e]*$+n[e]*_+r[e]*ee+l[e]*te)}return 27*(c+i+f+d+m)}}
    }
    return new Simplex();
}