// Set up the game canvas const canvas = document.getElementById('game-canvas'); const ctx = canvas.getContext('2d'); canvas.width = 400; canvas.height = 400; // Game variables let snake = [{ x: 10, y: 10 }]; let food = { x: Math.floor(Math.random() * 40) * 10, y: Math.floor(Math.random() * 40) * 10 }; let direction = 'right'; let score = 0; let gameOver = false; // Game loop function gameLoop() { if (!gameOver) { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Move the snake moveSnake(); // Draw the snake drawSnake(); // Draw the food drawFood(); // Check for collisions checkCollisions(); // Request the next frame requestAnimationFrame(gameLoop); } else { // Game over alert(`Game Over! Your score is: ${score}`); } } // Move the snake function moveSnake() { // Add a new head to the snake const head = { x: snake[0].x, y: snake[0].y }; switch (direction) { case 'up': head.y -= 10; break; case 'down': head.y += 10; break; case 'left': head.x -= 10; break; case 'right': head.x += 10; break; } snake.unshift(head); // Remove the tail if the snake is not growing if (head.x === food.x && head.y === food.y) { score++; food = { x: Math.floor(Math.random() * 40) * 10, y: Math.floor(Math.random() * 40) * 10 }; } else { snake.pop(); } } // Draw the snake function drawSnake() { ctx.fillStyle = 'green'; snake.forEach(segment => { ctx.fillRect(segment.x, segment.y, 10, 10); }); } // Draw the food function drawFood() { ctx.fillStyle = 'red'; ctx.fillRect(food.x, food.y, 10, 10); } // Check for collisions function checkCollisions() { // Check for self-collision for (let i = 1; i < snake.length; i++) { if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) { gameOver = true; return; } } // Check for wall collision if ( snake[0].x < 0 || snake[0].x >= canvas.width || snake[0].y < 0 || snake[0].y >= canvas.height ) { gameOver = true; return; } } // Handle keyboard input document.addEventListener('keydown', e => { switch (e.key) { case 'ArrowUp': if (direction !== 'down') direction = 'up'; break; case 'ArrowDown': if (direction !== 'up') direction = 'down'; break; case 'ArrowLeft': if (direction !== 'right') direction = 'left'; break; case 'ArrowRight': if (direction !== 'left') direction = 'right'; break; } }); // Start the game gameLoop();