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

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

const amount = 45; // min=15, max=75, step=1
const border = 1; // min=0, max=1, step=1
const draw_size = border ? 175 / amount : 200  / amount;
const buffer = [];

const FILLED = 1;
const EMPTY = 0;

const shape = 0; // min=0, max=2, step=1 (Gradient, Rectangle, Circle)

// borrowed from <https://turtletoy.net/turtle/cc4d10a96c>
let p;
if (shape == 0) p = (x,y) => x;
else if (shape == 1) p = (x,y) => .7;
else if (shape == 2) p = (x,y) => 1-3*Math.pow((x-.5)*(x-.5)+(y-.5)*(y-.5),.75);

const buffer_size = amount;

function init_buffer() {
    iter(buffer_size, y => iter(buffer_size, x => {
        buffer[y * buffer_size + x] = Math.random() > p(x / buffer_size,y / buffer_size) ? FILLED : EMPTY;
    }));
}

// The walk function will be called until it returns false.
function walk(i) {
    if (i === 0) init_buffer();
    const x =  i % buffer_size;
    const y =  i / buffer_size | 0;
    if (isFilled(i)) {
        if (y === 0 || !isFilled(i - buffer_size)) { // above
            line(x, y, x + 1, y);
        }
        if (y === buffer_size - 1 || !isFilled(i + buffer_size)) { // below
            line(x, y + 1, x + 1, y + 1);
        }
        if (x === 0 || !isFilled(i - 1)) {  // left
            line(x, y, x, y + 1);
        }
        if (x === buffer_size - 1 || !isFilled(i + 1)) {  // right
            line(x + 1, y, x + 1, y + 1);
        } 
    }
    return i < buffer_size*buffer_size;
}

const line = (x1,y1,x2,y2) => {
    x1 -= buffer_size / 2;
    x2 -= buffer_size / 2;
    y1 -= buffer_size / 2;
    y2 -= buffer_size / 2;
    turtle.goto(x1 * draw_size, y1 * draw_size);
    turtle.pendown();
    turtle.goto(x2 * draw_size, y2 * draw_size);
    turtle.penup();
};
const isFilled = i => buffer[i] == FILLED;
const iter = (to, cb) => { for(let v = 0; v < to; v++) cb(v); }