-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
384 lines (372 loc) · 11.6 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
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
384
const debug = window.location.href.includes("debug=true");
const clearStorage = window.location.href.includes("clearStorage=true");
const oneColor = storageLoad('oneColor');
const hardMode = storageLoad('hardMode');
var circles = ["🟢","⚪","🟣"];
const GREEN = "🟢";
const WHITE = "⚪";
const YELLOW = "🟣";
const GREEN_SQUARE = "🟩";
const WHITE_SQUARE = "⬜";
const YELLOW_SQUARE = "🟪";
const TODAY = new Date();
function toggleHardMode() {
storageSave('hardMode', !hardMode);
window.location.reload();
}
function toggleOneColor() {
storageSave('oneColor', !oneColor);
window.location.reload();
}
/* 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);
const SQUARES = supportsAll([GREEN_SQUARE, YELLOW_SQUARE, WHITE_SQUARE]);
/* 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);
return Math.ceil(Math.abs((start - TODAY) / dayMillis));
}
const PUZZLE_NUMBER = getNumber();
function getTitle(n) {
if (typeof n === "undefined") {
n = 0;
}
var difficulty = " (" + getSolution().solution.length + " moves";
if (oneColor) {
difficulty += ", one color";
}
if (hardMode) {
difficulty += ", hard";
}
difficulty += ")";
return "Josekle #" + (PUZZLE_NUMBER + n) + difficulty;
}
function getSolution() {
if (PUZZLE_NUMBER < 15) {
const oldPuzzle = puzzles[PUZZLE_NUMBER % puzzles.length]; //old puzzles
return {"node_id": null, "solution": oldPuzzle};
} else {
if (hardMode) {
return hardPuzzles[PUZZLE_NUMBER % hardPuzzles.length];
} else {
return easyPuzzles[PUZZLE_NUMBER % easyPuzzles.length];
}
}
}
/* functions to get inputted sequence from besogo */
function extractMovesFrom(current) {
var moves=[];
if (current.submitted) {
showPopup("Already submitted");
return [];
}
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] !== GREEN) {
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);
showPopup("Copied to clipboard");
}
function makeButton(value, title, onclick) {
element = document.createElement('input');
element.type = 'button';
element.value = value;
element.title = title;
element.onclick = onclick;
return element;
}
function scrollHints() {
document.querySelector(".besogo-hint").scrollTop = document.querySelector(".besogo-hint").scrollHeight;
}
function toggleButtons() {
document.querySelector('#output').appendChild(
makeButton("Share", "Copy results to clipboard", share)
);
document.querySelector('#Submit').classList.add("hidden");
}
function showExplorerLink(nodeId) {
if (nodeId === null || nodeId === undefined) { // old puzzles don't have node
return;
}
document.querySelector("#output").appendChild(
makeButton("OGS Explorer", "View this joseki on OGS Joseki Explorer", function() {
window.location="https://online-go.com/joseki/" + nodeId;
}));
}
function display(hints, message) {
var output = document.querySelector("#output");
var p = document.createElement("p");
if (CIRCLES && SQUARES) {
p.innerText = hints + " " + message;
output.appendChild(p);
} else {
var rest = [];
var split = [...hints];
const symbols = [YELLOW, GREEN, WHITE, YELLOW_SQUARE, GREEN_SQUARE, WHITE_SQUARE];
const imageNames = ["yellow", "green", "white", "yellow-square", "green-square", "white-square"];
split.forEach(c => {
const foundIndex = symbols.indexOf(c);
if (foundIndex >= 0) {
var img = document.createElement("img");
img.src = `img/emojis/${imageNames[foundIndex]}.png`;
img.className = "besogo-emoji";
p.appendChild(img);
} else {
rest.push(c);
}
});
p.innerHTML += " " + message;
output.appendChild(p);
}
scrollHints();
}
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) {
var isValid = true;
let counter = 0;
const dict = document.querySelector("#dictionary-board").editor;
moves.forEach(move => {
isValid &= dict.navigate(move.x, move.y, false);
if (isValid) ++counter;
})
dict.prevNode(-1);// reset the dictionary board
return counter;
}
function showPopup(text) {
var popup = document.querySelector("#notify");
popup.classList.add("active");
document.getElementById('notify-text').innerText = text;
setTimeout(function(){
popup.classList.remove("active");
}, 1200);
}
function submit() {
var moves = extractMoves();
if (moves.length === 0) {
return;
}
const puzzle = getSolution();
const solution = puzzle.solution;
if (moves.length > solution.length) {
showPopup("Too many moves");
return;
}
var hints = getInputEditor().check(solution);
var firstUnknownMoveIndex = checkDictionary(moves);
if (firstUnknownMoveIndex < moves.length) {
hints = hints.map((circle, index) => {
if (index < firstUnknownMoveIndex) {
return circle;
} else {
if (circle === GREEN) return GREEN_SQUARE;
if (circle === YELLOW) return YELLOW_SQUARE;
if (circle === WHITE) return WHITE_SQUARE;
}
})
}
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 (firstUnknownMoveIndex < moves.length) {
message = "Not present in the dictionary?";
}
storageSave(getTitle(),{
submissions: submissions,
solved: solved,
});
display(hints.join(""), message);
if (solved) {
toggleButtons();
showExplorerLink(puzzle.node_id);
scrollHints();
}
}
function startOneColorMode() {
const puzzle = getSolution();
const solution = puzzle.solution;
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.setVariantStyle(editor.getVariantStyle()); // 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();
initModal();
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()) {
if (oneColor) {
startOneColorMode();
}
tryRestore();
clearInterval(wait);
}
}, 100);
};