const gameArea = document.getElementById('gameArea');
const ball = document.getElementById('ball'); let ballX = gameArea.offsetWidth / 2 - ball.offsetWidth / 2;
let ballY = gameArea.offsetHeight / 2 - ball.offsetHeight / 2;
let ballSpeedX = 0;
let ballSpeedY = 0;
const gravity = 0.5;
const bounceFactor = -0.8;
const maxSpeed = 10; function updateBallPosition() {
ballSpeedY += gravity;
ballX += ballSpeedX;
ballY += ballSpeedY; // Check for wall collisions
if (ballX < 0 || ballX + ball.offsetWidth > gameArea.offsetWidth) {
ballSpeedX *= bounceFactor;
ballX = Math.max(0, Math.min(gameArea.offsetWidth - ball.offsetWidth, ballX));
} // Check for ground collision
if (ballY + ball.offsetHeight > gameArea.offsetHeight) {
ballSpeedY *= bounceFactor;
ballY = gameArea.offsetHeight - ball.offsetHeight;
if (Math.abs(ballSpeedY) < 1) {
ballSpeedY = 0;
}
} // Apply speed limits
ballSpeedX = Math.max(-maxSpeed, Math.min(maxSpeed, ballSpeedX));
ballSpeedY = Math.max(-maxSpeed, Math.min(maxSpeed, ballSpeedY)); ball.style.left = `${ballX}px`;
ball.style.top = `${ballY}px`; requestAnimationFrame(updateBallPosition);
} ball.addEventListener('click', (event) => {
const clickX = event.offsetX;
const clickY = event.offsetY; // Calculate the direction of the bounce based on where the ball was tapped
const centerX = ball.offsetWidth / 2;
const centerY = ball.offsetHeight / 2;
const deltaX = clickX - centerX;
const deltaY = clickY - centerY; ballSpeedX = deltaX * 0.5; // Adjust the horizontal bounce
ballSpeedY = deltaY * -1; // Adjust the vertical bounce
}); // Initialize ball position
ball.style.left = `${ballX}px`;
ball.style.top = `${ballY}px`; // Start the game loop
updateBallPosition();