-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (47 loc) · 1.85 KB
/
index.js
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
import Ball from './Ball.js';
import Paddle from './Paddle.js';
const ball = new Ball(document.getElementById('ball'));
const playerPaddle = new Paddle(document.getElementById('player-paddle'));
const computerPaddle = new Paddle(document.getElementById('computer-paddle'));
const playerScoreElem = document.getElementById('player-score');
const computerScoreElem = document.getElementById('computer-score');
let lastTime;
function update(time) {
if (lastTime != null) {
// how much time passes between frames
const delta = time - lastTime;
ball.update(delta, [playerPaddle.rect(), computerPaddle.rect()]);
computerPaddle.update(delta, ball.y);
// change hue(background color) automatically during game
const hue = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--hue'));
document.documentElement.style.setProperty('--hue', hue + delta * 0.01)
if (isLose()) {
handleLose();
};
};
lastTime = time;
// creates infinite loop every time something is able to change
// console.log(time);
window.requestAnimationFrame(update)
};
function isLose() {
const rect = ball.rect();
return rect.right >= window.innerWidth || rect.left <= 0;
};
function handleLose() {
// set score after loss
const rect = ball.rect();
if (rect.right >= window.innerWidth) {
playerScoreElem.textContent = parseInt(playerScoreElem.textContent) + 1;
} else {
computerScoreElem.textContent = parseInt(computerScoreElem.textContent) + 1;
}
ball.reset();
computerPaddle.reset();
};
document.addEventListener('mousemove', e => {
// e.y is pixel value, convert to percentage (CSS)
playerPaddle.position = (e.y / window.innerHeight) * 100;
});
// better choice than setInterval(not accurate)
window.requestAnimationFrame(update);