Viewing: snake2.js
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const scoreDisplay = document.getElementById("score");
const box = 20; // Size of each square (20x20 px)
let snake = [{ x: 9 * box, y: 10 * box }];
let direction = "RIGHT";
let score = 0;
// Initial food position
let food = {
x: Math.floor(Math.random() * 20) * box,
y: Math.floor(Math.random() * 20) * box,
};
// Handle arrow key input
document.addEventListener("keydown", changeDirection);
function changeDirection(event) {
if (event.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
else if (event.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
else if (event.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
else if (event.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
}
function draw() {
// Clear canvas
ctx.fillStyle = "#111";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw snake
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = i === 0 ? "#0f0" : "#0a0";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
}
// Draw food
ctx.fillStyle = "#f00";
ctx.fillRect(food.x, food.y, box, box);
// Get snake head coordinates
let headX = snake[0].x;
let headY = snake[0].y;
// Update position
if (direction === "LEFT") headX -= box;
if (direction === "RIGHT") headX += box;
if (direction === "UP") headY -= box;
if (direction === "DOWN") headY += box;
// Check collision with wall or self
if (
headX < 0 || headX >= canvas.width ||
headY < 0 || headY >= canvas.height ||
collision(headX, headY, snake)
) {
clearInterval(game);
alert("Game Over. Final Score: " + score);
return;
}
// Create new head
let newHead = { x: headX, y: headY };
// Check if food is eaten
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(); // Remove tail
}
snake.unshift(newHead); // Add new head
}
// Check for collision with snake body
function collision(x, y, array) {
return array.some(segment => segment.x === x && segment.y === y);
}
// Start game loop
const game = setInterval(draw, 150);
Close