Create script.js
Browse files
script.js
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const gameArea = document.getElementById('gameArea');
|
2 |
+
const paddleLeft = document.getElementById('paddleLeft');
|
3 |
+
const paddleRight = document.getElementById('paddleRight');
|
4 |
+
const ball = document.getElementById('ball');
|
5 |
+
|
6 |
+
let paddleLeftY = 160;
|
7 |
+
let paddleRightY = 160;
|
8 |
+
let ballX = 195;
|
9 |
+
let ballY = 195;
|
10 |
+
let ballSpeedX = 2;
|
11 |
+
let ballSpeedY = 2;
|
12 |
+
|
13 |
+
const paddleSpeed = 10;
|
14 |
+
const paddleHeight = 80;
|
15 |
+
const gameHeight = 400;
|
16 |
+
const gameWidth = 400;
|
17 |
+
|
18 |
+
function update() {
|
19 |
+
// Update ball position
|
20 |
+
ballX += ballSpeedX;
|
21 |
+
ballY += ballSpeedY;
|
22 |
+
|
23 |
+
// Ball collision with top and bottom walls
|
24 |
+
if (ballY <= 0 || ballY >= gameHeight - 15) {
|
25 |
+
ballSpeedY = -ballSpeedY;
|
26 |
+
}
|
27 |
+
|
28 |
+
// Ball collision with paddles
|
29 |
+
if (ballX <= 20 && ballY >= paddleLeftY && ballY <= paddleLeftY + paddleHeight) {
|
30 |
+
ballSpeedX = -ballSpeedX;
|
31 |
+
}
|
32 |
+
if (ballX >= gameWidth - 35 && ballY >= paddleRightY && ballY <= paddleRightY + paddleHeight) {
|
33 |
+
ballSpeedX = -ballSpeedX;
|
34 |
+
}
|
35 |
+
|
36 |
+
// Ball out of bounds
|
37 |
+
if (ballX <= 0 || ballX >= gameWidth) {
|
38 |
+
resetBall();
|
39 |
+
}
|
40 |
+
|
41 |
+
// Update ball position on screen
|
42 |
+
ball.style.left = ballX + 'px';
|
43 |
+
ball.style.top = ballY + 'px';
|
44 |
+
|
45 |
+
// Update paddle positions on screen
|
46 |
+
paddleLeft.style.top = paddleLeftY + 'px';
|
47 |
+
paddleRight.style.top = paddleRightY + 'px';
|
48 |
+
|
49 |
+
requestAnimationFrame(update);
|
50 |
+
}
|
51 |
+
|
52 |
+
function resetBall() {
|
53 |
+
ballX = gameWidth / 2;
|
54 |
+
ballY = gameHeight / 2;
|
55 |
+
ballSpeedX = -ballSpeedX;
|
56 |
+
}
|
57 |
+
|
58 |
+
// Touch controls for paddles
|
59 |
+
gameArea.addEventListener('touchmove', (e) => {
|
60 |
+
const touchY = e.touches[0].clientY - gameArea.getBoundingClientRect().top;
|
61 |
+
|
62 |
+
// Move left paddle
|
63 |
+
if (touchY < gameWidth / 2) {
|
64 |
+
paddleLeftY = touchY - paddleHeight / 2;
|
65 |
+
if (paddleLeftY < 0) paddleLeftY = 0;
|
66 |
+
if (paddleLeftY > gameHeight - paddleHeight) paddleLeftY = gameHeight - paddleHeight;
|
67 |
+
}
|
68 |
+
|
69 |
+
// Move right paddle
|
70 |
+
else {
|
71 |
+
paddleRightY = touchY - paddleHeight / 2;
|
72 |
+
if (paddleRightY < 0) paddleRightY = 0;
|
73 |
+
if (paddleRightY > gameHeight - paddleHeight) paddleRightY = gameHeight - paddleHeight;
|
74 |
+
}
|
75 |
+
});
|
76 |
+
|
77 |
+
update();
|