<html>
<head>
  <title>Catch the Falling Apples - HTML Game</title>
</head>
<body>
  <h1>Catch the Falling Apples</h1>
  <style>
    body {
      background-color: beige;
    }
    #game-area {
      position: relative;
      width: 500px;
      height: 400px;
      background-color: lightgreen;
      margin: 0 auto;
    }
    #basket {
      position: absolute;
      top: 350px;
      left: 225px;
      width: 50px;
      height: 50px;
      background-image: url('basket.png');
    }
    #apple {
      position: absolute;
      width: 50px;
      height: 50px;
      background-image: url('apple.png');
    }
  </style>
  <div id="game-area">
    <div id="basket"></div>
    <div id="apple"></div>
  </div>
  <script>
    let basket = document.querySelector('#basket');
    let apple = document.querySelector('#apple');
    let gameArea = document.querySelector('#game-area');
    let score = 0;
    let speed = 4;
    let gameOver = false;
<pre><code>// move the basket
window.onkeydown = function(e) {
  if (e.key === 'ArrowLeft' &amp;&amp; basket.offsetLeft &gt; 0) {
    basket.style.left = basket.offsetLeft - 15 + 'px';
  } else if (e.key === 'ArrowRight' &amp;&amp; basket.offsetLeft &lt; (gameArea.offsetWidth - basket.offsetWidth)) {
    basket.style.left = basket.offsetLeft + 15 + 'px';
  }
}

// move the apple
function moveApple() {
  if (apple.offsetTop &gt; gameArea.offsetHeight) {
    apple.style.top = 0;
    apple.style.left = Math.floor(Math.random() * gameArea.offsetWidth) + 'px';
  } else {
    apple.style.top = apple.offsetTop + speed + 'px';
  }
}

// check if apple was caught
function checkCollision() {
  if (
    apple.offsetTop + apple.offsetHeight &gt;= basket.offsetTop &amp;&amp;
    apple.offsetLeft + apple.offsetWidth &gt;= basket.offsetLeft &amp;&amp;
    apple.offsetLeft &lt;= basket.offsetLeft + basket.offsetWidth
  ) {
    score++;
    speed++;
    apple.style.top = 0;
    apple.style.left = Math.floor(Math.random() * gameArea.offsetWidth) + 'px';
  }
}

// check for game over
function checkGameOver() {
  if (apple.offsetTop + apple.offsetHeight &gt; gameArea.offsetHeight) {
    gameOver = true;
  }
}

// game loop
function loop() {
  if (!gameOver) {
    moveApple();
    checkCollision();
    checkGameOver();
    requestAnimationFrame(loop);
  } else {
    alert('Game Over! Your score is: ' + score);
  }
}
loop();
</code></pre>
  </script>
</body>
</html>
HTML Game: Catch the Falling Apples - Simple and Fun

原文地址: https://www.cveoy.top/t/topic/lmb8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录