Pong 3: Score & Computer Opponent
Our Pong from Pong 2 plays well, but nobody wins and you need a friend to play it. This step adds three things: a score, a proper serve with a short pause after each point, and a computer opponent that controls the right paddle until a second player joins.
Scoring and serving
When the ball leaves the court on the left, the right player scores, and vice versa. Instead of firing the ball immediately we park it in the middle for a second, so the players can see the score change and get ready. The serve goes toward the player who just lost the point, which is the usual table-tennis courtesy.
const score = { left: 0, right: 0 };
let serveTimer = 1, serveDir = 1;
function serve(dir) {
ball.x = W / 2 - ball.size / 2;
ball.y = H / 2 - ball.size / 2;
ball.vx = ball.vy = 0; // wait in the middle
serveDir = dir;
serveTimer = 1; // seconds
}serveTimer is a countdown timer, the simplest and most useful timing tool in games. Each update subtracts dt; when it crosses zero, something happens. No setTimeout needed, and the timer automatically stops when the game is paused, because update stops being called.
A computer opponent
A computer player that is perfect is no fun: if the paddle always moves to the ball's position, it never misses. Good game AI is about believable limits. Ours has three:
| Limit | Effect |
|---|---|
Top speed AI_SPEED slower than the player's |
a steep ball can outrun it |
| Only chases the ball when it is coming toward it; otherwise drifts back to the centre | it "relaxes" like a human |
| A dead zone of a few pixels | it doesn't twitch when it is already close |
Here is the same follow logic as a pure function, run for a few updates against a ball that sits at y = 200:
const AI_SPEED = 190, DEAD_ZONE = 6, DT = 1 / 60, PADDLE_H = 50;
function followTarget(paddleY, targetY) {
const diff = targetY - (paddleY + PADDLE_H / 2);
if (Math.abs(diff) <= DEAD_ZONE) return paddleY;
return paddleY + Math.sign(diff) * Math.min(AI_SPEED * DT, Math.abs(diff));
}
let y = 110; // paddle centre starts at 135
for (let step = 1; step <= 30; step++) {
y = followTarget(y, 200);
if (step % 6 === 0) console.log(`after ${step} updates: centre at ${(y + PADDLE_H / 2).toFixed(1)}`);
}after 6 updates: centre at 154.0
after 12 updates: centre at 173.0
after 18 updates: centre at 192.0
after 24 updates: centre at 195.2
after 30 updates: centre at 195.2
The paddle moves 190/60 ≈ 3.17 px per update and stops once it is within the 6 px dead zone. Tune AI_SPEED and DEAD_ZONE and you have difficulty levels.
The playable step
Play against the computer with W/S. Press 2 to switch the right paddle to a second human on ↑/↓, and 2 again to switch back:
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
// ---- Pong, step 3: score, serve and a computer opponent ----
const PADDLE_W = 8, PADDLE_H = 50, PADDLE_SPEED = 260;
const BALL_SPEED = 220, SPEEDUP = 1.06, MAX_SPEED = 520, MAX_ANGLE = Math.PI / 3;
const AI_SPEED = 190, AI_DEAD_ZONE = 6;
const left = { x: 16, y: H / 2 - PADDLE_H / 2 };
const right = { x: W - 16 - PADDLE_W, y: H / 2 - PADDLE_H / 2 };
const ball = { x: 0, y: 0, size: 8, vx: 0, vy: 0 };
const score = { left: 0, right: 0 };
let serveTimer = 0, serveDir = 1, twoPlayers = false;
function serve(dir) {
ball.x = W / 2 - ball.size / 2;
ball.y = H / 2 - ball.size / 2;
ball.vx = ball.vy = 0;
serveDir = dir;
serveTimer = 1;
}
serve(Math.random() < 0.5 ? -1 : 1);
function movePaddle(p, up, down, dt) {
if (keys.has(up)) p.y -= PADDLE_SPEED * dt;
if (keys.has(down)) p.y += PADDLE_SPEED * dt;
p.y = Math.max(0, Math.min(H - PADDLE_H, p.y));
}
function computerPaddle(p, dt) {
// Chase the ball only while it comes toward us; otherwise drift back to the centre.
const target = ball.vx > 0 ? ball.y + ball.size / 2 : H / 2;
const diff = target - (p.y + PADDLE_H / 2);
if (Math.abs(diff) > AI_DEAD_ZONE) p.y += Math.sign(diff) * Math.min(AI_SPEED * dt, Math.abs(diff));
p.y = Math.max(0, Math.min(H - PADDLE_H, p.y));
}
function hits(b, p) {
return b.x < p.x + PADDLE_W && b.x + b.size > p.x &&
b.y < p.y + PADDLE_H && b.y + b.size > p.y;
}
function bounceOff(p, dir) {
const offset = (ball.y + ball.size / 2 - (p.y + PADDLE_H / 2)) / (PADDLE_H / 2);
const angle = Math.max(-1, Math.min(1, offset)) * MAX_ANGLE;
const speed = Math.min(Math.hypot(ball.vx, ball.vy) * SPEEDUP, MAX_SPEED);
ball.vx = dir * speed * Math.cos(angle);
ball.vy = speed * Math.sin(angle);
}
function update(dt) {
if (pressed.has('Digit2')) twoPlayers = !twoPlayers;
movePaddle(left, 'KeyW', 'KeyS', dt);
if (twoPlayers) movePaddle(right, 'ArrowUp', 'ArrowDown', dt);
else computerPaddle(right, dt);
if (serveTimer > 0) { // waiting to serve
serveTimer -= dt;
if (serveTimer <= 0) {
const angle = (Math.random() - 0.5) * 0.8; // up to about ±23°
ball.vx = serveDir * BALL_SPEED * Math.cos(angle);
ball.vy = BALL_SPEED * Math.sin(angle);
}
return;
}
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }
if (ball.y + ball.size > H) { ball.y = H - ball.size; ball.vy = -Math.abs(ball.vy); }
if (ball.vx < 0 && hits(ball, left)) { ball.x = left.x + PADDLE_W; bounceOff(left, 1); }
if (ball.vx > 0 && hits(ball, right)) { ball.x = right.x - ball.size; bounceOff(right, -1); }
if (ball.x + ball.size < 0) { score.right++; serve(-1); } // serve toward the loser
if (ball.x > W) { score.left++; serve(1); }
}
function draw() {
ctx.fillStyle = '#0e1018';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#2a2f45';
for (let y = 4; y < H; y += 16) ctx.fillRect(W / 2 - 1, y, 2, 8);
ctx.fillStyle = '#5c6380';
ctx.font = 'bold 36px ui-monospace, monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
ctx.fillText(score.left, W / 2 - 50, 12);
ctx.fillText(score.right, W / 2 + 50, 12);
ctx.font = '11px system-ui, sans-serif';
ctx.fillText(twoPlayers ? '2 players (press 2)' : 'vs computer (press 2)', W / 2, H - 16);
ctx.fillStyle = '#e8eaf6';
ctx.fillRect(Math.round(left.x), Math.round(left.y), PADDLE_W, PADDLE_H);
ctx.fillRect(Math.round(right.x), Math.round(right.y), PADDLE_W, PADDLE_H);
// Blink the ball while it waits to be served.
if (serveTimer <= 0 || Math.floor(serveTimer * 6) % 2 === 0) {
ctx.fillStyle = '#ffb74d';
ctx.fillRect(Math.round(ball.x), Math.round(ball.y), ball.size, ball.size);
}
}
run(update, draw, 'W/S to move · 2 toggles a second player (↑/↓)');
</script>Things to notice
updatereturns early whileserveTimer > 0. Everything below it (ball movement, collisions, scoring) is skipped, but the paddles still move, so players can line up for the serve.- The serve angle uses
Math.random(), so every rally starts a little differently. Randomness is fine in the game; it's only our printed examples that must be deterministic. pressed.has('Digit2')reacts once per key press, whilekeys.has(...)is true for as long as the key is held. Usepressedfor toggles and menu choices,keysfor movement.- The blinking ball is a tiny piece of feedback: it tells the players "a serve is coming" without any text.
Tip: Want a harder opponent? Raise
AI_SPEEDto 240 or make it aim for where the ball will be (predict the bounce off the walls). Want an easier one? Add a reaction delay: ignore the ball until it crosses the centre line.
Test yourself
Why use a serveTimer decremented by dt instead of setTimeout?
setTimeoutdoesn't exist in iframes- The timer lives in game time: it pauses with the game and stays in sync with updates
- It is more accurate than the system clock
- Timers can't be cancelled
Which set should a "toggle two-player mode" key use?
keys(held keys)pressed(pressed since the last update)- Either; they are the same
- Neither; use
keyup
What makes the computer paddle beatable?
- It reads the keyboard
- Its top speed is limited, it only chases an approaching ball and it has a dead zone
- It is random
- It moves only every other frame