-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathbingo.js
737 lines (654 loc) · 17.7 KB
/
bingo.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
var DIFFICULTY;
var SEED;
var LAYOUT;
var HIDDEN;
var STREAMER_MODE;
var VERSION;
var DIFFICULTYTEXT = [ "Very Easy", "Easy", "Medium", "Hard", "Very Hard"];
const DEFAULT_SQUARE_CLASS_NAME = "greysquare";
const ALL_COLOURS = [DEFAULT_SQUARE_CLASS_NAME, "bluesquare", "greensquare", "redsquare", "yellowsquare", "cyansquare", "brownsquare"];
var COLOUR_SELECTIONS = [
[DEFAULT_SQUARE_CLASS_NAME, "greensquare"],
[DEFAULT_SQUARE_CLASS_NAME, "bluesquare", "greensquare", "redsquare"],
ALL_COLOURS
];
var COLOURCOUNT = 1; // used as an index in COLOUR_SELECTIONS and COLOURCOUNTTEXT
var COLOURCOUNTTEXT = [ "Green only", "Blue, Green, Red", "6 Colours"];
var COLOURSYMBOLS = false;
var DARK_MODE = false;
const NEVER_HIGHLIGHT_CLASS_NAME = "greensquare";
var hoveredSquare;
// Defines which version uses which goals array/algorithm function
// (by convention `bingoList_v1` is defined in the file goals_v1.js,
// but it could be different of course).
//
// Of course you wouldn't want to create a new version for every change,
// just when you feel like you want to "release" a stable state. For that
// either rename the current unstable version (and then maybe create files
// for a new unstable version) or create new files/a new entry for the
// release.
//
// The version is a string, so theoretically it doesn't have to just be
// numbers (although maybe just numbers would be better).
//
// The name is used for display purposes only.
var VERSIONS = [
{ id:"1", name:"v1 [1.12.2]", goals: bingoList_v1, generator: generator_v1, stable: true },
{ id:"2", name:"v2 [1.12.2]", goals: bingoList_v2, generator: generator_v2, stable: true },
{ id:"3", name:"v3 [1.13.2]", goals: bingoList_v3, generator: generator_v2, stable: true },
{ id:"4", name:"v4 [1.16.5]", goals: bingoList_v4, generator: generator_v3, stable: true },
{ id:"dev", name:"dev [1.16.5]", goals: bingoList_v5, generator: generator_v3, stable: false }, // Dev version
];
// This is the newest stable version that users not specifying a version will get
var LATEST_VERSION = "4";
const SQUARE_COUNT = 25;
const NODE_TYPE_TEXT = 3;
const TOOLTIP_TEXT_ATTR_NAME = "data-tooltiptext";
const TOOLTIP_IMAGE_ATTR_NAME = "data-tooltipimg";
const COLOUR_COUNT_SETTING_NAME = "bingoColourCount";
const COLOUR_SYMBOLS_SETTING_NAME = "bingoColourSymbols";
const COLOUR_THEME_SETTING_NAME = "bingoColourTheme";
const DARK_MODE_CLASS_NAME = "dark";
const SHOW_OPTIONS_MENU_CLASS_NAME = "show-options";
const SHOW_EXPORT_CLASS_NAME = "show-export";
// Dropdowns and pause menu handling.
$(document).click(function(event) {
const className = event.target.className;
if (className.includes('dropdown-button')) {
// if a button was clicked, toggle nearby dropdown
$(event.target).siblings('.dropdown').toggle(100);
return;
}
if (!$(event.target).closest(".dropdown-holder").length) {
// Hide if click was anywhere BUT on a dropdown menu
$('.dropdown').each(function() {
$(this).hide(100);
});
}
if (!$(event.target).closest(".pause-menu").length) {
if (event.target.id != "options-toggle-button") {
// Hide if click was anywhere BUT on a pause menu
hideOptionsMenu();
}
}
if (className.includes("pause-menu")) {
// hide if clicking on pause-menu layout, but not on buttons/sliders
hideOptionsMenu();
}
});
$(document).ready(function()
{
// Set the background to a random image
document.body.className += "bg" + (Math.floor(Math.random() * 10) + 1);
// On clicking a goal square
const bingoSquares = $("#bingo td");
bingoSquares.click(function()
{
const square = $(this);
setSquareColor(square, nextColour(square));
});
bingoSquares.contextmenu(function()
{
const square = $(this);
setSquareColor(square, prevColour(square));
return false;
});
const goalTooltip = $("#goalTooltip");
// On hovering a goal square
$("#bingo td img").hover(function()
{
goalTooltip.show();
},function()
{
// After hovering, hide the tooltip again
goalTooltip.hide();
});
// Move the tooltip with the mouse
$(document).mousemove(function(e)
{
var x = e.pageX + 2;
var y = e.pageY + 2;
var width = goalTooltip.outerWidth() + 25;
var height = goalTooltip.height() + 50;
var maxX = $(window).width() + window.pageXOffset;
var maxY = $(window).height() + window.pageYOffset;
if (x + width > maxX) {
x = maxX - width;
}
if (y + height > maxY) {
y = y - height;
}
goalTooltip.css({left:x, top:y});
});
bingoSquares.hover(function(e)
{
hoveredSquare = $(this);
// Fill the #goalTooltip with the content from the goal
var tooltipImg = hoveredSquare.attr(TOOLTIP_IMAGE_ATTR_NAME);
var tooltipText = hoveredSquare.attr(TOOLTIP_TEXT_ATTR_NAME);
$("#tooltipimg").attr('src', tooltipImg);
$("#tooltipimg").toggle(tooltipImg != "");
$("#tooltiptext").text(tooltipText);
},function(e)
{
hoveredSquare = null;
});
const SHORTCUT_COLOURS = {
48: DEFAULT_SQUARE_CLASS_NAME,
96: DEFAULT_SQUARE_CLASS_NAME, // Numpad
49: "bluesquare",
97: "bluesquare",
50: "greensquare",
98: "greensquare",
51: "redsquare",
99: "redsquare",
52: "yellowsquare",
100: "yellowsquare",
53: "cyansquare",
101: "cyansquare",
54: "brownsquare",
102: "brownsquare",
81 /* Q */: DEFAULT_SQUARE_CLASS_NAME
};
$(document).on("keydown", function(e)
{
if (hoveredSquare && e.which in SHORTCUT_COLOURS)
{
setSquareColor(hoveredSquare, SHORTCUT_COLOURS[e.which]);
}
if (e.keyCode == 27 /* Esc */)
{
toggleOptionsMenu();
}
});
fillVersionSelection();
$("#version_selection").change(function() {
changeVersion($(this).val());
});
$(".pause-menu-close").click(function() {
hideOptionsMenu();
});
$("#options-toggle-button").click(function() {
toggleOptionsMenu();
});
window.onpopstate = function(event)
{
loadSettings();
};
loadSettings();
});
function toggleOptionsMenu()
{
$("#bingo-box").toggleClass(SHOW_OPTIONS_MENU_CLASS_NAME);
}
function showOptionsMenu()
{
$("#bingo-box").addClass(SHOW_OPTIONS_MENU_CLASS_NAME);
}
function hideOptionsMenu()
{
$("#bingo-box").removeClass(SHOW_OPTIONS_MENU_CLASS_NAME);
}
function getColourClass(square)
{
return ALL_COLOURS.find(c => square.hasClass(c));
}
function nextColour(square)
{
return anotherColour(square, 1);
}
function prevColour(square)
{
return anotherColour(square, -1);
}
function anotherColour(square, increment)
{
const colourSelection = COLOUR_SELECTIONS[COLOURCOUNT];
const currColour = getColourClass(square);
const currIndex = colourSelection.indexOf(currColour);
if (currIndex == -1)
{
// default to second colour
return colourSelection[1];
}
const nextIndex = (colourSelection.length + currIndex + increment) % colourSelection.length;
return colourSelection[nextIndex];
}
function loadSettings()
{
getSettingsFromURL();
getSettingsFromLocalStorage();
}
function getSettingsFromURL()
{
/**
* URL Format: ?s=[difficulty]-[hideTable]_[seed]
*
* The seed should always be last, so in order to be able to add more settings,
* settings and the seed are separated from eachother.
*/
var split = gup("s").split("_");
if (split.length == 2)
{
var settings = split[0].split("-");
SEED = split[1];
DIFFICULTY = parseInt(settings[0]);
HIDDEN = settings[1] == "1";
STREAMER_MODE = settings[2] == "1";
var selectedVersion = settings[3];
}
// Set default values
if (isNaN(DIFFICULTY) || DIFFICULTY < 1 || DIFFICULTY > 5)
{
DIFFICULTY = 3;
}
VERSION = getVersion(selectedVersion);
if (VERSION == undefined) {
VERSION = getVersion(LATEST_VERSION);
}
// If there isn't a seed, make a new one
if (!SEED)
{
newSeed(false);
}
// Grab the layout setting from the URL
LAYOUT = gup( 'layout' );
if (LAYOUT == "set")
{
// Set the layout settings' text
// document.getElementById("whatlayout").innerHTML="Set Layout";
}
else
{
LAYOUT = "random";
// document.getElementById("whatlayout").innerHTML="Random Layout";
}
updateHidden();
updateStreamerMode();
updateDifficulty();
updateVersion();
generateNewSheet();
}
function getSettingsFromLocalStorage()
{
const savedColourSymbols = localStorage.getItem(COLOUR_SYMBOLS_SETTING_NAME);
if (savedColourSymbols != null)
{
COLOURSYMBOLS = savedColourSymbols == "true" ? true : false;
}
updateColourSymbols();
const savedColourCount = localStorage.getItem(COLOUR_COUNT_SETTING_NAME);
if (savedColourCount != null)
{
changeColourCount(savedColourCount);
}
else
{
// if not stored, then just use the default
updateColourCount();
}
const savedColourTheme = localStorage.getItem(COLOUR_THEME_SETTING_NAME);
DARK_MODE = (savedColourTheme == DARK_MODE_CLASS_NAME);
updateDarkMode();
}
/*
* Call given function for every square. The given function shall take two arguments:
* 1. an index
* 2. the square's element
*/
function forEachSquare(f)
{
for (var i = 0; i < SQUARE_COUNT; i++)
{
var slotId = "#slot"+ (i + 1);
var square = $(slotId);
f(i, square);
}
}
function generateNewSheet()
{
let seedInput = $(".seed-input");
seedInput.val(SEED);
seedInput.attr("size", Math.max(SEED.length, 5));
// Reset the random seed
Math.seedrandom(SEED);
// Reset every goal square
forEachSquare((i, square) => {
square.contents().filter(function(){ return this.nodeType == NODE_TYPE_TEXT; }).remove();
setSquareColor(square, DEFAULT_SQUARE_CLASS_NAME);
});
var result = VERSION.generator(LAYOUT, DIFFICULTY, VERSION.goals);
forEachSquare((i, square) => {
var goal = result[i];
//square.append(goal.generatedName + " " + goal.difficulty);
square.append(goal.generatedName);
square.attr(TOOLTIP_TEXT_ATTR_NAME, goal.tooltiptext || "");
square.attr(TOOLTIP_IMAGE_ATTR_NAME, goal.tooltipimg || "");
if (goal.tags && goal.tags.findIndex(t => t.name == "Never") != -1)
{
setSquareColor(square, NEVER_HIGHLIGHT_CLASS_NAME);
}
});
}
// Create a new seed
function newSeed(remakeSheet)
{
// Remove the current seed
Math.seedrandom();
// Making a new 5 digit seed
SEED = Math.floor((Math.random() * 90000) + 10000).toString();
// Set the new seed
Math.seedrandom(SEED);
// Update the seed in the URL
pushNewUrl();
// If a new sheet is required, generate one
if (remakeSheet)
{
generateNewSheet();
}
}
// Change the layout
function changeLayout()
{
// Change the layout based on the current layout
if (LAYOUT == "set")
{
LAYOUT = "random";
// Update the button's text
document.getElementById("whatlayout").innerHTML="Set Layout";
}
else
{
LAYOUT = "set";
document.getElementById("whatlayout").innerHTML="Random Layout";
}
// Update the URL
pushNewUrl();
// Generate a new sheet
generateNewSheet();
}
function updateHidden()
{
const box = $("#bingo-box");
const hiddenCssClassName = "hidden";
const button = document.getElementById("ishidden");
if (HIDDEN)
{
// Hide the goals and change the hidden setting's text
box.addClass(hiddenCssClassName);
button.innerHTML = "Show Table";
}
else
{
HIDDEN = false;
// Show the goals and change the hidden setting's text
box.removeClass(hiddenCssClassName);
button.innerHTML = "Hide Table";
}
}
function toggleHidden()
{
// Invert HIDDEN setting, then update
HIDDEN = !HIDDEN;
updateHidden();
pushNewUrl();
}
function popoutBingoCard(){
window.open(window.location.href, "_blank", "toolbar=no, status=no, menubar=no, scrollbars=no, width=745, height=715");
}
function toggleStreamerMode()
{
STREAMER_MODE = !STREAMER_MODE;
$(".dropdown").hide();
hideOptionsMenu();
updateStreamerMode();
pushNewUrl();
}
function updateStreamerMode()
{
const cssClassName = "streamer-mode";
const body = $("body");
if (STREAMER_MODE)
{
body.addClass(cssClassName);
}
else
{
body.removeClass(cssClassName);
}
}
// TODO reduce code duplication between sliders
function updateDifficulty()
{
$(".difficulty-text").text(DIFFICULTYTEXT[DIFFICULTY - 1]);
$("#difficultyRange").val(DIFFICULTY);
}
function changeDifficulty(value)
{
DIFFICULTY = parseInt(value);
updateDifficulty();
generateNewSheet();
pushNewUrl();
}
function changeSeed(value)
{
SEED = value;
generateNewSheet();
pushNewUrl();
}
function updateColourCount()
{
$(".colourCount-text").text(COLOURCOUNTTEXT[COLOURCOUNT]);
$("#colourCountRange").val(COLOURCOUNT);
}
function changeColourCount(value)
{
const maybeColourCount = parseInt(value);
if (isNaN(maybeColourCount))
{
COLOURCOUNT = 1;
}
else
{
COLOURCOUNT = Math.max(0, Math.min(COLOUR_SELECTIONS.length - 1, maybeColourCount));
}
updateColourCount();
pushNewLocalSetting(COLOUR_COUNT_SETTING_NAME, COLOURCOUNT);
}
function updateColourSymbols()
{
$(".symbol").css("display", !COLOURSYMBOLS ? "none" : "inline");
const button = document.getElementById("colourSymbols");
button.innerHTML = COLOURSYMBOLS ? "Hide Symbols" : "Show Symbols";
}
function toggleColourSymbols()
{
COLOURSYMBOLS = !COLOURSYMBOLS;
updateColourSymbols();
pushNewLocalSetting(COLOUR_SYMBOLS_SETTING_NAME, COLOURSYMBOLS);
}
function updateDarkMode()
{
const smoothTransitionClassName = "smooth-transition";
const body = $("body");
body.addClass(smoothTransitionClassName);
if (DARK_MODE)
{
body.addClass(DARK_MODE_CLASS_NAME);
}
else
{
body.removeClass(DARK_MODE_CLASS_NAME);
}
$(".dark-mode-button").text(DARK_MODE ? "Light Mode" : "Dark Mode");
setTimeout(() => {
body.removeClass(smoothTransitionClassName);
}, 1000);
}
function toggleDarkMode()
{
DARK_MODE = !DARK_MODE;
updateDarkMode();
pushNewLocalSetting(COLOUR_THEME_SETTING_NAME, DARK_MODE ? DARK_MODE_CLASS_NAME : "light");
}
function pushNewUrl()
{
var hidden = HIDDEN ? "1" : "0";
var streamerMode = STREAMER_MODE ? "1" : "0";
window.history.pushState('', "Sheet", "?s=" + DIFFICULTY + "-" + hidden + "-" + streamerMode + "-" + VERSION.id + "_" + SEED);
}
function pushNewLocalSetting(name, value)
{
try
{
localStorage.setItem(name, value.toString());
}
catch (ignored)
{
}
}
function getVersion(versionId)
{
for (var i=0; i<VERSIONS.length; i++)
{
if (versionId == VERSIONS[i].id)
{
return VERSIONS[i];
}
}
return undefined;
}
function updateVersion()
{
$("#version_selection").val(VERSION.id);
$("#versions-toggle-button").html(VERSION.name);
$(".versionText").html(VERSION.name);
if (VERSION.id != LATEST_VERSION && VERSION.stable)
{
$("#version_notice").css("display", "block");
} else {
$("#version_notice").css("display", "none");
}
if (!VERSION.stable) {
$("#version_notice_unstable").css("display", "block");
} else {
$("#version_notice_unstable").css("display", "none");
}
}
function changeVersion(versionId)
{
VERSION = getVersion(versionId);
generateNewSheet();
updateVersion();
pushNewUrl();
}
function fillVersionSelection()
{
VERSIONS.forEach(function(value) {
var label = value.name;
if (value.stable)
{
label += " (stable)";
}
else
{
label += " (WIP)";
}
$("#version_selection").append($('<option></option>').val(value.id).html(label))
var button = $('<button class="button version-button"></button>');
$("#versions-dropdown-main").append(button);
button.html(label);
button.click(function() {
changeVersion(value.id);
});
});
}
function setSquareColor(square, colorClass)
{
square.removeClass(ALL_COLOURS);
square.addClass(colorClass);
}
function copySeedToClipboard(id, event)
{
var id = "#"+id;
if (navigator.clipboard)
{
navigator.clipboard.writeText($(id).val()).then(ignored => {
showCopiedTooltip(event);
}, err => {
console.error('Async: Could not copy text: ', err);
alert("Failed to copy seed to clipboard :/");
});
}
else
{
$(id).select();
try
{
var successful = document.execCommand('copy');
if (!successful)
{
alert("Failed to copy seed to clipboard :/");
}
else
{
showCopiedTooltip(event);
}
}
catch (err)
{
alert("Failed to copy seed to clipboard :/");
}
// Deselect
$(id).blur();
}
}
function showCopiedTooltip(event)
{
const offset = $(event.target).offset();
const x = offset.left + event.target.offsetWidth;
const y = offset.top;
$("#copiedTooltip").css({left:x, top: y})
.css("display", "block")
.delay(100)
.fadeOut(1000, () => {
$(this).hide().fadeIn(0);
});
}
function createGoalExport()
{
let result = [];
forEachSquare((i, square) => {
result.push({
name: square.text(),
tooltip: square.attr(TOOLTIP_TEXT_ATTR_NAME)
});
});
$("#export textarea").text(JSON.stringify(result));
$("body").addClass(SHOW_EXPORT_CLASS_NAME);
}
function hideGoalExport()
{
$("body").removeClass(SHOW_EXPORT_CLASS_NAME);
}
// Made this a function for readability and ease of use
function getRandomInt(min, max)
{
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
function gup( name )
{
let params = new URLSearchParams(document.location.search);
let result = params.get(name);
if (result == null)
{
return "";
}
else
{
return result;
}
}
// random source: www.engin33r.net/bingo/random.js
(function(j,i,g,m,k,n,o){function q(b){var e,f,a=this,c=b.length,d=0,h=a.i=a.j=a.m=0;a.S=[];a.c=[];for(c||(b=[c++]);d<g;)a.S[d]=d++;for(d=0;d<g;d++)e=a.S[d],h=h+e+b[d%c]&g-1,f=a.S[h],a.S[d]=f,a.S[h]=e;a.g=function(b){var c=a.S,d=a.i+1&g-1,e=c[d],f=a.j+e&g-1,h=c[f];c[d]=h;c[f]=e;for(var i=c[e+h&g-1];--b;)d=d+1&g-1,e=c[d],f=f+e&g-1,h=c[f],c[d]=h,c[f]=e,i=i*g+c[e+h&g-1];a.i=d;a.j=f;return i};a.g(g)}function p(b,e,f,a,c){f=[];c=typeof b;if(e&&c=="object")for(a in b)if(a.indexOf("S")<5)try{f.push(p(b[a],e-1))}catch(d){}return f.length?f:b+(c!="string"?"\0":"")}function l(b,e,f,a){b+="";for(a=f=0;a<b.length;a++){var c=e,d=a&g-1,h=(f^=e[a&g-1]*19)+b.charCodeAt(a);c[d]=h&g-1}b="";for(a in e)b+=String.fromCharCode(e[a]);return b}i.seedrandom=function(b,e){var f=[],a;b=l(p(e?[b,j]:arguments.length?b:[(new Date).getTime(),j,window],3),f);a=new q(f);l(a.S,j);i.random=function(){for(var c=a.g(m),d=o,b=0;c<k;)c=(c+b)*g,d*=g,b=a.g(1);for(;c>=n;)c/=2,d/=2,b>>>=1;return(c+b)/d};return b};o=i.pow(g,m);k=i.pow(2,k);n=k*2;l(i.random(),j)})([],Math,256,6,52);