Viewing: snake7.js
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const scoreDisplay = document.getElementById("score");
const box = 20;
let snake = [{ x: 9 * box, y: 10 * box }];
let direction = "RIGHT";
let score = 0;
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box,
};
document.addEventListener("keydown", changeDirection);
function changeDirection(e) {
if (e.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
else if (e.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
else if (e.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
else if (e.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
}
function draw() {
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw snake with taper and eyes
for (let i = 0; i < snake.length; i++) {
const s = snake[i];
const isHead = i === 0;
const size = box * (1 - i / (snake.length * 1.5)); // taper tail
const centerX = s.x + box / 2;
const centerY = s.y + box / 2;
// Gradient from head to tail
const hue = 120 - i * 4;
ctx.fillStyle = `hsl(${hue}, 100%, ${isHead ? 60 : 40}%)`;
ctx.beginPath();
ctx.arc(centerX, centerY, size / 2, 0, Math.PI * 2);
ctx.fill();
// Draw eyes for head
if (isHead) {
ctx.fillStyle = "#fff";
const eyeOffset = size * 0.2;
ctx.beginPath();
ctx.arc(centerX - eyeOffset, centerY - eyeOffset, size * 0.08, 0, Math.PI * 2);
ctx.arc(centerX + eyeOffset, centerY - eyeOffset, size * 0.08, 0, Math.PI * 2);
ctx.fill();
}
}
// Draw food
ctx.fillStyle = "#f00";
ctx.beginPath();
ctx.arc(food.x + box / 2, food.y + box / 2, box / 2.5, 0, Math.PI * 2);
ctx.fill();
let headX = snake[0].x;
let headY = snake[0].y;
if (direction === "LEFT") headX -= box;
if (direction === "RIGHT") headX += box;
if (direction === "UP") headY -= box;
if (direction === "DOWN") headY += box;
// Wrap-around
if (headX < 0) headX = canvas.width - box;
if (headX >= canvas.width) headX = 0;
if (headY < 0) headY = canvas.height - box;
if (headY >= canvas.height) headY = 0;
if (collision(headX, headY, snake)) {
clearInterval(game);
alert("Game Over. Final Score: " + score);
return;
}
let newHead = { x: headX, y: headY };
if (headX === food.x && headY === food.y) {
score += 10;
scoreDisplay.textContent = score;
food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box,
};
} else {
snake.pop();
}
snake.unshift(newHead);
}
function collision(x, y, array) {
return array.some(segment => segment.x === x && segment.y === y);
}
const game = setInterval(draw, 150);
Close