-
Notifications
You must be signed in to change notification settings - Fork 0
/
guess.js
281 lines (235 loc) · 8.23 KB
/
guess.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
// Setting Game Name
let gameName = "Guess The Word Game";
document.title = gameName;
document.querySelector("h1").innerHTML = gameName;
document.querySelector(
"footer"
).innerHTML = `${gameName} Created By Aimad Bouchouaf`;
// Setting Game Options
let numbersOfTries = 6;
let numbersOfLetters = 6;
let currentTry = 1;
let numberOfHints = 2;
let numberOfUsedHints = 0 ;
// Manage Words
let wordToGuess = "";
const words = [
"Create",
"Update",
"Delete",
"Master",
"Branch",
"Mainly",
"String",
"Method",
"Object",
"Binary",
"Switch",
"Return",
"Define",
"Public",
"Buffer",
"Socket",
"Thread",
"Buffer",
"Struct",
"Global",
"Search",
"Assert",
"Vector",
"Import",
"Output",
"Random"
];
wordToGuess = words[Math.floor(Math.random() * words.length)].toLowerCase();
let messageArea = document.querySelector(".message");
let messageAreaHint = document.querySelector(".messageHint");
// console.log(wordToGuess); // to see printed word
// Manage Hints
document.querySelector(".hint span").innerHTML = numberOfHints;
const getHintButton = document.querySelector(".hint");
getHintButton.addEventListener("click", getHint);
function generateInput() {
const inputsContainer = document.querySelector(".inputs");
for (let i = 1; i <= numbersOfTries; i++) {
const tryDiv = document.createElement("div");
tryDiv.classList.add(`try-${i}`);
tryDiv.innerHTML = `<span>Try ${i}</span>`;
if (i !== 1) tryDiv.classList.add("disabled-inputs");
for (let j = 1; j <= numbersOfLetters; j++) {
const input = document.createElement("input");
input.type = "text";
input.id = `guess-${i}-letter-${j}`;
input.setAttribute("maxlength", "1");
tryDiv.appendChild(input);
}
inputsContainer.appendChild(tryDiv);
}
// focus on First Input In first Try Element
inputsContainer.children[0].children[1].focus();
// Disable All Inputs Except First One
const inputsInDisabledDiv = document.querySelectorAll(
".disabled-inputs > input"
);
inputsInDisabledDiv.forEach((input) => (input.disabled = true));
const inputs = document.querySelectorAll("input");
inputs.forEach((input, index) => {
// Convert Input To UpperCAse
input.addEventListener("input", function () {
this.value = this.value.toUpperCase();
const nextInput = inputs[index + 1];
if (nextInput) nextInput.focus(); // if nextInput exists
});
input.addEventListener("keydown", function (event) {
// console.log(event);
const currentIndex = Array.from(inputs).indexOf(event.target); // Or this
// console.log(currentIndex);
if (event.key === "ArrowRight") {
const nextInput = currentIndex + 1;
if (nextInput < inputs.length) inputs[nextInput].focus();
}
if (event.key === "ArrowLeft") {
const prevInput = currentIndex - 1;
if (prevInput >= 0) inputs[prevInput].focus();
}
});
});
}
const guessButton = document.querySelector(".check");
guessButton.addEventListener("click", handleGuesses);
function handleGuesses() {
let successGuess = true;
// console.log(wordToGuess);
for (let i = 1; i <= numbersOfLetters; i++) {
const inputField = document.querySelector(
`#guess-${currentTry}-letter-${i}`
);
const letter = inputField.value.toLowerCase();
// console.log(letter);
const actaulLetter = wordToGuess[i - 1];
// Game Logic
if (letter === actaulLetter) {
inputField.classList.add("yes-in-place");
} else if (wordToGuess.includes(letter) && letter !== "") {
// Letter Is Correct But In Wrong Place
inputField.classList.add("not-in-place");
successGuess = false;
} else {
inputField.classList.add("no");
successGuess = false;
}
}
// check If User Win The game or not
if (successGuess) {
messageArea.innerHTML = `You Win The word Is <span>${wordToGuess}</span>`;
if(numberOfHints ===2){
messageAreaHint.innerHTML = `<span style= "font-weight: bold; color:orange">Wow You Win Without Using Any Hints </span>`
}
else{
messageAreaHint.innerHTML = `<span>You Win Using ${numberOfUsedHints - numberOfHints} Hints </span>`
}
// Add Disabled Class ON All Try Divs
let alltries = document.querySelectorAll(".inputs > div");
alltries.forEach((tryDiv) => tryDiv.classList.add("disabled-inputs"));
// Disable Guess Button
guessButton.disabled = true ;
getHintButton.disabled = true;
// Lose Logic
} else {
document.querySelector(`.try-${currentTry}`).classList.add("disabel-inputs");
const currentTryInputs = document.querySelectorAll(`.try-${currentTry} input`);
currentTryInputs.forEach((input) => (input.disabled = true));
currentTry++;
const nextTryInputs = document.querySelectorAll(`.try-${(currentTry)} input`);
nextTryInputs.forEach((input)=>{ (input.disabled=false) });
let el = document.querySelector(`.try-${currentTry}`);
if(el){
document.querySelector(`.try-${currentTry}`).classList.remove("disabled-inputs");
el.children[1].focus();
}
else{
// Disable Guess Button
guessButton.disabled = true ;
getHintButton.disabled = true;
messageArea.innerHTML= `You Lose the Word Is <span>${wordToGuess}</span>`;
}
}
}
function getHint() {
if (numberOfHints > 0) {
numberOfHints--;
numberOfUsedHints++;
document.querySelector(".hint span").innerHTML = numberOfHints;
}
if (numberOfHints === 0) {
getHintButton.disabled = true;
}
const enabledInputs = document.querySelectorAll("input:not([disabled])");
const emptyEnabledInputs = Array.from(enabledInputs).filter(
(input) => input.value === ""
);
// Check if there are empty input fields
if (emptyEnabledInputs.length > 0) {
// Select a random empty input field
const randomIndex = Math.floor(Math.random() * emptyEnabledInputs.length);
const randomInput = emptyEnabledInputs[randomIndex];
// Get the index of the selected input field
const indexToFill = Array.from(enabledInputs).indexOf(randomInput);
if (indexToFill !== -1) {
randomInput.value = wordToGuess[indexToFill].toUpperCase();
// Update the class to reflect the change visually
randomInput.classList.remove("no");
if (randomInput.value.toLowerCase() === wordToGuess[indexToFill]) {
randomInput.classList.add("yes-in-place");
} else {
randomInput.classList.add("not-in-place");
}
}
} else {
// Find the first incorrect letter not in place
const incorrectInput = Array.from(enabledInputs).find(
(input) =>
input.classList.contains("not-in-place") && input.value !== wordToGuess[input.id.split("-")[2] - 1]
);
// If there's an incorrect input, replace its value with the correct one
if (incorrectInput) {
const indexToFill = Array.from(enabledInputs).indexOf(incorrectInput);
incorrectInput.value = wordToGuess[indexToFill].toUpperCase();
// Update the class to reflect the change visually
incorrectInput.classList.remove("no");
incorrectInput.classList.remove("not-in-place");
incorrectInput.classList.add("yes-in-place");
}
}
}
function handleBackspace(event){
if(event.key === "Backspace"){
const inputs = document.querySelectorAll("input:not([disabled])");
const currentIndex = Array.from(inputs).indexOf(document.activeElement);
if (currentIndex >= 0) {
const currentInput = inputs[currentIndex];
const prevInput = inputs[currentIndex - 1];
// Check if the current input is empty
if (currentInput.value === "") {
// If it's empty, delete the previous character and move focus to the previous input
currentInput.value = "";
prevInput.focus();
event.preventDefault(); // Prevent default behavior of the backspace key
} else {
// If it's not empty, delete the current character
currentInput.value = "";
}
}
}
}
document.addEventListener("keydown" , handleBackspace);
window.onload = function () {
generateInput();
};
// Get the restart button by its ClassName
const restartButton = document.querySelector(".restart");
// Add an event listener to the button
restartButton.addEventListener('click', function() {
// Reload the page
location.reload();
});