Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
83 lines (66 loc) · 2.51 KB
/
Copy pathscript.js
File metadata and controls
83 lines (66 loc) · 2.51 KB
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
const quotes = [
"Things are only impossible until they are not",
"It is possible to commit no errors and still lose. That is not a weakness. That is life",
"There is a way out of every box, a solution to every puzzle; it is just a matter of finding it.",
"Without freedom of choice there is no creativity",
"Logic is the beginning of wisdom, not the end",
"Improve a mechanical device and you may double productivity. But improve yourself, you gain a thousandfold",
"Compassion: that is the one thing no machine ever had. Maybe it is the one thing that keeps us ahead of them.",
];
const quote = document.getElementById("quote");
const input = document.getElementById("typed-value");
const start = document.getElementById("start");
const message = document.getElementById("message");
let wordQueue;
let quoteText;
let highlightPosition;
let startTime;
function startGame() {
console.log("Game Started!");
console.log(quotes.length);
const quoteIndex = Math.floor(Math.random() * quotes.length);
// will return a random number from 1 to 7
quoteText = quotes[quoteIndex];
wordQueue = quoteText.split(" ");
document.body.className = "";
start.className = "started";
message.innerHTML = "";
quote.innerHTML = wordQueue.map((word) => `<span>${word}</span>`).join("");
highlightPosition = 0;
quote.childNodes[highlightPosition].className = "highlight";
startTime = new Date().getTime();
setTimeout(() => {
start.className = "button";
}, 2000);
}
function checkInput() {
// wordQueue[0] allows us to grab the first element in our wordQueue array using an array indexer
const currentWord = wordQueue[0].replaceAll(".", "").replaceAll(",", "");
const typedValue = input.value.trim();
if (currentWord !== typedValue) {
input.className = currentWord.startsWith(typedValue) ? "" : "error";
return;
}
wordQueue.shift();
input.value = "";
// highlightPosition = 0;
quote.childNodes[highlightPosition].className = "";
if (wordQueue.length === 0) {
gameOver();
return;
}
// highlightPosition = 0 + 1;
highlightPosition++;
quote.childNodes[highlightPosition].className = "highlight";
}
function gameOver() {
const elapsedTime = new Date().getTime() - startTime;
document.body.className = "winner";
message.innerHTML = `
<span class="congrats">Congratulations!</span><br>
You finished in ${elapsedTime / 1000} seconds
`;
}
// element.addEventListener(event, function);
input.addEventListener("input", checkInput);
start.addEventListener("click", startGame);