Pingpong / script.js
Gregniuki's picture
Update script.js
5994a14 verified
raw
history blame
2.57 kB
const gameArea = document.getElementById('gameArea');
const paddleLeft = document.getElementById('paddleLeft');
const paddleRight = document.getElementById('paddleRight');
const ball = document.getElementById('ball');
let paddleLeftY = window.innerHeight / 2 - 40; // Center the paddle
let paddleRightY = window.innerHeight / 2 - 40; // Center the paddle
let ballX = window.innerWidth / 2; // Center the ball
let ballY = window.innerHeight / 2; // Center the ball
let ballSpeedX = 3; // Horizontal speed
let ballSpeedY = 3; // Vertical speed
const paddleHeight = 80;
const paddleWidth = 10;
const ballSize = 15;
// Touch controls
let touchY = 0;
gameArea.addEventListener('touchmove', (e) => {
e.preventDefault();
touchY = e.touches[0].clientY;
// Move paddles based on touch position
if (e.touches[0].clientX < window.innerWidth / 2) {
// Left paddle
paddleLeftY = touchY - paddleHeight / 2;
if (paddleLeftY < 0) paddleLeftY = 0;
if (paddleLeftY > window.innerHeight - paddleHeight) paddleLeftY = window.innerHeight - paddleHeight;
} else {
// Right paddle
paddleRightY = touchY - paddleHeight / 2;
if (paddleRightY < 0) paddleRightY = 0;
if (paddleRightY > window.innerHeight - paddleHeight) paddleRightY = window.innerHeight - paddleHeight;
}
});
function update() {
// Update ball position
ballX += ballSpeedX;
ballY += ballSpeedY;
// Ball collision with top and bottom walls
if (ballY <= 0 || ballY >= window.innerHeight - ballSize) {
ballSpeedY = -ballSpeedY;
}
// Ball collision with paddles
if (
ballX <= paddleWidth + 10 && // Left paddle
ballY >= paddleLeftY &&
ballY <= paddleLeftY + paddleHeight
) {
ballSpeedX = -ballSpeedX;
}
if (
ballX >= window.innerWidth - paddleWidth - 10 && // Right paddle
ballY >= paddleRightY &&
ballY <= paddleRightY + paddleHeight
) {
ballSpeedX = -ballSpeedX;
}
// Ball out of bounds (left or right)
if (ballX <= 0 || ballX >= window.innerWidth) {
resetBall();
}
// Update ball and paddle positions
ball.style.left = ballX + 'px';
ball.style.top = ballY + 'px';
paddleLeft.style.top = paddleLeftY + 'px';
paddleRight.style.top = paddleRightY + 'px';
requestAnimationFrame(update);
}
function resetBall() {
ballX = window.innerWidth / 2;
ballY = window.innerHeight / 2;
ballSpeedX = -ballSpeedX; // Reverse direction
}
// Start the game loop
update();