-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
448 lines (414 loc) · 14.1 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
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import Duck from "./src/duck.js";
import {
getRandomDuckPhrase,
getRandomPositivePhrase,
getRandomEncouragement,
} from "./src/duck.js";
import { loadAudio, playAudio, stopAudio } from "./src/audio.js";
// Most commonly used variables
let selectedRubbish = []; // keeps track of the selected rubbish that are in equation
let numberCount = 0; // keeps track of how many 'numbers' are in river
let symbolCount = 0; // keeps track of how many 'symbols' are in river
let lives; // number of lives user have
let score = 0; // number of equations correctly solved by user
// DOM Elements
const river = document.querySelector(".river");
const equationSlots = document.querySelectorAll(".equation-slot");
const equation = document.querySelector(".equation");
// Game Configurations
let lapse; // time lapse between every new rubbish, in ms
let rubbishLimit; // limit of rubbish in a river
let rubbishFlowRate = 4; // rubbish flow rate. 4 is ideal
let initiateRubbishID; // id to clear interval
let rubbishIntervalID; // id to clear interval
let isGameRunning = true;
// Load music
loadAudio();
const duck = new Duck();
duck.wander();
animationLoop();
addEventListeners();
// Initialize game (called only once)
function addEventListeners() {
addUserEventListeners();
// Add event listeners for user to select/deselect symbols
const symbols = document.querySelectorAll(".select-symbol");
for (let i = 0; i < symbols.length; i++) {
symbols[i].addEventListener("click", function () {
symbols[i].classList.toggle("unselected");
});
}
// Add event listeners to start game
document.querySelector(".start-game").addEventListener("click", function () {
let symbolList = getUserSelectedSymbols(symbols);
let difficulty = document.getElementById("difficulty").value;
lives = document.getElementById("health").value;
if (symbolList != "") {
// Replaces screen
document.querySelector(".menu").classList.add("hidden");
document.querySelector(".gameplay").classList.remove("hidden");
document.querySelector(".main-title").classList.add("hidden");
document.querySelector(".hud").classList.remove("hidden");
// Start Game
startGame(symbolList, difficulty, lives);
duck.speak("Here comes the rubbish!!");
playAudio();
} else {
duck.speak("Select at least ONE symbol!");
}
});
// Add event listener to allow user to exit game
document.querySelector(".return-home").addEventListener("click", function () {
returnHome();
stopAudio();
});
}
function startGame(symbolList, difficulty, health) {
console.log(symbolList, difficulty, health);
// Configure game difficulty
switch (difficulty) {
case "easy":
lapse = 5000;
rubbishLimit = 18;
break;
case "normal":
lapse = 3000;
rubbishLimit = 24;
break;
case "hard":
lapse = 2000;
rubbishLimit = 30;
break;
case "insane":
lapse = 1000;
rubbishLimit = 54;
break;
}
// Update HUD display
updateHUD();
// Add rubbish objects using DOM
let i = 0;
initiateRubbishID = setInterval(function () {
if (isGameRunning) {
addRubbish(symbolList);
i++;
if (i >= rubbishLimit) {
clearInterval(initiateRubbishID);
rubbishIntervalID = setInterval(function () {
if (isGameRunning) {
if (numberCount + symbolCount <= rubbishLimit) {
addRubbish(symbolList);
}
}
}, lapse);
}
}
}, 1000);
// Animate the rubbish flow
animationLoop.startAnimation();
}
// Returns to home screen
function returnHome() {
clearInterval(initiateRubbishID);
clearInterval(rubbishIntervalID);
document.querySelector(".menu").classList.remove("hidden");
document.querySelector(".gameplay").classList.add("hidden");
document.querySelector(".main-title").classList.remove("hidden");
document.querySelector(".hud").classList.add("hidden");
animationLoop.stopAnimation();
// Resets all variables
selectedRubbish = [];
numberCount = 0;
symbolCount = 0;
lives = undefined;
score = 0;
let allRubbish = document.querySelectorAll(".rubbish");
for (let i = 0; i < allRubbish.length; i++) {
allRubbish[i].remove();
}
let equationLog = document.querySelector(".equation-log");
while (equationLog.firstChild) {
equationLog.removeChild(equationLog.firstChild);
}
initiateRubbishID = undefined; // id to clear interval
rubbishIntervalID = undefined; // id to clear interval
duck.speak(getRandomDuckPhrase());
}
// Adds event listeners to allow user to interact with objects
function addUserEventListeners() {
// Adds event listener to equation slots, which allows user to de-select rubbish
for (let i = 0; i < equationSlots.length; i++) {
equationSlots[i].addEventListener("click", function () {
if (equationSlots[i].textContent != "") {
for (let j = 0; j < selectedRubbish.length; j++) {
if (selectedRubbish[j].textContent == equationSlots[i].textContent) {
// set greyed-out opacity back to 1
selectedRubbish[j].style.opacity = "1";
// remove the clicked rubbish from rubbishInEquation
selectedRubbish.splice(j, 1);
break;
}
}
equationSlots[i].textContent = "";
}
});
}
// Adds event listener to check user's answer when [Enter] key is pressed
equation.lastElementChild.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
if (selectedRubbish.length == 3) {
validateEquation();
} else {
console.log("This is not a valid expression!");
}
}
});
}
// Updates HUD (lives and rubbishCleared) using DOM
function updateHUD() {
if (lives != "inf") {
lives = parseFloat(lives);
document.querySelector("#lives").textContent = parseFloat(lives);
} else {
lives = "∞";
document.querySelector("#lives").textContent = "∞";
}
document.querySelector("#rubbish-cleared").textContent = score;
}
// Animation loop to animate river's rubbish
function animationLoop() {
// ...code template taken from the-art-of-web.com/javascript/animate-curved-path/
let requestID;
let requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
let cancelAnimationFrame =
window.cancelAnimationFrame || window.mozCancelAnimationFrame;
let start = null;
function step(timestamp) {
// Loop through and animate each rubbish
let children = river.children;
for (let i = 0; i < children.length; i++) {
let progress, x, y;
if (startAnimation === null) startAnimation = timestamp;
progress = ((timestamp - startAnimation) * rubbishFlowRate) / 1000; // percent
let child = children[i];
child.style.left =
limitMax(
parseFloat(child.style.left) + (1 * rubbishFlowRate) / 100,
0,
100
) + "%";
// Deduct health if rubbish reaches end of river
if ((child.style.left == "0%") & (lives != "∞")) {
if (lives == 0) {
endGame();
console.log("Game over...");
} else {
lives--;
document.querySelector("#lives").textContent = lives;
console.log("You lost a health!");
}
}
child.style.top =
parseFloat(child.style.top) +
0.1 * Math.sin(parseFloat(child.style.left)) +
"%";
if (progress >= 1) startAnimation = null;
}
requestID = requestAnimationFrame(step);
// Sets a value to min once it exceeds max
function limitMax(val, min, max) {
return val > max ? min : val;
}
}
// Stops rubbish animation and pauses agme
function stopAnimation() {
cancelAnimationFrame(requestID);
isGameRunning = false;
}
// Starts rubbish animation
function startAnimation() {
requestID = requestAnimationFrame(step);
isGameRunning = true;
}
animationLoop.stopAnimation = stopAnimation;
animationLoop.startAnimation = startAnimation;
}
// Returns a string of user selected symbols
function getUserSelectedSymbols(symbols) {
let plus = symbols[0].classList.contains("unselected") ? "" : "+";
let minus = symbols[1].classList.contains("unselected") ? "" : "-";
let multiply = symbols[2].classList.contains("unselected") ? "" : "x";
return plus + minus + multiply;
}
// Create and insert user-entered equation to the equation log
function addEquationLog(text, isCorrect) {
let eqLog = document.querySelector(".equation-log");
let newEq = document.createElement("p");
newEq.classList.add("logText");
if (isCorrect) {
newEq.classList.add("correct");
} else {
newEq.classList.add("wrong");
}
newEq.innerHTML = text;
eqLog.appendChild(newEq);
// auto scrolls to bottom every time new text is added
eqLog.scrollTop = eqLog.scrollHeight;
}
// Add rubbish (number or symbol) to river while maintaining a 2:1 ratio for number:symbol
function addRubbish(symbolList) {
let newRubbish;
if (numberCount / 2 > symbolCount) {
newRubbish = getNewSymbol(symbolList);
symbolCount++;
} else if (numberCount / 2 < symbolCount) {
newRubbish = getNewNumber();
numberCount++;
} else {
if (Math.floor(Math.random() * 2) == 0) {
newRubbish = getNewSymbol(symbolList);
symbolCount++;
} else {
newRubbish = getNewNumber();
numberCount++;
}
}
// Set rubbish to a random position
newRubbish.style.top = Math.floor(Math.random() * 85) + "%";
newRubbish.style.left = "0%";
river.appendChild(newRubbish);
}
// Returns a HTML element with a random number
function getNewNumber() {
let newNumber = document.createElement("p");
newNumber.textContent = Math.floor(Math.random() * 99) + 1; // Number Range
newNumber.classList.add("rubbish");
newNumber.classList.add("number");
newNumber.addEventListener("click", function () {
// Listens to click event. When clicked, add number to the equation if there is an empty slot
if (newNumber.style.opacity == "1" || newNumber.style.opacity == "") {
// Finds if empty slot available in the equation, if so add rubbish
if (equation.children[0].textContent == "") {
equation.children[0].textContent = newNumber.textContent;
newNumber.style.opacity = "0.5";
selectedRubbish.push(newNumber);
} else if (equation.children[2].textContent == "") {
equation.children[2].textContent = newNumber.textContent;
newNumber.style.opacity = "0.5";
selectedRubbish.push(newNumber);
} else {
console.log("Equation already has 2 numbers!");
}
} else {
// Removes rubbish from the equation
newNumber.style.opacity = "1";
for (let i = 0; i < equationSlots.length; i++) {
if (equationSlots[i].textContent == newNumber.textContent) {
for (let j = 0; j < selectedRubbish.length; j++) {
if (
selectedRubbish[j].textContent == equationSlots[i].textContent
) {
selectedRubbish[j].style.opacity = "1";
selectedRubbish.splice(j, 1);
}
}
equationSlots[i].textContent = "";
}
}
}
});
return newNumber;
}
// Returns a HTML element with a random symbol (+, -, x)
function getNewSymbol(symbolList) {
let newSymbol = document.createElement("p");
let n = Math.floor(Math.random() * symbolList.length);
newSymbol.textContent = symbolList[n];
newSymbol.classList.add("rubbish");
newSymbol.classList.add("symbol");
newSymbol.addEventListener("click", function () {
// Listens to click event. When clicked, add symbol to the equation if slot is empty
if (newSymbol.style.opacity == "1" || newSymbol.style.opacity == "") {
if (equation.children[1].textContent == "") {
equation.children[1].textContent = newSymbol.textContent;
newSymbol.style.opacity = "0.5";
selectedRubbish.push(newSymbol);
} else {
console.log("Equation already has a mathematical symbol!");
}
} else {
// Removes rubbish from the equation
newSymbol.style.opacity = "1";
for (let i = 0; i < equationSlots.length; i++) {
if (equationSlots[i].textContent == newSymbol.textContent) {
for (let j = 0; j < selectedRubbish.length; j++) {
if (
selectedRubbish[j].textContent == equationSlots[i].textContent
) {
selectedRubbish[j].style.opacity = "1";
selectedRubbish.splice(j, 1);
}
}
equationSlots[i].textContent = "";
}
}
}
});
return newSymbol;
}
// Validates the equation and updates the HUD and other variables
function validateEquation() {
let eq = equation.children;
let left = "";
let right = equation.lastElementChild.value;
for (let i = 0; i <= 2; i++) {
left += eq[i].textContent + " ";
}
if (eval(left.replace("x", "*")) == eval(right)) {
// Right answer!
duck.speak(getRandomPositivePhrase());
console.log("Correct! " + left + " = " + eval(right));
score++;
symbolCount--;
numberCount -= 2;
// Update Lives & Rubbish Cleared
document.querySelector("#lives").textContent = lives;
document.querySelector("#rubbish-cleared").textContent = score;
addEquationLog(left + "= " + eval(right), true);
cleanRubbish();
} else {
// Wrong answer!
duck.fallsDown();
duck.speak(getRandomEncouragement());
// console.log("Oops Wrong Answer! " + left + " is not " + eval(right));
addEquationLog(
left + "= " + "<span class='wrong-wavy'>" + eval(right) + "*</span>",
false
);
clearEquation();
}
}
// Removes rubbish from the river and calls clearEquation()
function cleanRubbish() {
selectedRubbish.forEach(function (item) {
item.remove();
});
selectedRubbish = [];
clearEquation();
equation.lastElementChild.value = "";
}
// Clears equation by reseting the opacity for all rubbish and setting text to empty
function clearEquation() {
selectedRubbish.forEach(function (item) {
item.style.opacity = "1";
});
selectedRubbish = [];
for (let i = 0; i <= 2; i++) {
equation.children[i].textContent = "";
}
equation.lastElementChild.value = "";
}