Ping Pong Game

by slawe

HTML

<h1>🏓 Ping Pong Game vs Auto Player</h1>
<canvas id="game" width="500" height="400"></canvas>
<div class="info">
  Score: <span id="score">0</span> | Level: <span id="level">1</span>
</div>

CSS

body {
  background: #111;
  color: white;
  font-family: Arial, sans-serif;
  text-align: center;
  margin: 0;
  padding: 20px;
}
canvas {
  background: black;
  display: block;
  margin: 0 auto;
  border: 2px solid white;
}
.info {
  margin-top: 10px;
  font-size: 18px;
}

JavaScript

const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");

const paddleWidth = 80, paddleHeight = 10;
const player = {
  x: canvas.width / 2 - paddleWidth / 2,
  y: canvas.height - 20,
  width: paddleWidth,
  height: paddleHeight,
  speed: 7,
  dx: 0,
};

const ai = {
  x: canvas.width / 2 - paddleWidth / 2,
  y: 10,
  width: paddleWidth,
  height: paddleHeight,
  speed: 5
};

const ball = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  radius: 8,
  dx: 3,
  dy: 3,
  speed: 3
};

let score = 0;
let level = 1;
let gameLoop;

function drawPaddle(paddle) {
  ctx.fillStyle = "white";
  ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}

function drawBall() {
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
  ctx.fillStyle = "red";
  ctx.fill();
  ctx.closePath();
}

function movePlayer() {
  player.x += player.dx;
  if (player.x < 0) player.x = 0;
  if (player.x + player.width > canvas.width) player.x = canvas.width - player.width;
}

function moveAI() {
  const targetX = ball.x - ai.width / 2;
  if (ai.x < targetX) ai.x += ai.speed;
  else if (ai.x > targetX) ai.x -= ai.speed;

  // clamp
  ai.x = Math.max(0, Math.min(canvas.width - ai.width, ai.x));
}

function moveBall() {
  ball.x += ball.dx;
  ball.y += ball.dy;

  // Wall bounce
  if (ball.x - ball.radius < 0 || ball.x + ball.radius > canvas.width) {
    ball.dx *= -1;
  }

  // AI paddle
  if (
    ball.y - ball.radius <= ai.y + ai.height &&
    ball.x > ai.x &&
    ball.x < ai.x + ai.width
  ) {
    ball.dy *= -1;
  }

  // Player paddle
  if (
    ball.y + ball.radius >= player.y &&
    ball.x > player.x &&
    ball.x < player.x + player.width
  ) {
    ball.dy *= -1;
    score++;
    document.getElementById("score").innerText = score;

    if (score % 5 === 0) {
      level++;
      document.getElementById("level").innerText = level;
      ball.dx *= 1.1;
      ball.dy *= 1.1;
    }
  }

  // Game Over
  if (ball.y + ball.radius >...