const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); let snake = [{ x: 10, y: 10 }]; let direction = { x: 0, y: 0 }; let food = { x: 15, y: 15 }; let score = 0; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw food ctx.fillStyle = 'red'; ctx.fillRect(food.x * 10, food.y * 10, 10, 10); // Draw snake ctx.fillStyle = 'green'; for (let segment of snake) { ctx.fillRect(segment.x * 10, segment.y * 10, 10, 10); } // Move snake const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y }; snake.unshift(head); // Check for food collision if (head.x === food.x && head.y === food.y) { score++; spawnFood(); } else { snake.pop(); } // Check for collisions with walls or self if (head.x < 0 || head.x >= canvas.width / 10 || head.y < 0 || head.y >= canvas.height / 10 || snakeCollision(head)) { alert('Game Over! Your score: ' + score); document.location.reload(); } } function spawnFood() { food.x = Math.floor(Math.random() * (canvas.width / 10)); food.y = Math.floor(Math.random() * (canvas.height / 10)); } function snakeCollision(head) { return snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y); } document.addEventListener('keydown', event => { if (event.key === 'ArrowUp' && direction.y === 0) { direction = { x: 0, y: -1 }; } else if (event.key === 'ArrowDown' && direction.y === 0) { direction = { x: 0, y: 1 }; } else if (event.key === 'ArrowLeft' && direction.x === 0) { direction = { x: -1, y: 0 }; } else if (event.key === 'ArrowRight' && direction.x === 0) { direction = { x: 1, y: 0 }; } }); setInterval(draw, 100);