Skip to content

Commit bc5556a

Browse files
Update script.js
1 parent 7b5fa07 commit bc5556a

1 file changed

Lines changed: 13 additions & 10 deletions

File tree

ping-pong/script.js

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,17 @@ function resizeCanvas() {
66
const height = Math.min(window.innerWidth * 0.5, 400);
77
canvas.width = width;
88
canvas.height = height;
9+
// Recenter paddles and ball after resize
10+
leftY = canvas.height / 2 - PADDLE_HEIGHT / 2;
11+
rightY = canvas.height / 2 - PADDLE_HEIGHT / 2;
12+
ballX = canvas.width / 2;
13+
ballY = canvas.height / 2;
914
}
10-
resizeCanvas();
11-
window.addEventListener('resize', resizeCanvas);
12-
1315
const PADDLE_WIDTH = 10;
1416
const PADDLE_HEIGHT = 70;
1517
const BALL_RADIUS = 8;
1618

17-
let leftY = canvas.height / 2 - PADDLE_HEIGHT / 2;
18-
let rightY = canvas.height / 2 - PADDLE_HEIGHT / 2;
19-
let ballX = canvas.width / 2;
20-
let ballY = canvas.height / 2;
19+
let leftY, rightY, ballX, ballY;
2120
let ballSpeedX = 4;
2221
let ballSpeedY = 3;
2322
let leftScore = 0;
@@ -27,6 +26,9 @@ let upPressed = false, downPressed = false, wPressed = false, sPressed = false;
2726
// Simple AI difficulty (pixels per frame)
2827
const AI_SPEED = 5;
2928

29+
resizeCanvas();
30+
window.addEventListener('resize', resizeCanvas);
31+
3032
function draw() {
3133
ctx.clearRect(0, 0, canvas.width, canvas.height);
3234

@@ -67,9 +69,10 @@ function update() {
6769
leftY = Math.max(0, Math.min(canvas.height - PADDLE_HEIGHT, leftY));
6870

6971
// AI paddle movement (right)
70-
if (rightY + PADDLE_HEIGHT/2 < ballY - 10) {
72+
let aiCenter = rightY + PADDLE_HEIGHT / 2;
73+
if (aiCenter < ballY - 10) {
7174
rightY += AI_SPEED;
72-
} else if (rightY + PADDLE_HEIGHT/2 > ballY + 10) {
75+
} else if (aiCenter > ballY + 10) {
7376
rightY -= AI_SPEED;
7477
}
7578
rightY = Math.max(0, Math.min(canvas.height - PADDLE_HEIGHT, rightY));
@@ -145,4 +148,4 @@ document.getElementById('restartBtn').onclick = function() {
145148

146149
canvas.focus();
147150
draw();
148-
update(); // Game starts immediately!
151+
update(); // Game starts immediately!

0 commit comments

Comments
 (0)