summaryrefslogtreecommitdiff
path: root/static/script.js
blob: b7544720f4e96ae56e02de606b94cd3cf1a6a606 (plain)
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
"use strict";

var currentBoard = null;
var selected = {};
var won = []

function newGroup() {
    var categoryPoint = Math.random();
    for (var category of corpus) {
        if (categoryPoint < category.portion) {
            continue;
        }
        var group = category.groups[category.groups.length * Math.random() << 0]
        var clues = randomSelect(group.clues, 4)
        break;
    }

    return {
        hint: group.hint,
        clues: clues,
        fullClues: group.clues,
    };
}

function first(xs) {
    return xs[0]
}

function newNonintersectingGroup(oldGroups) {
    var group = newGroup();
    for (var oldGroup of oldGroups) {
        var intersection = oldGroup.fullClues.map(first).filter(value => group.fullClues.map(first).includes(value));
        if (intersection.length > 0) {
            return newNonintersectingGroup(oldGroups);
        }
    }
    return group;
}

function newBoard() {
    var groups = [];
    for (var i = 0; i < 4; i++) {
        var group = newNonintersectingGroup(groups);
        groups.push(group);
    }
    var newGroups = [];
    for (var i = 0; i < 4; i++) {
        newGroups.push({hint: groups[i].hint, clues: groups[i].clues});
    }
    return newGroups;
}

function chooseBox(box) {
    var clue = parseInt(box.getAttribute('x-clue'));
    if (box.classList.contains('selected')) {
        box.classList.remove('selected');
        delete selected[clue];
    } else {
        box.classList.add('selected');
        selected[clue] = parseInt(box.getAttribute('x-group'));
    }

    if (Object.keys(selected).length == 4) {
        var [ok, grp] = checkGuess(selected)
        if (ok) {
            consume(grp);
        } else {
            clear();
        }
    }
}

function clear() {
    selected = {}
    var els = [...document.getElementsByClassName('selected')];
    for (var i = 0; i < 4; i++) {
        els[i].classList.remove('selected');
    }
}

function consume(grp) {
    won.push(grp)
    selected = {}
    var els = document.querySelectorAll(`[x-group="${grp}"]`);
    for (var el of els) {
        el.remove();
    }
    var group = currentBoard[grp];

    document.getElementById('answers').innerHTML +=
        `<div class="answer">
            <div class="answerline">${group.hint} <a class="flag" href="#" x-flag="${group.hint}">[flag]</a></div>
            <div class="clues">${group.clues.map(renderAnswerClue).join('')}</div>
        </div>`;
}

document.getElementById('answers').addEventListener('click', function(evt) {
    if (evt.target.classList.contains('flag')) {
        evt.preventDefault();
        let options = {
            method: 'GET',
            headers: {}
        };

        fetch('/flag?q=' + encodeURIComponent(evt.target.getAttribute('x-flag')), options)
        .then(body => {
            var el = document.createElement('span')
            el.innerText = `flagged`
            el.classList.add('flagged')
            evt.target.replaceWith(el)
        });
    }
});

function checkGuess(selected) {
    var ans = null;
    for (var clue of Object.keys(selected)) {
        var group = selected[clue];
        if (ans === null) {
            ans = group;
        } else if (ans != group) {
            return [false, 0];
        }
    }
    return [true, group];
}

function renderAnswerClue(clue) {
    var s = `<details class="answerclue"><summary>${clue[0]}</summary><span class="definition">${clue[1]}</span></details>`;
    return s
}

function serializeBoard(board) {
    var copy = []
    for (var group of board) {
        copy.push({
            clues: group.clues,
            hint: group.hint,
        })
    }
    return encodeURIComponent(btoa(JSON.stringify(copy)))
}

function deserializeBoard(s) {
    var copy = JSON.parse(atob(decodeURIComponent(s)))
    var board = []
    for (var group of copy) {
        board.push({
            clues: group.clues,
            hint: group.hint,
        })
    }
    return board;
}

function generateUrl(board) {
    return `${location.origin}/infinite-connections?q=${serializeBoard(board)}`
}

function startBoard(board) {
    selected = {};

    document.getElementById('url').value = generateUrl(board);

    document.getElementById('answers').innerHTML = '';
    var el = document.getElementById('board');

    currentBoard = board;
    won = [];

    var clues = [];
    for (var [i, group] of board.entries()) {
        for (var [j, clue] of group.clues.entries()) {
            clues.push([i, i*4+j, clue]);
        }
    }

    shuffle(clues);
    el.innerHTML = ``;
    for (var [i, j, clue] of clues) {
        el.innerHTML += `<div class="box" x-group=${i} x-clue=${j}>${clue[0]}</div>`;
    }
}

function giveUp() {
    for (var i = 0; i < 4; i++) {
        if (!won.includes(i)) {
            consume(i);
        }
    }
}

document.getElementById('board').addEventListener('click', function(evt) {
    if (evt.target.classList.contains('box')) {
        evt.preventDefault();
        chooseBox(evt.target);
    }
});

document.getElementById('new-board').addEventListener('click', function(evt) {
    startBoard(newBoard());
});

document.getElementById('copy-link').addEventListener('click', function(evt) {
    navigator.clipboard.writeText(generateUrl(currentBoard))
});

document.getElementById('clear').addEventListener('click', function(evt) {
    clear();
});

document.getElementById('reset').addEventListener('click', function(evt) {
    startBoard(currentBoard);
});

document.getElementById('give-up').addEventListener('click', function(evt) {
    giveUp();
});


window.onload = function() {
    var urlParams = new URLSearchParams(window.location.search);
    var q = urlParams.get('q')
    if (q) {
        startBoard(deserializeBoard(q));
        return;
    }
    startBoard(newBoard());
}

// Source: https://stackoverflow.com/a/19270021
function randomSelect(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
        throw new RangeError("randomSelect: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
    return result;
}

// Source: https://stackoverflow.com/a/2450976
function shuffle(array) {
  let currentIndex = array.length,  randomIndex;

  // While there remain elements to shuffle.
  while (currentIndex > 0) {

    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }

  return array;
}