SNAKE
#game-container { text-align: center; } #game-canvas { border: 1px solid black; } #touch-controls { margin-top: 10px; } #touch-controls button { font-size: 16px; padding: 5px 10px; margin: 0 5px; } const canvas = document.getElementById('game-canvas'); const ctx = canvas.getContext('2d'); // Set canvas dimensions canvas.width = 400; canvas.height = 400; // Game variables let snake = [{x: 200, y: 200}]; let food = {x: 0, y: 0}; let dx = 10; let dy = 0; // Generate random food position function generateFood() { food.x = Math.floor(Math.random() * (canvas.width / 10)) * 10; food.y = Math.floor(Math.random() * (canvas.height / 10)) * 10; } // Game loop function gameLoop() { // Move the snake const head = {x: snake[0].x + dx, y: snake[0].y + dy}; snake.unshift(head); // Check if snake eats the food if (head.x === food.x && head.y === food.y) { generateFood(); } else { snake.pop(); } // Clear canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw snake ctx.fillStyle = 'green'; snake.forEach(segment => { ctx.fillRect(segment.x, segment.y, 10, 10); }); // Draw food ctx.fillStyle = 'red'; ctx.fillRect(food.x, food.y, 10, 10); } // Change snake direction based on arrow keys document.addEventListener('keydown', e => { if (e.key === 'ArrowLeft' && dx === 0) { dx = -10; dy = 0; } else if (e.key === 'ArrowRight' && dx === 0) { dx = 10; dy = 0; } else if (e.key === 'ArrowUp' && dy === 0) { dx = 0; dy = -10; } else if (e.key === 'ArrowDown' && dy === 0) { dx = 0; dy = 10; } }); // Touch controls const upButton = document.getElementById('up-button'); const downButton = document.getElementById('down-button'); const leftButton = document.getElementById('left-button'); const rightButton = document.getElementById('right-button'); upButton.addEventListener('click', () => { if (dy === 0) { dx = 0; dy = -10; } }); downButton.addEventListener('click', () => { if (dy === 0) { dx = 0; dy = 10; } }); leftButton.addEventListener('click', () => { if (dx === 0) { dx = -10; dy = 0; } }); rightButton.addEventListener('click', () => { if (dx === 0) { dx = 10; dy = 0; } }); // Start the game generateFood(); setInterval(gameLoop, 100);