const snake = document.getElementById('snake');
const food = document.getElementById('food');
const gameContainer = document.querySelector('.game-container');
let snakeX = 2;
let snakeY = 2;
let foodX = 10;
let foodY = 10;
let gridSize = 20;
let snakeSpeed = 100;
let dx = gridSize;
let dy = 0;
let snakeBody = [];
let score = 0;
function update() {
snakeX += dx;
snakeY += dy;
if (snakeX < 0) snakeX = gameContainer.offsetWidth - gridSize;
if (snakeX >= gameContainer.offsetWidth) snakeX = 0;
if (snakeY < 0) snakeY = gameContainer.offsetHeight - gridSize;
if (snakeY >= gameContainer.offsetHeight) snakeY = 0;
if (snakeX === foodX && snakeY === foodY) {
score++;
foodX = Math.floor(Math.random() * (gameContainer.offsetWidth / gridSize)) * gridSize;
foodY = Math.floor(Math.random() * (gameContainer.offsetHeight / gridSize)) * gridSize;
} else {
snakeBody.pop();
}
const newHead = document.createElement('div');
newHead.style.width = gridSize + 'px';
newHead.style.height = gridSize + 'px';
newHead.style.backgroundColor = '#333';
newHead.style.position = 'absolute';
newHead.style.left = snakeX + 'px';
newHead.style.top = snakeY + 'px';
snakeBody.unshift(newHead);
snake.innerHTML = '';
snakeBody.forEach(segment => snake.appendChild(segment));
if (snakeBody.length > score + 1) {
snakeBody.pop();
}
if (checkCollision()) {
clearInterval(gameInterval);
alert('Game Over! Your Score: ' + score);
}
}
function checkCollision() {
return snakeBody.slice(1).some(segment => {
return snakeX === parseInt(segment.style.left, 10) && snakeY === parseInt(segment.style.top, 10);
});
}
document.addEventListener('keydown', (e) => {
switch (e.key) {
case 'ArrowUp':
if (dy !== gridSize) {
dx = 0;
dy = -gridSize;
}
break;
case 'ArrowDown':
if (dy !== -gridSize) {
dx = 0;
dy = gridSize;
}
break;
case 'ArrowLeft':
if (dx !== gridSize) {
dx = -gridSize;
dy = 0;
}
break;
case 'ArrowRight':
if (dx !== -gridSize) {
dx = gridSize;
dy = 0;
}
break;
}
});
let gameInterval = setInterval(update, snakeSpeed);