<!DOCTYPE html>
<html>
  <head>
    <title>Simple HTML Game: Move the Player to the Target</title>
    <style>
      body {
        background: #f2f2f2;
      }
<pre><code>  #game {
    width: 600px;
    height: 400px;
    margin: auto;
    background: #ccc;
    padding: 15px;
  }
  
  #player {
    width: 30px;
    height: 30px;
    background: #000;
    position: relative;
    left: 0;
    top: 0;
  }
  
  #target {
    width: 30px;
    height: 30px;
    background: #f00;
    position: relative;
    left: 0;
    top: 0;
  }
&lt;/style&gt;
</code></pre>
  </head>
  <body>
    <h1>Simple HTML Game: Move the Player to the Target</h1>
    <div id='game'>
      <div id='player'></div>
      <div id='target'></div>
    </div>
    <script>
      let player = document.querySelector('#player');
      let target = document.querySelector('#target');
<pre><code>  // Listen to keydown events
  document.addEventListener('keydown', function(e) {
    
    // Check which key was pressed
    switch(e.keyCode) {
      // Left arrow
      case 37:
        // Move left
        player.style.left = (player.offsetLeft - 10) + 'px';
        break;
      // Up arrow
      case 38:
        // Move up
        player.style.top = (player.offsetTop - 10) + 'px';
        break;
      // Right arrow
      case 39:
        // Move right
        player.style.left = (player.offsetLeft + 10) + 'px';
        break;
      // Down arrow
      case 40:
        // Move down
        player.style.top = (player.offsetTop + 10) + 'px';
        break;
    }
    
    // Check if the player has reached the target
    if (player.offsetLeft == target.offsetLeft &amp;&amp; player.offsetTop == target.offsetTop) {
      alert('You won!');
    }
  });
&lt;/script&gt;
</code></pre>
  </body>
</html>
Simple HTML Game: Move the Player to the Target

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

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