-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
383 lines (330 loc) · 10.4 KB
/
main.js
File metadata and controls
383 lines (330 loc) · 10.4 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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
let hexChars = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
"D",
"E",
"F",
];
// based on code from https://stackoverflow.com/questions/424292/seedable-javascript-random-number-generator
// rng class to generate seeded random value in range
class RNG {
constructor(seed) {
// LCG using GCC's constants
this.m = 0x80000000; // 2**31;
this.a = 1103515245;
this.c = 12345;
this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));
}
// returns a random number in range
nextInRange(start, length) {
this.state = (this.a * this.state + this.c) % this.m;
// can't modulu state because of weak randomness in lower bits
const randomUnder1 = this.state / this.m;
return start + Math.floor(randomUnder1 * (length - start));
}
}
// game constants and variables
const dayLength = 24 * 60 * 60 * 1000;
const startDate = new Date("2025-03-21");
const maxDay = Math.ceil((Date.now() - startDate) / dayLength);
const maxAttempts = 6;
let day = maxDay;
let target = "";
let guesses = [];
let accuracies = [];
let attempts = 1;
let won = false;
// returns a durration in ms in HH:mm:ss format
function timeFromMilliseconds(ms) {
const hours = Math.trunc(ms / 1000 / 60 / 60);
ms -= hours * 1000 * 60 * 60;
const minutes = Math.trunc(ms / 1000 / 60);
ms -= minutes * 1000 * 60;
const seconds = Math.trunc(ms / 1000);
return (
String(hours).padStart(2, "0") +
":" +
String(minutes).padStart(2, "0") +
":" +
String(seconds).padStart(2, "0")
);
}
// returns the date a set number of days away from the startdate
// uses YYYY-MM-DD fomrat
function dateStringFromDay(days) {
let result = new Date(startDate.getTime());
result.setDate(result.getDate() + days);
const year = result.getFullYear();
const month = String(result.getMonth() + 1).padStart(2, "0");
const day = String(result.getDate()).padStart(2, "0");
return year + "-" + month + "-" + day;
}
// loads in gamestate from storage if it exists and readies the page
function load() {
// read in a gamestate from local storage if it exists
const gameStateString = localStorage.getItem(dateStringFromDay(day));
const gameState = JSON.parse(gameStateString);
if (gameState != null) {
guesses = gameState.guesses;
accuracies = gameState.accuracies;
attempts = gameState.attempts;
won = gameState.won;
} else {
guesses = [];
accuracies = [];
attempts = 1;
won = false;
}
updateUI();
}
// updates the elemets of the game after a change in game state
function updateUI(fromLoad = false) {
// set up header
document.getElementById("day-counter").innerHTML = day;
document.getElementById("btn-add-day").disabled = day >= maxDay;
document.getElementById("btn-sub-day").disabled = day <= 1;
// get target color
let dayRNG = new RNG(day);
target = "";
for (let i = 0; i < 6; i++) {
randIndex = dayRNG.nextInRange(0, hexChars.length);
target += hexChars[randIndex];
}
// set up color boxes
document.getElementById("display-target-color").style.backgroundColor =
"#" + target;
if (attempts > 1) {
document.getElementById("display-guessed-color").style.backgroundColor =
"#" + guesses[guesses.length - 1];
} else {
document.getElementById("display-guessed-color").style.backgroundColor =
"#888888";
}
// set up inputs and output based on gamestate
document.getElementById("btn-submit").disabled = won || attempts > maxAttempts;
const output = document.getElementById("user-output");
// if the player has won or is out of attempts enable share
if (won || attempts > maxAttempts) {
document.getElementById("btn-share").style.display = "block";
document.getElementById("btn-share").disabled = false;
// if won, display score
if (won) {
let msg = "You guessed the code in ";
if (attempts == 1) {
msg += "one try!";
} else {
msg += attempts + " tries!";
}
msg += " Your score is " + getScore() + "%";
output.innerHTML = msg;
}
// if lost, shame user
else {
output.innerHTML = "Wow... You actually ran out of guesses.";
}
}
// if the player has not yet won, disable
else {
document.getElementById("btn-share").style.display = "none";
document.getElementById("btn-share").disabled = true;
// if player is nearly out of attempts, warn them
if (attempts == maxAttempts) {
output.innerHTML = "Last chance.";
}
// if the player has guessed less, motivate them
else if (attempts > 1) {
output.innerHTML = "Nope. Try that again, but better.";
} else {
output.innerHTML = "Enter your guess above.";
}
}
// build guess div (does nothing if no game data exists)
buildGuessDiv(guesses, accuracies);
}
// adjusts the selected day by amount and reloads the gamestate
function changeDay(amt) {
if (day + amt > 0 && day + amt <= maxDay) {
day += amt;
dayRNG = new RNG(day);
load();
}
}
// adjusts the day to the most resent and reloads the gamestate
function resetDay() {
day = maxDay;
dayRNG = new RNG(day);
load();
}
// constucts a div containing the guesses color coded and marked
function buildGuessDiv(guesses, accuracies) {
let guessBox = document.getElementById("guesses");
guessBox.innerHTML = "";
// for each set of guesses and accuracies check them and buld a row
for (let i = guesses.length - 1; i >= 0; i--) {
const guess = guesses[i];
let guessColor = "#"
for (let ch of guess) guessColor += ch
const accuracy = accuracies[i];
const div = document.createElement("div");
div.className = "guess";
for (let index in accuracy) {
const guessCard = document.createElement("div");
guessCard.className = "guess-card";
guessCard.style.borderColor = guessColor
const digit = document.createElement("div")
const wrong = document.createElement("div")
digit.innerHTML = guess[index];
if (accuracy[index] == 0) {
guessCard.className += " correct";
wrong.innerHTML += "\u2713";
}
else if (accuracy[index] < 3 && accuracy[index] > -3) {
guessCard.className += " close";
wrong.innerHTML += accuracy[index] > 0 ? "\u2191" : "\u2193";
} else {
wrong.innerHTML += accuracy[index] > 0 ? "\u21C8" : "\u21CA";
}
guessCard.append(digit, wrong)
div.append(guessCard);
}
guessBox.append(div);
}
}
// buids a string representation of the accuracy of the guesses
function getGuessesStringArr() {
let strings = [];
for (let guess of accuracies) {
let temp = "";
for (let digit of guess) {
if (digit == 0) temp += "\u2713";
else if (digit < 3 && digit > 0) temp += "\u2191";
else if (digit > -3 && digit < 0) temp += "\u2193";
else if (digit > 0) temp += "\u21C8";
else temp += "\u21CA";
}
strings.push(temp);
}
return strings;
}
// a variable and function to help update the countdown in the share dialog
let timeLeftInterval;
function updateTimeLeft() {
const tl = document.getElementById("time-left");
if (tl == null) return;
const timeMS = dayLength - ((Date.now() - startDate) % dayLength);
tl.innerHTML = timeFromMilliseconds(timeMS);
}
// opens and populates the win/share dialog
function showWin() {
let modal = document.getElementById("win-modal");
modal.querySelector("#lbl-share-day").innerHTML = day;
let p = modal.querySelector("#sharable-results");
p.innerHTML = "";
const score = "Score: " + getScore() + "%";
let strings = [...getGuessesStringArr(), score];
for (let i = strings.length - 1; i >= 0; i--) {
p.append(strings[i], document.createElement("br"));
}
timeLeftInterval = setInterval(updateTimeLeft, 200);
modal.showModal();
}
// closes the win/share dialog
function unshowWin() {
clearInterval(timeLeftInterval);
document.getElementById("win-modal").close();
}
// writes the depicted results to the clipboard in string format
function shareResults() {
let text = "Score: " + getScore() + "%\n";
let strings = getGuessesStringArr();
for (let i = strings.length - 1; i >= 0; i--) {
text += strings[i] + "\n";
}
navigator.clipboard.writeText(text);
}
// calculates a score based on guess accuracy
function getScore() {
let scoreTotal = 0
for (let accuracy of accuracies) {
for (let index in accuracy) {
if (accuracy[index] == 0) scoreTotal += 1;
else if (Math.abs(accuracy[index]) == 1) scoreTotal += 0.5;
else if (Math.abs(accuracy[index]) == 2) scoreTotal += 0.15;
}
}
for (let i = accuracies.length; i <= maxAttempts; i++) {
scoreTotal += maxAttempts + 1 - accuracies.length
}
scorePossible = maxAttempts * 6
return Math.round((scoreTotal / scorePossible) * 100);
}
// handles an entry of a new guess, and updates the gamestate and page with results
function logSubmit(event) {
event.preventDefault();
// get inupt and output and reset input
let userInput = document.getElementById("user-input");
let userOutput = document.getElementById("user-output");
let input = userInput.value.toUpperCase();
// if input is invalid, return
if (input.length < 6) {
userOutput.value = "Try using the right number of digits.";
return;
}
let invalidChars = false;
for (let char of input) {
if (!hexChars.some((ch) => ch == char)) {
invalidChars = true;
break;
}
}
if (invalidChars) {
userOutput.value = "Wrong numbers. (0-9, A-F)";
return;
}
userInput.value = "";
// update color of guess box
document.getElementById("display-guessed-color").style.backgroundColor =
"#" + input;
// create accuracy entry
let accuracy = [];
for (let char in input) {
let inputIndex, targetIndex;
for (let index in hexChars) {
if (hexChars[index] == input[char]) inputIndex = index;
if (hexChars[index] == target[char]) targetIndex = index;
}
accuracy[char] = targetIndex - inputIndex;
}
// write guesses and accuracy to thier arrays and to the display
guesses.push(input);
accuracies.push(accuracy);
buildGuessDiv(guesses, accuracies);
// check if target was guessed
won = input == target;
//call UI updates
if (won) showWin();
else {
attempts++;
}
updateUI();
// update gamestate in localstorage
const gameState = {
guesses: guesses,
accuracies: accuracies,
attempts: attempts,
won: won,
};
const gameStateString = JSON.stringify(gameState);
localStorage.setItem(dateStringFromDay(day), gameStateString);
}