<html>
  <title>Ping Pong</title>
  <body>
    <div style='width: 300px; height: 300px; background-color: black;'>
      <div id='player1' style='width: 10px; height: 50px; background-color: red; position: absolute; top: 125px; left: 10px;'></div>
      <div id='player2' style='width: 10px; height: 50px; background-color: blue; position: absolute; top: 125px; right: 10px;'></div>
      <div id='ball' style='width: 10px; height: 10px; background-color: white; position: absolute; top: 50px; left: 145px;'></div>
    </div>
    <script>
      document.onkeydown = checkKey;
      let top1 = 125;
      let top2 = 125;
      let left = 145;
      let top = 50;
      let dir = 1;
<pre><code>  function checkKey(e) {
    e = e || window.event;

    if (e.keyCode == '38') {
  top2 -= 10;
  if (top2 &lt; 0) top2 = 0;
    }
    else if (e.keyCode == '40') {
  top2 += 10;
  if (top2 &gt; 250) top2 = 250;
    }
    else if (e.keyCode == '87') {
  top1 -= 10;
  if (top1 &lt; 0) top1 = 0;
    }
    else if (e.keyCode == '83') {
  top1 += 10;
  if (top1 &gt; 250) top1 = 250;
    }

document.getElementById('player1').style.top = top1 + 'px';
document.getElementById('player2').style.top = top2 + 'px';

left += 10 * dir;

  if (left &gt; 290) {
    if (top2 &lt; top + 10 &amp;&amp; top2 &gt; top - 50) {
      dir = -1;
    } else {
      alert('Player 1 wins!');
      document.location.reload();
    }
  }

  if (left &lt; 10) {
    if (top1 &lt; top + 10 &amp;&amp; top1 &gt; top - 50) {
      dir = 1;
    } else {
      alert('Player 2 wins!');
      document.location.reload();
    }
  }

  top += Math.random() * 20 - 10;
  if (top &lt; 0) top = 0;
  if (top &gt; 290) top = 290;

  document.getElementById('ball').style.left = left + 'px';
  document.getElementById('ball').style.top = top + 'px';
  }
&lt;/script&gt;
</code></pre>
  </body>
</html>
Simple HTML Ping Pong Game: No Instructions Needed

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

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