-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame unli guesses.js
311 lines (260 loc) · 7.97 KB
/
game unli guesses.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
const game = document.querySelector('#game');
const guessRows = document.querySelectorAll('.guess.row');
const guessBoxes = document.querySelectorAll('.guess.row .char');
const keys = document.querySelectorAll('.key');
const notif = document.querySelector('#notif');
const notifMessage = document.querySelector('#notif .notif-message');
const notifButton = document.querySelector('#notif .notif-button');
// Load data from locatStorage, split string to convert into array
let answerKey = localStorage.getItem('anskey').split(',') || [];
let validWords = localStorage.getItem('validwords').split(',') || [];
// Store to local storage
if (answerKey.length == 0 || validWords.length == 0) {
console.log('Storage is empty!')
loadData();
} else console.log('Storage exists!');
// Fetch data if localStorage empty
function loadData() {
// fetch answers.json
async function fetchAns() {
const response = await fetch('./answers.json');
const data = await response.json();
return data;
}
fetchAns().then((value) => {
answerKey = localStorage.setItem('anskey', value);
console.log('Answers loaded from localstorage.')
})
// fetch valid-words.json
async function fetchValid() {
const response = await fetch('./valid-words.json');
const data = await response.json();
return data;
}
fetchValid().then((value) => {
validWords = localStorage.setItem('validwords', value);
console.log('Valid words loaded from localstorage.')
})
}
// Today's hidden word
let startDate = new Date('2024-02-17');
let currentDate = Date.now();
console.log(Date.parse(startDate));
console.log(currentDate);
let dayNumber = Math.floor((currentDate - startDate) / (365 * 24 * 60 * 60));
let answer = answerKey[dayNumber];
let answerArray = answer.split("");
console.log(answer);
console.log(answerKey);
// Load valid-words.json first time
async function loadValidWords() {
const response = await fetch('./valid-words.json');
const data = await response.json();
return data;
};
async function validateGuess(guess) {
const validWords = await loadValidWords();
return validWords.includes(guess);
}
// Valid keys
const validKeys = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z' ]
// Counters
let currentGuessRow = 0;
// Submitted word
let currentGuess = [];
// List of submitted words
let allKeys = [];
// List of keys used
let usedKeys = [];
// Changes when successfully solved
let success = false;
// Print each letter iput
function showChar() {
const boxes = guessRows[currentGuessRow].querySelectorAll('.char');
boxes.forEach ((box, i) => {
box.textContent = currentGuess[i];
})
}
// Style current row
function styleCurrentRow() {
guessRows.forEach((row, i) => {
if (currentGuessRow == i) {
row.classList.remove('current');
row.classList.add('current');
} else row.classList.remove('current');
return true;
})
}
// Style used keys based on currentguess array
function styleKeys() {
//// Go through currentGuess array
currentGuess.forEach((char) => {
if (!(usedKeys.includes(char))) {
usedKeys.push(char);
};
});
//// Actual styling
keys.forEach((key) => {
if (usedKeys.includes(key.dataset.key)) {
key.classList.add('used');
};
if (answerArray.includes(key.dataset.key)) {
key.classList.add('correct');
};
});
};
// Reset all game counters
function resetBoard() {
currentGuessRow = 0;
currentGuess = [];
allKeys = [];
usedKeys = [];
correctKeys = [];
guessBoxes.forEach((box) => {
box.classList.remove('correct');
box.classList.remove('wrong');
box.classList.remove('position');
box.textContent = "";
})
keys.forEach((key) => {
key.classList.remove('used');
})
//// Hard refresh
location.reload();
styleCurrentRow();
styleKeys();
showChar();
}
// Handle notifs
function notifCentre(message) {
if (message == 'success') {
notifMessage.innerHTML = "You guessed the word in " + (currentGuessRow + 1) + ((currentGuessRow > 0) ? " tries!" : " try!" );
notifButton.textContent = 'Play again';
notifButton.addEventListener('click', () => {
notif.classList.add('hide');
resetBoard();
})
notif.classList.remove('hide');
} else if (message == 'fail') {
notifMessage.textContent = "Sorry, you have no more tries left!";
notifButton.textContent = 'Start over';
notifButton.addEventListener('click', () => {
notif.classList.add('hide');
return false;
})
notif.classList.remove('hide');
} else if (message == 'invalid') {
notifMessage.textContent = "Invalid word is not in the dictionary!";
notifButton.textContent = 'Try again';
notifButton.addEventListener('click', () => {
notif.classList.add('hide');
return;
})
notif.classList.remove('hide');
}
}
// Check submitted guess
function checkGuess(answer) {
//// Counter for number of correct letters
let correctGuesses = 0;
const answeredBoxes = guessRows[currentGuessRow].querySelectorAll('.char');
answerArray.forEach((ans, j) => {
////// Check if letter is included in the answer
if (answerArray.includes(answeredBoxes[j].textContent)) {
answeredBoxes[j].classList.add('position');
}
////// Check if letter matches to answer
if (ans == answeredBoxes[j].textContent) {
answeredBoxes[j].classList.add('correct');
correctGuesses++;
} else if (ans != answeredBoxes[j].textContent) {
answeredBoxes[j].classList.add('wrong');
}
})
// Check if all 5 letters are correct
if (correctGuesses == 5) {
//// SUCCESS - show success notification
notifCentre('success');
} else {
//// Not all letter are correct, move to next row
currentGuessRow++;
//// Highlight next row
styleCurrentRow();
//// Empty your guess array
currentGuess.length = 0;
}
// Check if currentGessRow is 6 (game over)
if (currentGuessRow >= 6) {
//// FAIL
notifCentre('fail');
}
} // checkGuess() //
//
//
//
// GAME START
function startGame() {
//// Clean up game board
// resetBoard();
styleCurrentRow();
styleKeys();
showChar();
console.log(answer)
//// ARM on-screen keyboard
keys.forEach((k) => {
k.addEventListener('click', (e) => {
////// Close notification by clicking any button
notif.classList.add('hide');
////// Send letter to current guess row
if (currentGuess.length < 5 && !(k.dataset.key === 'enter') && !(k.dataset.key === 'del')) {
currentGuess.push(k.dataset.key)
showChar();
} else if (k.dataset.key == 'enter') {
let guessString = currentGuess.join("");
validateGuess(guessString).then((res) => {
if (res) {
//////// Submit and style currentGuess
styleKeys();
checkGuess(answer);
} else {
notifCentre('invalid');
}
});
} else if (k.dataset.key == 'del') {
////// Check if row has letters to delete
////// Pop last letter
currentGuess.pop();
showChar();
}
});
});
//// ARM physical keyboard
document.addEventListener('keyup', (e) => {
////// Close notification by clicking any button
notif.classList.add('hide');
////// Only accept letters, del and enter keys
if (currentGuess.length < 5 && validKeys.includes(e.key)) {
currentGuess.push(e.key)
showChar();
} else if (e.key == 'Enter') {
let guessString = currentGuess.join("");
validateGuess(guessString).then((res) => {
if (res) {
//////// Submit and style currentGuess
styleKeys();
checkGuess(answer);
} else {
notifCentre('invalid');
}
});
} else if (e.key == 'Backspace') {
currentGuess.pop();
showChar( );
}
});
}; // startGame() //
startGame();