Viewing: snake9.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 isPaused = false;
const headImg = new Image();
headImg.src = "snake-head.png";
const bodyImg = new Image();
bodyImg.src = "snake-body.png";
const foodImg = new Image();
foodImg.src = "apple.png";
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box,
};
document.addEventListener("keydown", (e) => {
if (e.key === "p" || e.key === "P") {
isPaused = !isPaused;
return;
}
changeDirection(e);
});
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() {
if (isPaused) {
drawPauseScreen();
return;
}
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < snake.length; i++) {
const segment = snake[i];
const img = i === 0 ? headImg : bodyImg;
ctx.drawImage(img, segment.x, segment.y, box, box);
}
ctx.drawImage(foodImg, food.x, food.y, box, box);
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;
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;
}
const 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 drawPauseScreen() {
// Draw dimmed background
ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw "Paused" text
ctx.fillStyle = "#0f0";
ctx.font = "30px Arial";
ctx.textAlign = "center";
ctx.fillText("Paused", canvas.width / 2, canvas.height / 2);
}
function collision(x, y, array) {
return array.some(segment => segment.x === x && segment.y === y);
}
const game = setInterval(draw, 150);
Close