Untitled

 avatar
unknown
plain_text
11 days ago
2.7 kB
3
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Catch the Falling Stars</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
      font-family: Arial, sans-serif;
      background: linear-gradient(to bottom, #1e3c72, #2a5298);
    }

    #gameCanvas {
      display: block;
      margin: 0 auto;
      background-color: #fff3e0;
    }

    .score {
      position: absolute;
      top: 10px;
      left: 10px;
      color: #fff;
      font-size: 20px;
      z-index: 1;
    }
  </style>
</head>
<body>
  <div class="score">Score: <span id="score">0</span></div>
  <canvas id="gameCanvas"></canvas>

  <script>
    const canvas = document.getElementById("gameCanvas");
    const ctx = canvas.getContext("2d");

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    const basket = {
      x: canvas.width / 2 - 50,
      y: canvas.height - 80,
      width: 100,
      height: 20,
      color: "#f39c12",
      moveSpeed: 15,
    };

    const stars = [];
    const starSpeed = 3;
    const starSize = 20;

    let score = 0;

    function drawBasket() {
      ctx.fillStyle = basket.color;
      ctx.fillRect(basket.x, basket.y, basket.width, basket.height);
    }

    function drawStars() {
      stars.forEach((star) => {
        ctx.fillStyle = "#f1c40f";
        ctx.beginPath();
        ctx.arc(star.x, star.y, starSize, 0, Math.PI * 2);
        ctx.fill();
      });
    }

    function updateStars() {
      stars.forEach((star, index) => {
        star.y += starSpeed;

        if (star.y > canvas.height) {
          stars.splice(index, 1);
        }

        if (
          star.x > basket.x &&
          star.x < basket.x + basket.width &&
          star.y + starSize > basket.y
        ) {
          score++;
          document.getElementById("score").innerText = score;
          stars.splice(index, 1);
        }
      });
    }

    function createStar() {
      const x = Math.random() * canvas.width;
      stars.push({ x, y: 0 });
    }

    function moveBasket(event) {
      if (event.key === "ArrowLeft" && basket.x > 0) {
        basket.x -= basket.moveSpeed;
      }
      if (event.key === "ArrowRight" && basket.x < canvas.width - basket.width) {
        basket.x += basket.moveSpeed;
      }
    }

    function gameLoop() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawBasket();
      drawStars();
      updateStars();
      requestAnimationFrame(gameLoop);
    }

    window.addEventListener("keydown", moveBasket);
    setInterval(createStar, 800);
    gameLoop();
  </script>
</body>
</html>
Leave a Comment