|
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; |
|
let paddleRightY = window.innerHeight / 2 - 40; |
|
let ballX = window.innerWidth / 2; |
|
let ballY = window.innerHeight / 2; |
|
let ballSpeedX = 3; |
|
let ballSpeedY = 3; |
|
|
|
const paddleHeight = 80; |
|
const paddleWidth = 10; |
|
const ballSize = 15; |
|
|
|
|
|
let touchY = 0; |
|
|
|
gameArea.addEventListener('touchmove', (e) => { |
|
e.preventDefault(); |
|
touchY = e.touches[0].clientY; |
|
|
|
|
|
if (e.touches[0].clientX < window.innerWidth / 2) { |
|
paddleLeftY = touchY - paddleHeight / 2; |
|
if (paddleLeftY < 0) paddleLeftY = 0; |
|
if (paddleLeftY > window.innerHeight - paddleHeight) paddleLeftY = window.innerHeight - paddleHeight; |
|
} |
|
}); |
|
|
|
function update() { |
|
|
|
ballX += ballSpeedX; |
|
ballY += ballSpeedY; |
|
|
|
|
|
if (ballY <= 0 || ballY >= window.innerHeight - ballSize) { |
|
ballSpeedY = -ballSpeedY; |
|
} |
|
|
|
|
|
if ( |
|
ballX <= paddleWidth + 10 && |
|
ballY + ballSize >= paddleLeftY && |
|
ballY <= paddleLeftY + paddleHeight |
|
) { |
|
ballSpeedX = -ballSpeedX; |
|
} |
|
|
|
|
|
if ( |
|
ballX >= window.innerWidth - paddleWidth - 25 && |
|
ballY + ballSize >= paddleRightY && |
|
ballY <= paddleRightY + paddleHeight |
|
) { |
|
ballSpeedX = -ballSpeedX; |
|
} |
|
|
|
|
|
if (ballX <= 0 || ballX >= window.innerWidth) { |
|
resetBall(); |
|
} |
|
|
|
|
|
if (ballSpeedX > 0) { |
|
if (paddleRightY + paddleHeight / 2 < ballY) { |
|
paddleRightY += 3; |
|
} else if (paddleRightY + paddleHeight / 2 > ballY) { |
|
paddleRightY -= 3; |
|
} |
|
} |
|
|
|
|
|
if (paddleRightY < 0) paddleRightY = 0; |
|
if (paddleRightY > window.innerHeight - paddleHeight) paddleRightY = window.innerHeight - paddleHeight; |
|
|
|
|
|
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; |
|
} |
|
|
|
|
|
update(); |