Changed around line 1
+ const canvas = document.getElementById('pongCanvas');
+ const ctx = canvas.getContext('2d');
+
+ const paddleWidth = 10, paddleHeight = 100;
+ const ballRadius = 10;
+
+ let paddle1Y = 250, paddle2Y = 250;
+ let ballX = 400, ballY = 300;
+ let ballSpeedX = 5, ballSpeedY = 5;
+
+ let upPressed = false, downPressed = false;
+ let arrowUpPressed = false, arrowDownPressed = false;
+
+ document.addEventListener('keydown', keyDownHandler);
+ document.addEventListener('keyup', keyUpHandler);
+
+ function keyDownHandler(e) {
+ if (e.key === 'w') upPressed = true;
+ if (e.key === 's') downPressed = true;
+ if (e.key === 'ArrowUp') arrowUpPressed = true;
+ if (e.key === 'ArrowDown') arrowDownPressed = true;
+ }
+
+ function keyUpHandler(e) {
+ if (e.key === 'w') upPressed = false;
+ if (e.key === 's') downPressed = false;
+ if (e.key === 'ArrowUp') arrowUpPressed = false;
+ if (e.key === 'ArrowDown') arrowDownPressed = false;
+ }
+
+ function drawPaddle(x, y) {
+ ctx.fillStyle = '#fff';
+ ctx.fillRect(x, y, paddleWidth, paddleHeight);
+ }
+
+ function drawBall() {
+ ctx.beginPath();
+ ctx.arc(ballX, ballY, ballRadius, 0, Math.PI * 2);
+ ctx.fillStyle = '#fff';
+ ctx.fill();
+ ctx.closePath();
+ }
+
+ function draw() {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+
+ drawPaddle(0, paddle1Y);
+ drawPaddle(canvas.width - paddleWidth, paddle2Y);
+ drawBall();
+
+ if (upPressed && paddle1Y > 0) paddle1Y -= 7;
+ if (downPressed && paddle1Y < canvas.height - paddleHeight) paddle1Y += 7;
+ if (arrowUpPressed && paddle2Y > 0) paddle2Y -= 7;
+ if (arrowDownPressed && paddle2Y < canvas.height - paddleHeight) paddle2Y += 7;
+
+ ballX += ballSpeedX;
+ ballY += ballSpeedY;
+
+ if (ballY + ballRadius > canvas.height || ballY - ballRadius < 0) {
+ ballSpeedY = -ballSpeedY;
+ }
+
+ if (ballX - ballRadius < paddleWidth && ballY > paddle1Y && ballY < paddle1Y + paddleHeight) {
+ ballSpeedX = -ballSpeedX;
+ }
+
+ if (ballX + ballRadius > canvas.width - paddleWidth && ballY > paddle2Y && ballY < paddle2Y + paddleHeight) {
+ ballSpeedX = -ballSpeedX;
+ }
+
+ if (ballX - ballRadius < 0 || ballX + ballRadius > canvas.width) {
+ resetBall();
+ }
+
+ requestAnimationFrame(draw);
+ }
+
+ function resetBall() {
+ ballX = canvas.width / 2;
+ ballY = canvas.height / 2;
+ ballSpeedX = -ballSpeedX;
+ }
+
+ draw();