Home What I do Work Playground Toolbox About Contact Shop ↗ DEEN

Playground · mini game

Ping-pong against the computer

A complete game in one HTML file, built from a single prompt. Mouse or finger, on a PC or a phone.

Open in a new tab ↗ Download as a file

The prompt

Copy it and paste it into Claude, ChatGPT or Gemini. The AI answers with the complete code.

Build me a ping-pong game against the computer as a single HTML file, no external libraries.
- Dark background, paddles and ball glow green.
- I control my paddle with the mouse or with my finger on a phone.
- In landscape I play on the left, in portrait at the bottom. The court adapts to any screen size.
- The computer makes the occasional mistake, so you can actually win.
- The ball gets a little faster after every hit.
- Big score in the background. First to 7 points wins, then "Play again" with a click or tap.

How to run it

  1. Copy the code from the AI's answer (there is usually a copy button on the code block).
  2. Open a text editor, Notepad for example, paste the code and save it as ping-pong.html. The .html ending is what matters.
  3. Double-click the file. It opens in your browser, done. No server, no install.

Fixed afterwards

After the first test, these follow-ups were added. Same chat, simply as the next message:

At high speed the ball sometimes slips through the paddle. Please fix that.
The computer is too easy to beat. Let it miss a little less often.
When the mouse leaves the court, I can't move my paddle any more. Capture the mouse on click (Pointer Lock) and pause with Esc or P: a click resumes, R restarts. Also pause when the window loses focus.
While playing, show "Esc or click: pause" small at the top. A mouse click during the game should also pause and release the mouse.

The code

This is the code that came out of the prompt and the follow-ups above (with Claude). Every AI builds it a little differently, that's normal. If your version doesn't run, paste the error message or a description back into the chat.

Show code (295 lines)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ping-Pong</title>
<style>
  html, body { margin: 0; height: 100%; background: #07090a; overflow: hidden; }
  canvas { display: block; width: 100%; height: 100%; touch-action: none; cursor: pointer; }
</style>
</head>
<body>
<canvas id="court"></canvas>
<script>
const canvas = document.getElementById('court');
const ctx = canvas.getContext('2d');

const GREEN = '#5abe41';
const TARGET = 7;               // points to win
const TEXT = {
  title: 'Ping-Pong',
  start: 'Click or tap to start',
  keys: 'Esc or click: pause',
  pause: 'Paused',
  resume: 'Click: resume · R: restart',
  you: 'You win!',
  computer: 'The computer wins',
  again: 'Play again: click or tap'
};

// The court is always computed "lying down": x runs from my paddle (left) to the computer (right).
// In portrait it is rotated when drawing, so I play at the bottom.
let dpr, sw, sh, portrait, W, H;
let length, thickness, margin, radius;
let player, computer, ball, score;
let state;                      // 'start', 'play', 'pause' or 'over'
let withMouse = false;          // last played with the mouse? Then the pause hint shows at the top while playing

function resize() {
  dpr = window.devicePixelRatio || 1;
  sw = window.innerWidth;
  sh = window.innerHeight;
  canvas.width = Math.round(sw * dpr);
  canvas.height = Math.round(sh * dpr);
  portrait = sh > sw;
  W = portrait ? sh : sw;       // distance between the paddles
  H = portrait ? sw : sh;       // width of the court
  length = H * 0.2;
  thickness = Math.max(10, W * 0.014);
  margin = W * 0.04;
  radius = Math.max(6, Math.min(W, H) * 0.016);
}

function setState(next) {
  state = next;
  canvas.style.cursor = next === 'play' ? 'none' : 'pointer';
}

function newGame(next) {
  player = { y: H / 2 };
  computer = { y: H / 2, error: 0 };
  score = [0, 0];
  setState(next);
  serve(Math.random() < 0.5 ? 1 : -1);
}

function serve(direction) {
  const speed = W * 0.55;
  const angle = (Math.random() - 0.5) * 0.9;
  ball = {
    x: W / 2, y: H / 2,
    vx: direction * speed * Math.cos(angle),
    vy: speed * Math.sin(angle),
    wait: 0.8                   // short pause before the serve
  };
  computer.error = (Math.random() - 0.5) * length * 1.2;
}

// When the ball bounces off a paddle, the spot it hits sets the new angle
function bounce(paddleY, direction) {
  const spot = Math.max(-1, Math.min(1, (ball.y - paddleY) / (length / 2)));
  const speed = Math.min(Math.hypot(ball.vx, ball.vy) * 1.06, W * 1.4);
  const angle = spot * 1.0;
  ball.vx = direction * speed * Math.cos(angle);
  ball.vy = speed * Math.sin(angle);
}

function step(dt) {
  if (state !== 'play') return;

  // Computer: follows the ball, but with limited speed and a small aiming error
  const target = ball.vx > 0 ? ball.y + computer.error : H / 2;
  const maxMove = H * 0.85 * dt;
  computer.y += Math.max(-maxMove, Math.min(maxMove, target - computer.y));
  computer.y = Math.max(length / 2, Math.min(H - length / 2, computer.y));

  if (ball.wait > 0) { ball.wait -= dt; return; }

  // Move in small steps, so a fast ball can't slip through a paddle
  const parts = Math.ceil(Math.hypot(ball.vx, ball.vy) * dt / (radius * 0.5));
  for (let i = 0; i < parts && ball.wait <= 0 && state === 'play'; i++) ballStep(dt / parts);
}

function ballStep(dt) {
  ball.x += ball.vx * dt;
  ball.y += ball.vy * dt;

  // Walls
  if (ball.y < radius) { ball.y = radius; ball.vy = Math.abs(ball.vy); }
  if (ball.y > H - radius) { ball.y = H - radius; ball.vy = -Math.abs(ball.vy); }

  // My paddle
  const frontLeft = margin + thickness;
  if (ball.vx < 0 && ball.x - radius <= frontLeft && ball.x > margin - radius &&
      Math.abs(ball.y - player.y) <= length / 2 + radius) {
    ball.x = frontLeft + radius;
    bounce(player.y, 1);
    computer.error = (Math.random() - 0.5) * length * 1.2;
  }

  // Computer's paddle
  const frontRight = W - margin - thickness;
  if (ball.vx > 0 && ball.x + radius >= frontRight && ball.x < W - margin + radius &&
      Math.abs(ball.y - computer.y) <= length / 2 + radius) {
    ball.x = frontRight - radius;
    bounce(computer.y, -1);
  }

  // Point
  if (ball.x < -radius * 2) point(1);
  if (ball.x > W + radius * 2) point(0);
}

function point(who) {
  score[who]++;
  if (score[who] >= TARGET) {
    setState('over');
    release();
  } else {
    serve(who === 0 ? 1 : -1);
  }
}

// Court coordinates to screen coordinates (for text)
function toScreen(x, y) {
  return portrait ? [y, sh - x] : [x, y];
}

// Dimmed overlay with one big line and small lines below
function notice(big, ...small) {
  const m = Math.min(sw, sh);
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.fillStyle = 'rgba(7, 9, 10, 0.7)';
  ctx.fillRect(0, 0, sw, sh);
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillStyle = '#eef5ea';
  ctx.font = `600 ${Math.round(m * 0.08)}px system-ui, sans-serif`;
  ctx.fillText(big, sw / 2, sh / 2 - m * 0.04);
  ctx.font = `${Math.round(m * 0.04)}px system-ui, sans-serif`;
  small.forEach((line, i) => {
    ctx.fillStyle = i === 0 ? GREEN : 'rgba(238, 245, 234, 0.55)';
    ctx.fillText(line, sw / 2, sh / 2 + m * (0.05 + i * 0.065));
  });
}

function draw() {
  ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  ctx.fillStyle = '#07090a';
  ctx.fillRect(0, 0, sw, sh);

  // Big score in the background
  ctx.fillStyle = 'rgba(90, 190, 65, 0.16)';
  ctx.font = `600 ${Math.round(Math.min(W, H) * 0.32)}px system-ui, sans-serif`;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  for (const [who, x] of [[0, W * 0.25], [1, W * 0.75]]) {
    const [sx, sy] = toScreen(x, H / 2);
    ctx.fillText(score[who], sx, sy);
  }

  // from here on, draw on the court (rotated in portrait)
  if (portrait) ctx.setTransform(0, -dpr, dpr, 0, 0, sh * dpr);

  ctx.strokeStyle = 'rgba(90, 190, 65, 0.3)';
  ctx.lineWidth = 2;
  ctx.setLineDash([12, 14]);
  ctx.beginPath();
  ctx.moveTo(W / 2, 0);
  ctx.lineTo(W / 2, H);
  ctx.stroke();
  ctx.setLineDash([]);

  ctx.shadowColor = GREEN;
  ctx.shadowBlur = 18;
  ctx.fillStyle = GREEN;
  ctx.fillRect(margin, player.y - length / 2, thickness, length);
  ctx.fillRect(W - margin - thickness, computer.y - length / 2, thickness, length);

  if (state !== 'over') {
    ctx.fillStyle = '#d8ffc8';
    ctx.beginPath();
    ctx.arc(ball.x, ball.y, radius, 0, Math.PI * 2);
    ctx.fill();
  }
  ctx.shadowBlur = 0;

  // While playing with the mouse: a small line at the top on how to get out again
  if (state === 'play' && withMouse) {
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.fillStyle = 'rgba(238, 245, 234, 0.5)';
    ctx.font = `${Math.round(Math.max(12, Math.min(sw, sh) * 0.03))}px system-ui, sans-serif`;
    ctx.fillText(TEXT.keys, sw / 2, portrait ? sh * 0.12 : Math.max(16, sh * 0.04));
  }

  if (state === 'start') notice(TEXT.title, TEXT.start, TEXT.keys);
  if (state === 'pause') notice(TEXT.pause, TEXT.resume);
  if (state === 'over') notice(score[0] > score[1] ? TEXT.you : TEXT.computer, TEXT.again);
}

// Capture the mouse (Pointer Lock): it can no longer leave the court.
// Esc releases it again, and the game pauses.
function capture(e) {
  if (e.pointerType !== 'mouse' || !canvas.requestPointerLock) return;
  const attempt = canvas.requestPointerLock();
  if (attempt && attempt.catch) attempt.catch(() => {});
}

function release() {
  if (document.pointerLockElement === canvas) document.exitPointerLock();
}

function pause() {
  if (state !== 'play') return;
  setState('pause');
  release();
}

// Controls: with a captured mouse the movement counts, otherwise the position of mouse or finger
function move(e) {
  if (state !== 'play') return;
  if (document.pointerLockElement === canvas) {
    player.y += portrait ? e.movementX : e.movementY;
  } else {
    player.y = portrait ? e.clientX : e.clientY;
  }
  player.y = Math.max(length / 2, Math.min(H - length / 2, player.y));
}

window.addEventListener('pointermove', move);
window.addEventListener('pointerdown', (e) => {
  withMouse = e.pointerType === 'mouse';
  // A mouse click while playing pauses and releases the mouse (a finger only steers)
  if (state === 'play' && withMouse) { pause(); return; }
  if (state === 'over') newGame('play');
  else if (state !== 'play') setState('play');
  capture(e);
  move(e);
});
document.addEventListener('pointerlockchange', () => {
  if (document.pointerLockElement !== canvas) pause();
});
window.addEventListener('keydown', (e) => {
  if (e.key === 'Escape' || e.key === 'p' || e.key === 'P') pause();
  if ((e.key === 'r' || e.key === 'R') && state !== 'play') newGame('start');
});
// Leaving the window, another tab, or the mouse leaving the court without capture: pause, so no point is lost
window.addEventListener('blur', pause);
document.addEventListener('visibilitychange', () => { if (document.hidden) pause(); });
document.documentElement.addEventListener('mouseleave', () => {
  if (document.pointerLockElement !== canvas) pause();
});

window.addEventListener('resize', () => {
  resize();
  player.y = computer.y = H / 2;
  if (state !== 'over') serve(ball.vx > 0 ? 1 : -1);
});

let last = performance.now();
function loop(now) {
  const dt = Math.min(0.033, (now - last) / 1000);
  last = now;
  step(dt);
  draw();
  requestAnimationFrame(loop);
}

resize();
newGame('start');
requestAnimationFrame(loop);
</script>
</body>
</html>

Download as a file

Keep building

A few ideas for your next message in the same chat:

Add sound: a short click when the ball hits a paddle and a lower tone for every point. Web Audio API only, no files.
Let the ball leave a glowing trail that fades quickly.
Add three difficulty levels to tap before the game starts: easy, medium, hard.
Turn it into a two-player game on one device: left uses W and S, right uses arrow up and down.

← All games

↑ Back to top