function resetBall() {
ballX = canvas.width / 2 - ballSize / 2;
ballY = canvas.height / 2 - ballSize / 2;
ballSpeedX = -ballSpeedX;
ballSpeedY = 3 * (Math.random() > 0.5 ? 1 : -1);
}
function update() {
// Move ball
ballX += ballSpeedX;
ballY += ballSpeedY;
// Collisions with top/bottom walls
if (ballY < 0 || ballY + ballSize > canvas.height) ballSpeedY = -ballSpeedY;
// Collisions with paddles
if (ballX < paddleWidth && ballY + ballSize > playerY && ballY < playerY + paddleHeight) {
ballSpeedX = -ballSpeedX;
}
if (ballX + ballSize > canvas.width - paddleWidth && ballY + ballSize > botY && ballY < botY + paddleHeight) {
ballSpeedX = -ballSpeedX;
}
// Ball out of bounds
if (ballX < 0 || ballX + ballSize > canvas.width) resetBall();
moveBot();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw paddles
ctx.fillStyle = 'white';
ctx.fillRect(0, playerY, paddleWidth, paddleHeight);
ctx.fillRect(canvas.width - paddleWidth, botY, paddleWidth, paddleHeight);
// Draw ball
ctx.fillRect(ballX, ballY, ballSize, ballSize);
}
function loop() {
update();
draw();
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>