Maze Splat

Grid walker using random restarts within limits

Log in to post a comment.

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

// adjustments
let fullness = 50; //min=1,max=100,step=1
var extent = 98; // (100 best) less frame, more is off screen
var interations = 5*fullness*fullness; // (maze fullness)
var darken = true; // redraw lines to darken them
let rigidity = .9; //min=0.5,max=1,step=.01


// keeping track of where it has been
var hit = new Array();
var max = Math.max(fullness, 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() < rigidity && 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(-fullness, fullness));
    turtle.sety(randInt(-fullness, fullness));
    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;
}