forked from WebDevSimplified/chrome-dino-game-clone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
91 lines (77 loc) · 2.29 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { updateGround, setupGround } from "./ground.js"
import { updateDino, setupDino, getDinoRect, setDinoLose } from "./dino.js"
import { updateCactus, setupCactus, getCactusRects } from "./cactus.js"
const WORLD_WIDTH = 100
const WORLD_HEIGHT = 30
const SPEED_SCALE_INCREASE = 0.00001
const worldElem = document.querySelector("[data-world]")
const scoreElem = document.querySelector("[data-score]")
const startScreenElem = document.querySelector("[data-start-screen]")
setPixelToWorldScale()
window.addEventListener("resize", setPixelToWorldScale)
document.addEventListener("keydown", handleStart, { once: true })
let lastTime
let speedScale
let score
function update(time) {
if (lastTime == null) {
lastTime = time
window.requestAnimationFrame(update)
return
}
const delta = time - lastTime
updateGround(delta, speedScale)
updateDino(delta, speedScale)
updateCactus(delta, speedScale)
updateSpeedScale(delta)
updateScore(delta)
if (checkLose()) return handleLose()
lastTime = time
window.requestAnimationFrame(update)
}
function checkLose() {
const dinoRect = getDinoRect()
return getCactusRects().some(rect => isCollision(rect, dinoRect))
}
function isCollision(rect1, rect2) {
return (
rect1.left < rect2.right &&
rect1.top < rect2.bottom &&
rect1.right > rect2.left &&
rect1.bottom > rect2.top
)
}
function updateSpeedScale(delta) {
speedScale += delta * SPEED_SCALE_INCREASE
}
function updateScore(delta) {
score += delta * 0.01
scoreElem.textContent = Math.floor(score)
}
function handleStart() {
lastTime = null
speedScale = 1
score = 0
setupGround()
setupDino()
setupCactus()
startScreenElem.classList.add("hide")
window.requestAnimationFrame(update)
}
function handleLose() {
setDinoLose()
setTimeout(() => {
document.addEventListener("keydown", handleStart, { once: true })
startScreenElem.classList.remove("hide")
}, 100)
}
function setPixelToWorldScale() {
let worldToPixelScale
if (window.innerWidth / window.innerHeight < WORLD_WIDTH / WORLD_HEIGHT) {
worldToPixelScale = window.innerWidth / WORLD_WIDTH
} else {
worldToPixelScale = window.innerHeight / WORLD_HEIGHT
}
worldElem.style.width = `${WORLD_WIDTH * worldToPixelScale}px`
worldElem.style.height = `${WORLD_HEIGHT * worldToPixelScale}px`
}