-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
218 lines (199 loc) · 7.08 KB
/
script.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
// Global variables
let secretWord = "";
let currentWord = "";
let guessParts = [];
let wordParts = [];
let excludedLetters = new Set();
const ANSWER_LENGTH = 5;
// ----- Function definitions -----
// Function to get the Word of the Day
async function getSecretWord() {
try {
const response = await fetch(
"https://words.dev-apis.com/word-of-the-day?random=1"
);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const json = await response.json();
console.log("Word of the day is:", json.word);
secretWord = json.word;
wordParts = secretWord.split("");
return secretWord;
} catch (error) {
console.error("Error fetching word of the day:", error);
return null;
}
}
var isAlpha = function (ch) {
return /^[A-Za-z]$/i.test(ch);
};
function getWord(myForm) {
// takes a form element (a row), and returns the string value (guess word) it holds
let wordArray = [];
Array.from(myForm.querySelectorAll(".letterSquare")).forEach((e) => {
wordArray.push(e.value);
});
return wordArray.join("");
}
function makeMap(array) {
// takes an array of letters (like ['E', 'L', 'I', 'T', 'E']) and creates
// an object out of it (like {E: 2, L: 1, T: 1}) so we can use that to
// make sure we get the correct amount of letters marked close instead
// of just wrong or correct
const obj = {};
for (let i = 0; i < array.length; i++) {
if (obj[array[i]]) {
obj[array[i]]++;
} else {
obj[array[i]] = 1;
}
}
return obj;
}
function init() {
let currentBox = 0;
getSecretWord();
// Handling user interaction
for (let r = 0; r < 6; r++) {
// for each row (guess word line)
for (let i = 1 + 6 * r; i < 6 + 6 * r; i++) {
// for each input square on this row
// Get the current letter box in a variable
currentBox = document.getElementById(`letter${i}`);
// Listen for user input
currentBox.addEventListener("keydown", (event) => {
let input = event.target.value;
if (input.length === 1 && isAlpha(event.key)) {
// if the user input is a valid letter
// move on to the next letter box
document.getElementById(`letter${i + 1}`).focus();
}
});
// Listen for Backspace key press
currentBox.addEventListener("keydown", (event) => {
if (event.key === "Backspace" && event.target.value === "") {
// if Backspace is pressed and the box is empty
// move back to the previous letter box
if (i != 1) {
let prevBox = document.getElementById(`letter${i - 1}`);
if (prevBox) {
prevBox.focus();
}
}
}
});
}
// Submitting a guess
document.forms[r].addEventListener("submit", (event) => {
event.preventDefault();
wordGuessed = getWord(document.forms[r]);
// reset buffers and get ready for next line
lettersEntered = [];
wordGuessed = "";
// move focus to next line
if (r < 5) {
document.getElementById(`letter${r * 6 + 7}`).focus();
}
});
}
// Get all the letter buttons from the virtual keyboards
const VKButtons = document.getElementsByClassName("btn")
// Wire them up with event handlers
Array.from(VKButtons).forEach((e) => {
e.addEventListener("click", (event) => {
console.log("Debugging:", event.target.textContent)
// Virtual Keyboard logic
})
})
}
// Setting things up
init();
// Reset all
document.querySelectorAll(".letterSquare").forEach((e) => (e.value = ""));
// Async part
let linesArray = Array.from(document.forms);
linesArray.forEach(function (line) {
line.addEventListener("submit", function () {
// Set the current word to the word entered
currentWord = getWord(line);
// Each time a word is Entered, do this
fetch("https://words.dev-apis.com/validate-word", {
method: "POST",
body: JSON.stringify({
word: currentWord,
}),
})
.then((response) => response.json())
.then((json) => {
// In this part,
// we make the distinction between actual words and non-words
if (json.validWord === true) {
// The player entered an actual word
// Prevent the user from changing this line
Array.from(line.querySelectorAll(".letterSquare")).forEach((e) => {
e.disabled = true;
});
// Winning Logic
if (currentWord === secretWord) {
// Player entered the Word of the Day
// 1. Display Winning Message
console.log("YOU WON! HOORAY!");
document.getElementById("winning").id = "winningMessage";
document.getElementById("winningMessage").innerHTML =
"GOOD JOB! YOU WON!";
// 2. End the game. Disable all inputs.
Array.from(document.querySelectorAll(".letterSquare")).forEach(
(e) => {
e.disabled = true;
}
);
Array.from(line.querySelectorAll(".letterSquare")).forEach((e) => {
e.style.backgroundColor = "green";
});
} else {
// Scenario #2 (Valid word but not the Answer)
guessParts = currentWord.split("");
const map = makeMap(wordParts);
for (let i = 0; i < ANSWER_LENGTH; i++) {
if (guessParts[i] === wordParts[i]) {
// mark as correct
line[i].style.backgroundColor = "green";
map[guessParts[i]]--;
}
}
for (let i = 0; i < ANSWER_LENGTH; i++) {
if (guessParts[i] === wordParts[i]) {
// do nothing
} else if (map[guessParts[i]] && map[guessParts[i]] > 0) {
// mark as close
allRight = false;
line[i].style.backgroundColor = "orange";
map[guessParts[i]]--;
} else {
// wrong
allRight = false;
line[i].style.backgroundColor = "gray";
if(!secretWord.includes(guessParts[i])) {
excludedLetters.add(guessParts[i])
}
console.log("(Debugging) Excluded letters:", excludedLetters)
Array.from(document.getElementsByClassName("btn")).forEach((e) =>
{
if(excludedLetters.has(e.textContent.toLowerCase())) {
e.style.color = "red";
}
})
}
}
}
} else if (json.validWord === false) {
// The player entered a non-word
// 1. Reset the whole line
line.querySelectorAll(".letterSquare").forEach((e) => (e.value = ""));
// 2. Move the focus back to the first box on the line
line.querySelector("input").focus();
}
});
});
});