Lucky Turtlesnake

This #snake can sometimes win the game!

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;
let attempts = 0;
let optimism = 5;
let dirfn = turtle.left;
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() {
    h = Math.round(360+turtle.h())%360;
    const oldx = x;
    const oldy = y;
    if (h === 270) {
        if (x+1 < divs && pixels[x+1][y+1] === true && pixels[x+1][y] === false) {
            h = (h + 90)%360;
            x++;
        } 
        else {
            y--;
        }
    }
    else if (h === 0) {
        if (y+1 < divs && pixels[x-1][y+1] === true && pixels[x][y+1] === false) {
            h = (h + 90)%360;
            y++;
        } 
        else {
            x++;
        }
    }
    else if (h === 90) {
        if (x-1 >= 0 && pixels[x-1][y-1] === true && pixels[x-1][y] === false) {
            h = (h + 90)%360;
            x--;
        }
        else {
            y++;
        }
    }
    else if (h === 180) {
        if (y-1 >= 0 && pixels[x-1][y-1] === true && pixels[x][y-1] === false) {
            h = (h + 90)%360;
            y--;
        }
        else {
            x--;
        }
    }
    turtle.seth(h);
    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;
}

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 {
        pixels[x][y] = true;
        pixel(i==0 ? 1 : 0.5);
        optimism--;
        if (optimism < 0) {
            optimism = 5;
        }
    }
    return true;
}