File size: 2,136 Bytes
a3b97ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const gameArea = document.getElementById('gameArea');
const paddleLeft = document.getElementById('paddleLeft');
const paddleRight = document.getElementById('paddleRight');
const ball = document.getElementById('ball');

let paddleLeftY = 160;
let paddleRightY = 160;
let ballX = 195;
let ballY = 195;
let ballSpeedX = 2;
let ballSpeedY = 2;

const paddleSpeed = 10;
const paddleHeight = 80;
const gameHeight = 400;
const gameWidth = 400;

function update() {
    // Update ball position
    ballX += ballSpeedX;
    ballY += ballSpeedY;

    // Ball collision with top and bottom walls
    if (ballY <= 0 || ballY >= gameHeight - 15) {
        ballSpeedY = -ballSpeedY;
    }

    // Ball collision with paddles
    if (ballX <= 20 && ballY >= paddleLeftY && ballY <= paddleLeftY + paddleHeight) {
        ballSpeedX = -ballSpeedX;
    }
    if (ballX >= gameWidth - 35 && ballY >= paddleRightY && ballY <= paddleRightY + paddleHeight) {
        ballSpeedX = -ballSpeedX;
    }

    // Ball out of bounds
    if (ballX <= 0 || ballX >= gameWidth) {
        resetBall();
    }

    // Update ball position on screen
    ball.style.left = ballX + 'px';
    ball.style.top = ballY + 'px';

    // Update paddle positions on screen
    paddleLeft.style.top = paddleLeftY + 'px';
    paddleRight.style.top = paddleRightY + 'px';

    requestAnimationFrame(update);
}

function resetBall() {
    ballX = gameWidth / 2;
    ballY = gameHeight / 2;
    ballSpeedX = -ballSpeedX;
}

// Touch controls for paddles
gameArea.addEventListener('touchmove', (e) => {
    const touchY = e.touches[0].clientY - gameArea.getBoundingClientRect().top;

    // Move left paddle
    if (touchY < gameWidth / 2) {
        paddleLeftY = touchY - paddleHeight / 2;
        if (paddleLeftY < 0) paddleLeftY = 0;
        if (paddleLeftY > gameHeight - paddleHeight) paddleLeftY = gameHeight - paddleHeight;
    }

    // Move right paddle
    else {
        paddleRightY = touchY - paddleHeight / 2;
        if (paddleRightY < 0) paddleRightY = 0;
        if (paddleRightY > gameHeight - paddleHeight) paddleRightY = gameHeight - paddleHeight;
    }
});

update();