Maze Splat

Grid walker using random restarts within limits

Log in to post a comment.

Canvas.setpenopacity(-1);
const turtle = new Turtle();

// adjustments
var lim = 57; // dimensional (100 = full)
var extent = 100; // (100 best) less frame, more is off screen
var interations = 4*lim*lim; // (maze fullness)
var darken = true; // redraw lines to darken them
var staying = .6 // 0 (curvy) to 1 (straight)


// keeping track of where it has been
var hit = new Array();
var max = Math.max(lim, extent);
for (var x = -max; x <= max; x++) {
    hit[x] = new Array();
    for (var y = -max; y <= max; y++) {
        hit[x][y] = false;
    }
}

function logHit() {
    hit[turtle.x()][turtle.y()] = true;
}

function isValidDestination(x,y) {
    if (x < -extent || x > extent || 
        y < -extent || y > extent ||
        hit[x][y]) return false;
    return true;
}

var lastdir;

function pickDirection() {
    var okdirs = new Array();
    if (isValidDestination(turtle.x()+1,turtle.y())) okdirs.push(1);
    if (isValidDestination(turtle.x()-1,turtle.y()  )) okdirs.push(2);
    if (isValidDestination(turtle.x()  ,turtle.y()+1)) okdirs.push(3);
    if (isValidDestination(turtle.x()  ,turtle.y()-1)) okdirs.push(4);

    if (okdirs.length == 0) return 0;
    if (Math.random() < staying && okdirs.indexOf(lastdir) != -1) {
        return lastdir;
    } else {
        return okdirs[Math.floor(Math.random()*okdirs.length)];
    }
}

function drawTo(x,y) {
    var fromx = turtle.x();
    var fromy = turtle.y();
    turtle.goto(x,y);
    if (darken) { //redraw at slight offset to darken lines
        var offset = .2;
        turtle.goto(fromx+offset,fromy+offset);
        turtle.goto(x+offset,y+offset);
        turtle.goto(x,y);
    }
}

function move() {
    var newdir = pickDirection();
    if (newdir == 0) { restartTurtle(); return; }
    lastdir = newdir;
    var newx = turtle.x();
    var newy = turtle.y();
    switch(newdir) {
        case 1:
            newx += 1;
            break;
        case 2:
            newx -= 1;
            break;
        case 3:
            newy += 1;
            break;
        case 4:
            newy -= 1;
            break;
        default:
            console.log('move switch default ('+newdir+') hit oops!');
    }
    drawTo(newx, newy);
    logHit();
}

function restartTurtle() {
    turtle.penup();
    turtle.setx(randInt(-lim, lim));
    turtle.sety(randInt(-lim, lim));
    logHit();
    turtle.pendown();
}

// utils
function randInt(min, max) {
    var pick = Math.floor(Math.random() * (max - min + 1) + min);
    return pick;
}

function outline() {
    turtle.penup();
    turtle.goto(-extent,-extent);
    turtle.pendown();
    turtle.goto(extent,-extent);
    turtle.goto(extent,extent);
    turtle.goto(-extent,extent);
    turtle.goto(-extent,-extent);
}

// init
outline();
restartTurtle();

function walk(i) {
    move();

    return i < interations;
}