-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
276 lines (248 loc) · 8.26 KB
/
core.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";
import { getFirestore, collection, getDocs, addDoc, query, orderBy, limit } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-firestore.js";
const DateTime = luxon.DateTime
import { dict as tech } from "./dictionary.js"
let PAUSE_TIME = 3000
let SPEED_RATIO = 25
let LIVES = 3
let createBlocks
const audio = new Audio('./sounds/tap.wav')
const audioWrong = new Audio('./sounds/wrong.wav')
const mainTheme = new Audio('./sounds/main_theme.mp3')
const audioError = new Audio('./sounds/wrong.wav')
const audioFail = new Audio('./sounds/fail.mp3')
const audioLose = new Audio('./sounds/lose.wav')
const firebaseConfig = {
apiKey: "AIzaSyBEjyeuOo9OgxG-veawtq4l7TKidzvOS0k",
authDomain: "catchyy-ecc85.firebaseapp.com",
projectId: "catchyy-ecc85",
storageBucket: "catchyy-ecc85.appspot.com",
messagingSenderId: "334084561026",
appId: "1:334084561026:web:0356c6a59cc8593dddfc9b"
};
initializeApp(firebaseConfig);
const db = getFirestore()
const scoresRef = collection(db, "scores")
const topScoresQuery = query(collection(db, "scores"), orderBy("score", "desc"), orderBy("solved", "desc"), limit(100))
document.getElementById("start").addEventListener("click", () => {
startClick()
})
function startClick() {
restart()
init()
checkInput()
detectEnter()
initCollisionCheck()
cleanInput(document.querySelector(".user-input"))
document.querySelector(".user-input").focus()
}
function startAgain() {
restart()
init()
initCollisionCheck()
document.querySelector(".user-input").focus()
}
function restart() {
if(document.querySelector(".game-over")) {
document.querySelector(".game-over").remove()
}
PAUSE_TIME = 3000
LIVES = 3
document.getElementById("score").innerText = 0
document.getElementById("solved").innerText = 0
}
function init() {
createBlock()
createBlocks = setInterval(createBlock, PAUSE_TIME)
mainTheme.volume = 0.2
mainTheme.loop = true
mainTheme.play()
renderLives()
setSpeed()
}
function createBlock() {
const block = document.createElement("div")
block.className = "block"
block.innerText = tech[Math.floor(Math.random()*tech.length)]
block.style.left = Math.random() * (window.innerWidth - 110) + "px"
document.querySelector(".sky").appendChild(block)
}
function checkInput() {
document.getElementById("send").addEventListener("click", () => {
checkAnswer()
})
}
function detectEnter() {
document.addEventListener('keypress', (event) => {
if(event.charCode === 13) {
checkAnswer()
}
})
}
function checkAnswer() {
const userInput = document.querySelector(".user-input").value
const blocks = document.querySelectorAll(".block")
let result = []
for(let block of blocks) {
if(userInput === block.innerText) {
result.push(true)
audio.play()
document.getElementById("score").innerText = Number(document.getElementById("score").innerText) + block.innerText.length
document.getElementById("solved").innerText = Number(document.getElementById("solved").innerText) + 1
PAUSE_TIME -= SPEED_RATIO
setSpeed()
clearInterval(createBlocks)
createBlocks = setInterval(createBlock, PAUSE_TIME)
createBlock()
block.remove()
}
}
if(!result.includes(true)) {
shakeInput()
audioWrong.play()
}
document.querySelector(".user-input").value = ""
}
function shakeInput() {
audioError.play()
const input = document.querySelector(".user-input")
input.style.cssText = `
animation: shake 0.82s cubic-bezier(.36,.07,.19,.97) both;
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
perspective: 1000px;
border: 2px solid red;
`
setTimeout(() => {
input.style.cssText = `
animation: none;
transform: none;
backface-visibility: visible;
perspective: 1000px;
border: 2px solid #422800;
`
}, 1050)
}
function decreaseLives() {
LIVES -= 1
renderLives()
}
function setSpeed() {
document.querySelector(".speed").textContent = `${(PAUSE_TIME / 1000).toFixed(2)}s`
}
function renderLives() {
document.getElementById("lives").textContent = ("❤️".repeat(LIVES))
}
function initCollisionCheck() {
setInterval(checkCollision, 1000)
}
function checkCollision() {
const blocks = document.querySelectorAll(".block")
const footer = document.querySelector("footer").getBoundingClientRect()
blocks.forEach(block => {
const rect = block.getBoundingClientRect()
if (rect.x < footer.x + footer.width &&
rect.x + rect.width > footer.x &&
rect.y < footer.y + footer.height &&
rect.height + rect.y > footer.y) {
block.remove()
audioFail.play()
decreaseLives()
PAUSE_TIME -= SPEED_RATIO
setSpeed()
clearInterval(createBlocks)
createBlocks = setInterval(createBlock, PAUSE_TIME)
createBlock()
if(LIVES == 0) {
document.querySelectorAll(".block").forEach(block => block.remove())
clearInterval(createBlocks)
mainTheme.pause()
audioLose.play()
createGameOver()
}
}
})
}
function createGameOver() {
const score = document.getElementById("score").innerText
const solved = document.getElementById("solved").innerText
const gm = document.createElement("div")
gm.className = "game-over"
gm.innerHTML = `
<img src="./img/gameover.gif" alt="Geme over">
<h2>Game Over</h2>
<p>You have solved <b>${solved}</b> words and got <b>${score}</b> points!</p>
<div class="set-player">
<label>Player name</label>
<input id="player-name" type="text">
<button id="submit-player">Submit</button>
</div>
`
document.querySelector("main").appendChild(gm)
document.getElementById("submit-player").addEventListener("click", () => {
submitResult()
})
cleanInput(document.querySelector("#player-name"))
}
function submitResult() {
addDoc(scoresRef, {
name: document.getElementById("player-name").value,
score: parseInt(document.getElementById("score").innerText),
solved: parseInt(document.getElementById("solved").innerText),
date: DateTime.now().ts
})
document.querySelector(".game-over").remove()
createScoresTable()
}
async function createScoresTable() {
const highScores = document.createElement("div")
highScores.className = "high-scores"
highScores.innerHTML = `
<h2>High scores</h2>
<div class="scores-list">
${await createRows()}
</div>
<button id="again">Play again</button>
`
document.querySelector("main").appendChild(highScores)
document.getElementById("again").addEventListener("click", () => {
startAgain()
document.querySelector(".high-scores").remove()
})
}
async function createRows() {
const scores = await getScores()
let tableRows = `
<div class="score-row table-head">
<p class="table-number">#</p>
<p class="table-player">Player</p>
<p class="table-score">Score</p>
<p class="table-solved">Solved</p>
</div>
`
scores.forEach((score, index) => {
tableRows += `
<div class="score-row">
<p class="table-number">${index + 1}.</p>
<p class="table-player">${score.name}</p>
<p class="table-score">${score.score}</p>
<p class="table-solved">${score.solved}</p>
</div>
`
})
return tableRows
}
async function getScores() {
const snap = await getDocs(topScoresQuery)
let scores = []
snap.docs.forEach(doc => {
scores.push({...doc.data()})
})
return sortScores(scores)
}
function sortScores(scores) {
return scores.sort((a, b) => (a.score === b.score) ? b.solved - a.solved : b.score - a.score)
}
function cleanInput(input) {
input.addEventListener("input", () => input.value = input.value.replace(/[^A-Za-z0-9\s]/g,''))
}