-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
59 lines (39 loc) · 1.37 KB
/
script.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
57
58
59
// Update Loop
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) {
//console.log(time)
if(lastTime != null) {
const delta = time - lastTime
ball.update(delta, [playerPaddle.rect(), computerPaddle.rect()])
computerPaddle.update(delta, ball.y)
if(isLose()) handleLose()
}
lastTime = time
window.requestAnimationFrame(update)
}
function isLose() {
const rect = ball.rect()
return rect.right >= window.innerWidth || rect.left <= 0
}
function handleLose() {
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 => {
playerPaddle.position = (e.y / window.innerHeight) * 100 // Converting to %
})
window.requestAnimationFrame(update)