-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
50 lines (42 loc) · 1.47 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
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) {
const delta = time - lastTime
ball.update(delta, [playerPaddle.rect(), computerPaddle.rect()])
computerPaddle.update(delta, ball.y)
const hue = parseFloat(
getComputedStyle(document.documentElement).getPropertyValue("--hue")
)
document.documentElement.style.setProperty("--hue", hue + delta * 0.01)
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
computerPaddle.faster()
} else {
computerScoreElem.textContent = parseInt(computerScoreElem.textContent) + 1
computerPaddle.slower()
}
ball.reset()
computerPaddle.reset()
}
document.addEventListener("mousemove", e => {
playerPaddle.position = (e.y / window.innerHeight) * 100
})
window.requestAnimationFrame(update)