<html>
  <head>
    <title>Simple HTML Game: Create Your Own</title>
    <style type="text/css">
      #game {
        width: 400px;
        height: 300px;
        background-color: #ccc;
        position: relative;
      }
      #player {
        width: 50px;
        height: 50px;
        background-color: red;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <h1>Simple HTML Game: Create Your Own</h1>
    <div id="game">
      <div id="player"></div>
    </div>
    <script>
      let game = document.getElementById('game');
      let player = document.getElementById('player');
      let speed = 5;
<pre><code>  document.onkeydown = function(event) {
    let x = player.offsetLeft;
    let y = player.offsetTop;
    
    switch (event.keyCode) {
      case 37: // left
        x -= speed;
        break;
      case 38: // up
        y -= speed;
        break;
      case 39: // right
        x += speed;
        break;
      case 40: // down
        y += speed;
        break;
    }
    
    // check if player is outside the game area
    if (x &gt; game.offsetWidth - player.offsetWidth) x = game.offsetWidth - player.offsetWidth;
    if (y &gt; game.offsetHeight - player.offsetHeight) y = game.offsetHeight - player.offsetHeight;
    if (x &lt; 0) x = 0;
    if (y &lt; 0) y = 0;
    
    player.style.left = x + 'px';
    player.style.top = y + 'px';
  }
&lt;/script&gt;
</code></pre>
  </body>
</html>
Simple HTML Game: Create Your Own with Code

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

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