<html>
<head>
  <title>Ping Pong Game</title>
</head>
<body>
  <div>
    <h1>Ping Pong Game</h1>
    <div>
      <div>
        <canvas id='game-board' height='400' width='600'></canvas>
      </div>
    </div>
  </div>
  <script>
    const canvas = document.getElementById('game-board');
    const ctx = canvas.getContext('2d');
<pre><code>let ballX = canvas.width/2;
let ballY = canvas.height/2;
let ballSpeedX = 5;
let ballSpeedY = 5;

const PADDLE_WIDTH = 100;
const PADDLE_THICKNESS = 10;
const PADDLE_DIST_FROM_EDGE = 50;
let paddleX = 400;

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

function drawCircle(x, y, radius, color) {
  ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2, true);
  ctx.fill();
}

function calculateMousePos(evt) {
  let rect = canvas.getBoundingClientRect();
  let root = document.documentElement;
  let mouseX = evt.clientX - rect.left - root.scrollLeft;
  let mouseY = evt.clientY - rect.top - root.scrollTop;
  return {
    x: mouseX,
    y: mouseY
  };
}

window.onmousemove = function(evt) {
  let mousePos = calculateMousePos(evt);
  paddleX = mousePos.x - PADDLE_WIDTH/2;
}

// Main game loop
function drawGame() {
  // Draw game board
  drawRect(0, 0, canvas.width, canvas.height, 'black');

  // Draw ball
  drawCircle(ballX, ballY, 10, 'green');

  // Draw paddle
  drawRect(paddleX, canvas.height - PADDLE_DIST_FROM_EDGE, PADDLE_WIDTH, PADDLE_THICKNESS, 'red');

  // Move ball
  ballX += ballSpeedX;
  ballY += ballSpeedY;

  // Bounce ball off left/right walls
  if (ballX &gt; canvas.width || ballX &lt; 0) {
    ballSpeedX *= -1;
  }
  // Bounce ball off top/bottom walls
  if (ballY &gt; canvas.height || ballY &lt; 0) {
    ballSpeedY *= -1;
  }
  // Bounce ball off paddle
  if (ballY &gt; canvas.height - PADDLE_DIST_FROM_EDGE &amp;&amp;
      ballX &gt; paddleX &amp;&amp;
      ballX &lt; paddleX + PADDLE_WIDTH) {
    ballSpeedY *= -1;
  }
}

setInterval(drawGame, 1000/30);
</code></pre>
  </script>
</body>
</html>
Simple HTML Ping Pong Game - No Instructions

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

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