This is an old revision of the document!

<!DOCTYPE html> <html lang=“en”> <head>

<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ping Pong Game</title>
<style>
  body {
    margin: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #000;
  }
  canvas {
    background-color: #111;
    display: block;
  }
</style>

Advertisement

</head> <body>

<canvas id="gameCanvas" width="800" height="400"></canvas>
<script>
  const canvas = document.getElementById('gameCanvas');
  const ctx = canvas.getContext('2d');
  const paddleWidth = 10;
  const paddleHeight = 100;
  let playerY = canvas.height / 2 - paddleHeight / 2;
  let aiY = canvas.height / 2 - paddleHeight / 2;
  const ballSize = 10;
  let ballX = canvas.width / 2;
  let ballY = canvas.height / 2;
  let ballSpeedX = 4;
  let ballSpeedY = 4;
  document.addEventListener('mousemove', (e) => {
    const rect = canvas.getBoundingClientRect();
    playerY = e.clientY - rect.top - paddleHeight / 2;
  });
  function drawRect(x, y, w, h, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x, y, w, h);
  }

Advertisement

  function drawBall(x, y, size, color) {
    ctx.fillStyle = color;
    ctx.fillRect(x, y, size, size);
  }
  function resetBall() {
    ballX = canvas.width / 2;
    ballY = canvas.height / 2;
    ballSpeedX = -ballSpeedX;
    ballSpeedY = 4 * (Math.random() > 0.5 ? 1 : -1);
  }
  function update() {
    // Move ball
    ballX += ballSpeedX;
    ballY += ballSpeedY;
    // Bounce off top and bottom
    if (ballY <= 0 || ballY + ballSize >= canvas.height) {
      ballSpeedY = -ballSpeedY;
    }
    // Player paddle collision
    if (
      ballX <= paddleWidth &&
      ballY + ballSize >= playerY &&
      ballY <= playerY + paddleHeight
    ) {
      ballSpeedX = -ballSpeedX;
    }
    // AI paddle collision
    if (
      ballX + ballSize >= canvas.width - paddleWidth &&
      ballY + ballSize >= aiY &&
      ballY <= aiY + paddleHeight
    ) {
      ballSpeedX = -ballSpeedX;
    }

Advertisement

    // Score and reset
    if (ballX <= 0 || ballX + ballSize >= canvas.width) {
      resetBall();
    }
    // AI movement
    const aiCenter = aiY + paddleHeight / 2;
    if (aiCenter < ballY) aiY += 4;
    else aiY -= 4;
  }
  function draw() {
    drawRect(0, 0, canvas.width, canvas.height, '#111');
    drawRect(0, playerY, paddleWidth, paddleHeight, '#0f0');
    drawRect(canvas.width - paddleWidth, aiY, paddleWidth, paddleHeight, '#f00');
    drawBall(ballX, ballY, ballSize, '#fff');
  }
  function gameLoop() {
    update();
    draw();
    requestAnimationFrame(gameLoop);
  }
  gameLoop();
</script>

</body> </html>

Last modified: by 5.36.185.252