let snake = [{x: 10, y: 10}];
let food = generateFood();
let direction = 'RIGHT';
let nextDirection = 'RIGHT';
let gameInterval;
let speed = 150;
let score = 0;
let highScore = localStorage.getItem('snakeHighScore') || 0;
let isPaused = false;
let isGameRunning = false;
highScoreDisplay.textContent = highScore;
function initBoard() {
board.innerHTML = '';
for (let i = 0; i < GRID_SIZE * GRID_SIZE; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
board.appendChild(cell);
}
}
function generateFood() {
let newFood;
do {
newFood = {
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
};
} while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
return newFood;
}
function draw() {
const cells = document.querySelectorAll('.cell');
cells.forEach(cell => {
cell.classList.remove('snake', 'food');
});
snake.forEach(segment => {
const index = segment.y * GRID_SIZE + segment.x;
if (index >= 0 && index < cells.length) {
cells[index].classList.add('snake');
}
});
const foodIndex = food.y * GRID_SIZE + food.x;
if (foodIndex >= 0 && foodIndex < cells.length) {
cells[foodIndex].classList.add('food');
}
}
function update() {
if (isPaused) return;
direction = nextDirection;
const head = {...snake[0]};
switch (direction) {
case 'UP':
head.y--;
break;
case 'DOWN':
head.y++;
break;
case 'LEFT':
head.x--;
break;
case 'RIGHT':
head.x++;
break;
}