-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (74 loc) · 2.27 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
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
import { duration, setDuration, resetDuration } from './scripts/duration.js'
import { lives, setLives, resetLives } from './scripts/lives.js'
import { score, setScore, resetScore } from './scripts/scores.js'
import { observer, collisions } from './scripts/collisions.js'
import animateCollision from './scripts/animateCollision.js'
import { step, setStep } from './scripts/steps.js'
import addViewportHelper from './scripts/viewportHelper.js'
import getControls from './scripts/controls.js'
import { getStyles } from './scripts/utils.js'
import { getAnimationById, removeAnimation, addAnimation, cancelAndRemoveAnimations, finishAnimation, getAnimation } from './scripts/animations.js'
import { game, targets, playButtons } from './scripts/elements.js'
let raf
let controls
(async function() {
controls = await getControls()
init()
})()
function loop() {
if(collisions().length) {
collisions().forEach(({ target }) => {
const { x, y, z, theme } = getStyles(target)
if(100 - Math.abs(z) >= 1) {
finishAnimation(target.id)
if('evil' in target.dataset) {
setLives(lives() - 1)
} else {
setScore(score() + parseInt(target.dataset.points))
}
animateCollision({ x, y, z, theme })
}
})
}
raf = requestAnimationFrame(loop)
}
function animateTarget(target) {
let animation = getAnimationById(target.id)
if(animation) {
observer.unobserve(target)
removeAnimation(animation)
setDuration(duration() - 20)
}
animation = getAnimation({
target,
duration: duration(),
id: target.id,
onFinish: () => step() < 3 && animateTarget(target)
})
addAnimation(animation)
observer.observe(target)
}
function startGame() {
cancelAndRemoveAnimations()
resetDuration()
resetScore()
resetLives()
setStep(2)
targets.forEach(target => animateTarget(target))
controls.addControls()
raf = requestAnimationFrame(loop)
}
export function stopGame() {
targets.forEach(target => observer.unobserve(target))
cancelAnimationFrame(raf)
controls.removeControls()
setStep(3)
}
function init() {
playButtons.forEach(button => button.addEventListener('click', startGame))
setStep(1)
addViewportHelper()
if(controls.isTouch) {
game.classList.add('is-touch')
}
}