/
app.js
332 lines (326 loc) · 10.2 KB
/
app.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
const debug = window.location.href.includes("debug=true");
const oneColor = window.location.href.includes("oneColor=true");
const clearStorage = window.location.href.includes("clearStorage=true");
var circles = ["🟢","⚪","🟣"];
const GREEN = "🟢";
const WHITE = "⚪";
const YELLOW = "🟣";
const ROTATE = "🔄";
/* functions for emoji support detection */
function supportsEmoji (e) {
const ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = ctx.canvas.height = 1;
ctx.fillText(e, -4, 4);
return ctx.getImageData(0, 0, 1, 1).data[3] > 0; // Not a transparent pixel
}
function supportsAll(emojis) {
for (var i = 0; i < emojis.length; i++) {
var e = emojis[i];
if (!supportsEmoji(e)) {
return false;
}
}
return true;
}
const CIRCLES = supportsAll(circles);
/* daily puzzle */
function getNumber() {
const re=/puzzle=(\d+)/;
var m;
if ((m = window.location.href.match(re)) && m.length > 1) {
return parseInt(m[1]);
}
const dayMillis = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const start = new Date(2022, 1, 1);
const today = new Date();
return Math.ceil(Math.abs((start - today) / dayMillis));
}
function getTitle(n) {
if (typeof n === "undefined") {
n=0;
}
return "Josekle #"+(getNumber()+n);
}
function getSolution() {
return puzzles[getNumber() % puzzles.length];
}
/* functions to get inputted sequence from besogo */
function extractMovesFrom(current) {
var moves=[];
if (current.markup.length > 0) {
return []; // Detects if there are already hints
}
while (current.move !== null) {
moves.push({x:current.move.x, y:current.move.y});
current=current.parent;
}
return moves.reverse();
}
function getInputEditor() {
return document.querySelector("#input-board").editor;
}
function extractMoves() {
var inputBoard=document.querySelector("#input-board");
var current=inputBoard.editor.getCurrent();
return extractMovesFrom(current);
}
function pretty_print(moves) {
return moves.map(move => move.x+"-"+move.y).join(", ");
}
/* functions to handle inputted guesses and update state on success */
function wasCorrect(hints, solution) {
// Considers guess to be correct if the solution is a prefix
for (i=0; i < hints.length && i < solution.length; i++) {
if (hints[i]===YELLOW || hints[i]===WHITE) {
return false;
}
}
return solution.length <= hints.length;
}
function share() {
var text = getTitle() + "\n";
text += guesses.map(guess => guess.join("")).join("\n");
text += "\n";
text += "https://okonomichiyaki.github.io/josekle/";
navigator.clipboard.writeText(text);
}
function shareDiscord() {
var text = getTitle() + "\n";
text += "||";
text += guesses.map(guess => guess.join("")).join("\n");
text += "||\n";
text += "https://okonomichiyaki.github.io/josekle/";
navigator.clipboard.writeText(text);
}
function shareDiscourse() {
var text = `[details="${getTitle()}"]\n`;
text += guesses.map(guess => guess.join("")).join("\n");
text += `\n[/details]`;
text += "\n";
text += "https://okonomichiyaki.github.io/josekle/";
navigator.clipboard.writeText(text);
}
function makeButton(value, title, onclick) {
element = document.createElement('input');
element.type = 'button';
element.value = value;
element.title = title;
element.onclick = onclick;
return element;
}
function toggleButtons() {
document.querySelector('#output').appendChild(
makeButton("Share (Discourse)", "Copy results to clipboard with Discourse spoiler tags", shareDiscourse)
);
document.querySelector('#output').appendChild(
makeButton("Share (Discord)", "Copy results to clipboard with Discord spoiler tags", shareDiscord)
);
document.querySelector('#output').appendChild(
makeButton("Share", "Copy results to clipboard without spoiler tags", share)
);
document.querySelector('#Submit').classList.add("hidden");
}
function display(hints, message) {
var output = document.querySelector("#output");
var p = document.createElement("p");
if (CIRCLES) {
p.innerText = hints + " " + message;
output.appendChild(p);
} else {
var rest = [];
var split = [...hints];
split.forEach(c => {
if (c === YELLOW) {
var img = document.createElement("img");
img.src = "img/emojis/yellow.png";
p.appendChild(img);
} else if (c === GREEN) {
var img = document.createElement("img");
img.src = "img/emojis/green.png";
p.appendChild(img);
} else if (c === WHITE) {
var img = document.createElement("img");
img.src = "img/emojis/white.png";
p.appendChild(img);
} else {
rest.push(c);
}
});
p.innerHTML += " " + message;
output.appendChild(p);
}
document.querySelector(".besogo-hint").scrollTop = document.querySelector(".besogo-hint").scrollHeight;
}
function isDictionaryReady() {
const dict = document.querySelector("#dictionary-board").editor;
// the dictionary should be ready if 4-4 is navigable:
const ready = dict.navigate(16, 4, false);
dict.prevNode(-1);
return ready;
}
function checkDictionary(moves) {
if (!debug) {
return true;
}
var isValid = true;
const dict = document.querySelector("#dictionary-board").editor;
moves.forEach(move => {
isValid &= dict.navigate(move.x, move.y, false);
})
dict.prevNode(-1);// reset the dictionary board
return isValid;
}
function submit() {
var moves = extractMoves();
if (moves.length === 0) {
return;
}
var solution = getSolution();
var hints = getInputEditor().check(solution);
if (debug) {
console.log("guess: " + pretty_print(moves));
console.log("solution: " + pretty_print(solution));
console.log(hints);
}
submissions.push(moves);
guesses.push(hints);
var message = "";
if (moves.length < solution.length) {
message = "Too few moves";
} else if (moves.length > solution.length) {
message = "Too many moves";
}
const solved = wasCorrect(hints, solution);
if (solved) {
if (hints.length > solution.length) {
message = " Good Enough!";
} else {
switch(guesses.length) {
case 1:
message = " Genius";
break;
case 2:
message = " Magnificent";
break;
case 3:
message = " Impressive";
break;
case 4:
message = " Splendid";
break;
case 5:
message = " Great";
break;
default:
message = " Phew";
}
}
} else if (!checkDictionary(moves)) {
message = "Not present in the dictionary?";
}
storageSave(getTitle(),{
submissions: submissions,
solved: solved
});
display(hints.join(""), message);
if (solved) {
toggleButtons();
}
}
function startOneColorMode() {
const solution = getSolution();
const editor = getInputEditor();
for (var i = solution.length - 1; i >= 0; i--) {
var move = solution[i];
editor.getRoot().addMarkup(move.x,move.y,2);
}
editor.toggleVariantStyle(); // toggles a redraw
}
/* functions to save and restore previous attempts */
function storageSave(key, val) {
if (localStorage) {
localStorage.setItem(key, JSON.stringify(val));
}
}
function storageLoad(key) {
if (localStorage) {
const json = localStorage.getItem(key);
if (json) {
return JSON.parse(json);
}
}
return null;
}
function storageClear(key) {
if (localStorage) {
if (key) {
localStorage.removeItem(key);
} else {
localStorage.clear();
}
}
}
function tryRestore() {
const dark = storageLoad("dark");
if (dark === "on") {
document.querySelector('button[title="Toggle dark theme"]').click();
}
const zoom = storageLoad("zoom");
if (zoom) {
const editor = getInputEditor();
editor.setZoom(zoom);
}
const saved = storageLoad(getTitle());
if (saved && saved["submissions"] !== null && saved["submissions"].length > 0) {
const submissions = saved["submissions"];
const editor = getInputEditor();
for (var i = 0; i < submissions.length; i++) {
const submission = submissions[i];
submission.forEach(move => {
editor.click(move.x, move.y, false, false);
});
submit();
// after replaying each but the last, reset to root to keep replaying:
if (i < submissions.length - 1) {
editor.prevNode(-1);
} else {
// for the last replay, if unsolved, also reset
// if solved, will not reset to display the solution
if (!saved["solved"]) {
editor.prevNode(-1);
}
}
};
return true;
} else {
storageClear(getTitle(-1));
}
return false;
}
const submissions = [];
const guesses = [];
window.onload = function() {
if (clearStorage) {
localStorage.clear();
}
besogo.autoInit();
document.querySelector("div#title").innerText=getTitle();
getInputEditor().addListener(function(msg) {
if (msg.zoom) {
storageSave("zoom", msg.zoom);
}
if (msg.dark === false || msg.dark === true) {
const value = msg.dark ? "on" : "off";
storageSave("dark", value);
}
})
var wait = setInterval(function () {
if (isDictionaryReady()) {
const restored = tryRestore();
if (oneColor && !restored) {
startOneColorMode();
}
clearInterval(wait);
}
}, 100);
};