Viewing: snake6.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 gradient and rounded corners
for (let i = 0; i < snake.length; i++) {
const s = snake[i];
const isHead = i === 0;
const grad = ctx.createLinearGradient(s.x, s.y, s.x + box, s.y + box);
grad.addColorStop(0, isHead ? "#9f0" : "#0f0");
grad.addColorStop(1, isHead ? "#0f0" : "#060");
ctx.fillStyle = grad;
ctx.shadowColor = "#0f0";
ctx.shadowBlur = isHead ? 15 : 8;
drawRoundedRect(s.x, s.y, box, box, 5);
}
ctx.shadowBlur = 0; // reset shadow
// 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);
}
// Utility: Draw a rounded rectangle
function drawRoundedRect(x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fill();
}
const game = setInterval(draw, 150);
Close