let canvas, ctx; let submarine = { x: 180, y: 500, width: 40, height: 20 }; let obstacles = []; let gameInterval; let score = 0; function startGame() { canvas = document.getElementById("gameCanvas"); ctx = canvas.getContext("2d"); obstacles = []; score = 0; document.getElementById("status").textContent = ""; clearInterval(gameInterval); gameInterval = setInterval(gameLoop, 30); document.addEventListener("keydown", moveSubmarine); } function moveSubmarine(e) { if (e.key === "ArrowLeft" && submarine.x > 0) submarine.x -= 10; if (e.key === "ArrowRight" && submarine.x < canvas.width - submarine.width) submarine.x += 10; } function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw submarine ctx.fillStyle = "#00ccff"; ctx.fillRect(submarine.x, submarine.y, submarine.width, submarine.height); // Create obstacles if (Math.random() < 0.03) { obstacles.push({ x: Math.random() * 360, y: 0, size: 30 }); } // Draw and move obstacles ctx.fillStyle = "#33cc33"; for (let i = 0; i < obstacles.length; i++) { let obs = obstacles[i]; obs.y += 4; ctx.beginPath(); ctx.arc(obs.x, obs.y, obs.size / 2, 0, 2 * Math.PI); ctx.fill(); // Collision if ( obs.y + obs.size / 2 > submarine.y && obs.x > submarine.x && obs.x < submarine.x + submarine.width ) { endGame(); return; } } // Remove passed obstacles obstacles = obstacles.filter((o) => o.y < canvas.height); score++; if (score > 500) { endGame(true); } } function endGame(win = false) { clearInterval(gameInterval); document.removeEventListener("keydown", moveSubmarine); document.getElementById("status").textContent = win ? "🌊 You reached Atlantis!" : "💥 You were tangled in algae!"; }