Optimistic Turtlesnake

This Turtlesnake's glass tends to being half full. #snake

Log in to post a comment.

Canvas.setpenopacity(1);
const divs = 40;
const extent = 100;
const step = 2*extent/divs;

const turtle = new Turtle();
let pixels = [...Array(divs)].map(_ => [...Array(divs)].map(_ => false));
turtle.penup();
let x = Math.floor(divs/4+Math.random()*divs/2);
let y = Math.floor(divs/4+Math.random()*divs/2);
let h = Math.round(Math.random()*4)*90;
turtle.goto(x*step-extent/2, y*step-extent/2+step/2);
turtle.seth(h);

function pixel(opacity) {
    turtle.goto(-extent+x*step+step/3, -extent+y*step+step/3);
    turtle.seth(0);
    turtle.forward(0.5);
    turtle.right(90);
    turtle.forward(0.5);
    turtle.right(90);
    turtle.pendown();
    for (let i = turtle.y()-step; i < turtle.y()+step-2; i+=0.25/opacity) {
        turtle.forward(step-1);
        turtle.right(90);
        turtle.forward(0.125/opacity);
        turtle.right(90);
        turtle.forward(step-1);
        turtle.left(90);
        turtle.forward(0.125/opacity);
        turtle.left(90);
    }
    turtle.penup();
    turtle.seth(h);
}

function attempt() {
    const oldx = x;
    const oldy = y;
    pixels[x][y] = true;
    if (h === 270) {
        y--;
    }
    else if (h === 0) {
        x++;
    }
    else if (h === 90) {
        y++;
    }
    else if (h === 180) {
        x--;
    }
    if (x >= divs || x <= 0 || y >= divs || y <= 0) {
        x = oldx;
        y = oldy;
        return false;
    }
    if (pixels[x][y]) {
        x = oldx;
        y = oldy;
        return false;
    }
    return true;
}

let attempts = 0;
let optimism = 5;
let dirfn = turtle.left;

function walk(i) {
    attempts = 0;
    dirfn = Math.random() ? turtle.left : turtle.right;
    while (attempts < 3 && !attempt()) {
        attempts++;
        dirfn.call(turtle, 90);
        if (optimism < 0) {
            dirfn.call(turtle, 90);
        }
        if ((turtle.h()+180)%360 === h) {
            dirfn.call(turtle, 90);
        }
        h = Math.round(360+turtle.h())%360;
    }
    if (attempts === 3) {
        pixel(1);
        return false;
    } else {
        pixel(i==0 ? 1 : 0.5);
        optimism--;
        if (optimism < 0) {
            optimism = 5;
        }
    }
    return true;
}