Turtlesnake

The indestructible classic #snake. It's not very smart!

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+step/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;

function walk(i) {
    attempts = 0;
    while (attempts < 3 && !attempt()) {
        attempts++;
        i%3==0 ? turtle.left(90) : turtle.right(90);
        h = Math.round(360+turtle.h())%360;
    }
    if (attempts === 3) {
        pixel(1);
        return false;
    } else {
        pixel(i==0 ? 1 : 0.5);
    }
    if (Math.random() > 0.95 || (Math.random() > 0.8 && (x > divs-3 || y > divs-3 || x < 3 || y < 3))) {
        Math.random() > 0.5 ? turtle.left(90) : turtle.right(90);
        h = Math.round(360+turtle.h())%360;
    }
    return true;
}