-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
266 lines (214 loc) · 6.73 KB
/
main.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
import randomWord from "./randomWord.js";
console.log("winning word:", randomWord);
const bodyEl = document.querySelector("body");
// o---------------o
// | Game settings |
// o---------------o
const WORD_LENGTH = 5;
const NUM_OF_ATTEMPTS = 6;
let isGameWon = false;
class Word {
constructor(parent) {
this.word = "";
this.parent = parent;
}
create() {
this.container = createElement({
tag: "div",
className: "word",
parent: this.parent,
});
this.createLetters();
}
createLetters() {
for (let i = 0; i < WORD_LENGTH; i++) {
createElement({
tag: "div",
className: "letter-container",
parent: this.container,
});
}
}
update() {
const letterNodeList = this.container.querySelectorAll(".letter-container");
const wordArr = Array.from(this.word);
// Emptying the innerHTML of the nodeList items allows us to replace the current with new content
emptyNodeListInnerHTML(letterNodeList);
wordArr.forEach((letter, index) => {
createElement({
tag: "p",
className: "letter",
text: letter,
parent: letterNodeList[index],
});
});
}
}
const wordsDiv = document.querySelector(".words-container");
const wordsRowsArr = new Array(NUM_OF_ATTEMPTS)
.fill("")
.map((item) => new Word(wordsDiv));
let currentWordRowIndex = 0;
wordsRowsArr.forEach((word) => word.create());
highlightCurrentWordRow();
function highlightCurrentWordRow() {
const currentWordObj = wordsRowsArr[currentWordRowIndex];
const letterNodeList =
currentWordObj.container.querySelectorAll(".letter-container");
letterNodeList.forEach((item) =>
item.classList.add("letter-container--active")
);
}
class KeyboardKey {
constructor({ value, parentRow }) {
this.value = value;
this.parentRow = parentRow;
}
create() {
const row = document.querySelector(`#keyboard__${this.parentRow}`);
const isNonStandardKey =
this.value === "Backspace" || this.value === "Enter";
const nonStandardKeys = {
Backspace: "⌫",
Enter: "⏎",
};
const currentKeyText = isNonStandardKey
? nonStandardKeys[this.value]
: this.value;
this.container = createElement({
tag: "span",
className: "keyboard__key",
parent: row,
text: currentKeyText,
id: this.value.toLowerCase(),
});
this.container.addEventListener("click", this.handleClick.bind(this));
}
handleClick() {
const keyCodeInAlphabetRange = 69; // Arbitrary MEME number chosen. As long as it's within the alphabet keycode range, it will work.
runGame({ keyCode: keyCodeInAlphabetRange, key: this.value });
}
}
const keyboard = [];
const keyboardKeysArr = Array.from("qwertyuiop'asdfghjkl'zxcvbnm").concat(
"Enter",
"Backspace"
);
const keyboardRowsClassList = ["first-row", "second-row", "third-row"];
let keyboardRowIndex = 0;
keyboardKeysArr.forEach((value, index) => {
if (value === "'") return keyboardRowIndex++;
keyboard.push(
new KeyboardKey({
value,
parentRow: keyboardRowsClassList[keyboardRowIndex],
})
);
const currentKeyIndex = keyboard.length - 1;
keyboard[currentKeyIndex].create();
});
// Keyboard input
document.addEventListener("keydown", runGame);
function runGame({ keyCode, key }) {
const wordObj = wordsRowsArr[currentWordRowIndex];
const isWordShort = wordObj.word.length < WORD_LENGTH;
const isGameOver = currentWordRowIndex > NUM_OF_ATTEMPTS;
const isKeyValid =
keyCode == 13 || // Return/Enter
keyCode == 8 || // Backspace
(keyCode > 64 && keyCode < 91); // Letters range
if (isGameOver || isGameWon || !isKeyValid) return;
if (key === "Enter") return validateWord(wordObj, isWordShort);
if (key === "Backspace") return deleteLastLetter(wordObj);
if (!isWordShort) return;
wordObj.word += key;
wordObj.update();
}
async function validateWord(wordObj, isWordShort) {
if (isWordShort) return createNotification("Too short");
if (!(await isWordInDictionary(wordObj.word)))
return createNotification("Not in wordlist");
if (wordObj.word === randomWord) {
isGameWon = true;
createNotification(`You won! The word was "${randomWord.toUpperCase()}"`);
}
applyLetterStyling(keyboard, wordObj.container);
currentWordRowIndex++;
highlightCurrentWordRow();
}
function deleteLastLetter(wordObj) {
wordObj.word = wordObj.word.slice(0, -1);
wordObj.update();
return;
}
function createNotification(text) {
const notificationsDiv = document.querySelector(".notifications");
const notification = createElement({
tag: "div",
className: "notification",
parent: notificationsDiv,
text: text,
});
setTimeout(() => notification.remove(), 3000);
}
async function isWordInDictionary(word) {
// Show user that we are fetching the data
bodyEl.style = "cursor: wait !important";
try {
const response = await fetch(
`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`
);
const data = await response.json();
// Remove 'loading' styling
bodyEl.style.cursor = "default";
return data.title !== "No Definitions Found";
} catch (error) {
console.error(`Error found ${e}`);
}
}
function applyLetterStyling(keyboard, wordObj) {
const letterNodeList = wordObj.querySelectorAll(".letter-container");
letterNodeList.forEach((letter, index) => {
const letterInnerText = letter.innerText.toLowerCase();
const keyboardKeyContainer = keyboard.find(
(key) => key.value === letterInnerText
).container;
if (letterInnerText === randomWord[index]) {
letter.classList.add("letter-container--correct");
// Remove out of order modifier to allow replacement with updated class
keyboardKeyContainer.classList.remove("keyboard__key--out-of-order");
keyboardKeyContainer.classList.add("keyboard__key--correct");
return;
}
if (randomWord.includes(letterInnerText)) {
letter.classList.add("letter-container--out-of-order");
keyboardKeyContainer.classList.add("keyboard__key--out-of-order");
return;
}
letter.classList.add("letter-container--not-present");
keyboardKeyContainer.classList.add("keyboard__key--not-present");
});
}
// Helper functions
function createElement({
tag,
className,
parent,
parentSelector,
text = "",
id,
}) {
const parentEl = parent || document.querySelector(parentSelector);
const newElement = document.createElement(tag);
if (text) newElement.innerText = text;
if (className) newElement.classList.add(className);
if (id) newElement.id = id;
if (parentEl) parentEl.append(newElement);
return newElement;
}
function emptyNodeListInnerHTML(nodeList) {
nodeList.forEach(emptyElementInnerHTML);
}
function emptyElementInnerHTML(element) {
element.innerHTML = "";
}