const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const scoreSpan = document.getElementById('score-value'); const restartBtn = document.getElementById('restart-btn'); const gameOverDiv = document.getElementById('game-over-message'); // Parámetros del juego const gridSize = 20; // Tamaño de cada celda const tileCount = 20; // El área es de 20x20 celdas let snake, direction, food, score, gameInterval, gameOver; function startGame() { snake = [ {x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10} ]; direction = 'right'; score = 0; gameOver = false; scoreSpan.textContent = score; gameOverDiv.textContent = ''; placeFood(); clearInterval(gameInterval); gameInterval = setInterval(gameLoop, 100); } function placeFood() { food = { x: Math.floor(Math.random() * tileCount), y: Math.floor(Math.random() * tileCount) }; // Asegúrate que la comida no aparece en la serpiente if (snake.some(segment => segment.x === food.x && segment.y === food.y)) { placeFood(); } } function gameLoop() { // Mueve la serpiente const head = {x: snake[0].x, y: snake[0].y}; switch (direction) { case 'left': head.x--; break; case 'up': head.y--; break; case 'right': head.x++; break; case 'down': head.y++; break; } // Choca con pared if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) { endGame(); return; } // Choca consigo mismo if (snake.some(seg => seg.x === head.x && seg.y === head.y)) { endGame(); return; } snake.unshift(head); // Come la comida if (head.x === food.x && head.y === food.y) { score++; scoreSpan.textContent = score; placeFood(); } else { snake.pop(); } drawGame(); } function drawGame() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Dibuja la comida ctx.fillStyle = "#fc5185"; ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize); // Dibuja la serpiente for (let i = 0; i < snake.length; i++) { ctx.fillStyle = i === 0 ? "#ffd700" : "#145991"; ctx.fillRect(snake[i].x * gridSize, snake[i].y * gridSize, gridSize, gridSize); } } function changeDirection(e) { if (gameOver) return; switch (e.key) { case "ArrowLeft": if (direction !== "right") direction = "left"; break; case "ArrowUp": if (direction !== "down") direction = "up"; break; case "ArrowRight": if (direction !== "left") direction = "right"; break; case "ArrowDown": if (direction !== "up") direction = "down"; break; } } function endGame() { clearInterval(gameInterval); gameOver = true; gameOverDiv.textContent = "¡Fin del juego! Puntaje final: " + score; } window.addEventListener('keydown', changeDirection); restartBtn.onclick = startGame; // Inicia el juego startGame();