canv = document.querySelector("#gc"); // Canvas
ctx = canv.getContext("2d"); // Get 2d context for canvas
gs = 20; // width of a single square
tc = 20; // Tile count (reused for x and y)
speed = 12; // Speed of snake (higher is faster)
ax = 15, ay = 15; // Apple position (begins at 15, 15)
xv = 0, yv = 0; // X and Y velocity (begins at zero so the snake doesn't move)
px = 10, py = 10; // Start with our snake in the center
trail = []; // This contains the coordinates for our snake parts
tail = 5; // Length of snake
// Game clock
setInterval(function () {
// Shitty AI to change the game cursor direction
yv = ay != py ? (ay > py ? 1 : -1) : 0; // Y axis: Go toward the apple
xv = ax != px && yv == 0 ? (ax > px ? 1 : -1) : 0; // X axis: Also go toward the apple (but let Y go first)
// Move the game cursor
px += xv;
py += yv;
// When overflowing from left edge, wrap to right edge
if (px < 0) px = tc - 1;
// Handle overflow from right edge to left
if (px > tc - 1) px = 0;
// Handle overflow from top to bottom
if (py < 0) py = tc - 1;
// Handle overflow from bottom to top
if (py > tc - 1) py = 0;
// Draw the background
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 400, 400);
// Draw the snake
ctx.fillStyle = "lime";
for (var i = 0; i < trail.length; i++) {
ctx.fillRect(trail[i].x * gs, trail[i].y * gs, gs - 2, gs - 2);
if (trail[i].x == px && trail[i].y == py) tail = 5;
}
// Push a new square to the array at our cursor
trail.push({ x: px, y: py });
while (trail.length > tail) trail.shift();
// Case: Handle collision with apple
if (ax == px && ay == py) {
ax = Math.floor(Math.random() * tc);
ay = Math.floor(Math.random() * tc);
tail++;
}
// Draw our apple
ctx.fillStyle = "red";
ctx.fillRect(ax * gs, ay * gs, gs - 2, gs - 2);
}, 1000 / speed);