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

var entryEl = document.getElementById("entry")
var guessesEl = document.getElementById("guesses")
var winEl = document.getElementById("win")

function renderWord(word, wordIdx, guess, score, offset) {
    var els = []
    var c = 0;
    for (var syllable of word) {
        var sylEls = []

        var shouldStress = syllable[0] == "/";
        if (shouldStress) {
            syllable = syllable.slice(1)
        }
        var stress = shouldStress ? "stress" : ""
        for (var _ in syllable) {
            var charclass = ''
            var able = ''
            if (score) {
                if (score.greens[c]) {
                    charclass += 'green'
                } else if (score.yellows[c]) {
                    charclass += 'yellow'
                } else if (score.greys[c]) {
                    charclass += 'grey'
                }
                able = 'disabled'
            }
            var val = guess ? guess[wordIdx][c] : ''
            var typ = guess ? 'solbox' : 'entrybox'
            sylEls.push(`<div data-word="${wordIdx}" data-character="${c}" data-offset="${c+offset}" class="box ${typ} ${charclass}">${val}</div>`)
            c++;
        }

        els.push(`<div class="syllable ` + stress + `">` + sylEls.join('') + `</div>`)
    }

    return `<div class="word">` + els.join('') + `</div>`
}

function renderLine(line, guess, scores) {
    var els = []
    var offset = 0;
    for (var wordIdx in line) {
        var word = line[wordIdx]
        els.push(renderWord(word, wordIdx, guess, scores && scores[wordIdx], offset))
        offset += word.join('').replaceAll('/', '').length
    }
    return `<div class="line">` + els.join('') + `</div>`
}

function consumeInput() {
    var els = Array.from(document.getElementsByClassName("entrybox"));
    for (var el of els) {
        if (el.innerText.trim().length == '') {
            return null
        }
    }
    els.sort((x, y) => {
        var xword = x.getAttribute('data-word')
        var xchar = x.getAttribute('data-character')
        var yword = y.getAttribute('data-word')
        var ychar = y.getAttribute('data-character')

        if (xword != yword) {
            return xword - yword;
        }
        return xchar - ychar;
    })
    var words = {}
    for (var el of els) {
        words[el.getAttribute('data-word')] = (words[el.getAttribute('data-word')] || '') +
                el.innerText.trim().toUpperCase()
    }
    return words
}

function scoreLine(guess, answer) {
    var scores = []
    for (var idx in guess) {
        var guessword = guess[idx]
        var answerword = answer[idx].join('').replaceAll('/', '').toUpperCase()
        scores.push(scoreWord(guessword, answerword))
    }
    return scores
}

function scoreWord(guess, answer) {
    var greens = {}
    var yellows = {}
    var greys = {}
    var counts = {}
    var placed = {}
    for (var idx in guess) {
        if (guess[idx] == answer[idx]) {
            greens[idx] = 1
            placed[answer[idx]] = (placed[answer[idx]] || 0) + 1
        }
        counts[answer[idx]] = (counts[answer[idx]] || 0) + 1
    }
    for (var idx in guess) {
        if (greens[idx]) {
            continue
        }
        if ((placed[guess[idx]] || 0) < counts[guess[idx]]) {
            yellows[idx] = 1
            placed[guess[idx]] = (placed[guess[idx]] || 0) + 1;
        } else {
            greys[idx] = 1
        }
    }
    return {greens: greens, yellows: yellows, greys: greys}
}

var focused = null;

document.getElementById('clear').onclick = function(e) {
    e.preventDefault();
    for (var el of document.getElementsByClassName('entrybox')) {
        el.innerText = ''
    }
    unfocus(document.querySelector(`[data-offset="${focused}"]`));
    focus(document.querySelector(`[data-offset="0"]`))
}

document.getElementById('check').addEventListener('click', function(e) {
    var guess = consumeInput()
    if (guess == null) {
        return;
    }
    guesses.push(guess)
    var scores = scoreLine(guess, challenge.line)
    var linehtml = renderLine(challenge.line, guess, scores)
    guessesEl.innerHTML = linehtml + guessesEl.innerHTML
    var win = true;
    for (var score of scores) {
        if (Object.keys(score.yellows).length || Object.keys(score.greys).length) {
            win = false;
        }
    }
    if (win) {
        entryEl.innerHTML = linehtml
        winGame(challenge)
    }
})

function winGame(challenge) {
    winEl.style = 'display: block;'
    document.getElementById('btns').style = 'display: none;'
    document.getElementById('meter').innerText = challenge.meter
    document.getElementById('ctx').innerHTML = challenge.ctx.replaceAll(/^(.*)/gm, '  $1') + `\n\t<span class="byline">&mdash;<a href="${challenge.link}">${challenge.title}</a>, ${challenge.collection}, ${challenge.author}</span>`
    var date = new Date().toISOString().slice(0, 10)
    var firstguess = Object.values(guesses[0]).join(' ')
    document.getElementById('share').value = `I solved the ${date} Prosodyle at cyfraeviolae.org/prosodyle. My first guess was: "${firstguess}".`
}

document.addEventListener('keydown', function(e) {
    // if (!Array.from(e.target.classList).includes('entrybox')) {
    //     return;
    // }
    // if (e.ctrlKey || e.altKey || (e.key.length != 1 && e.key != 'Backspace')) {
    //     return;
    // }
    if (e.ctrlKey || e.altKey || (!"ABCDEFGHIJKLMNOPQRSTUVWXYZ".includes(e.key.toUpperCase()) && e.key != 'Backspace' && e.key != 'Enter')) {
        return;
    }
    if (e.target.id == 'share') {
        return;
    }
    e.preventDefault();

    if (e.key == 'Enter') {
        document.getElementById('check').click()
        return;
    }
    var el = document.querySelector(`[data-offset="${focused}"]`);
    var offset = parseInt(el.getAttribute('data-offset'))
    var nextel;
    if (e.key == 'Backspace') {
        el.innerText = '';
        nextel = document.querySelector(`[data-offset="${offset-1}"]`);
    } else {
        el.innerText = e.key.toUpperCase();
        nextel = document.querySelector(`[data-offset="${offset+1}"]`);
    }
    if (nextel) {
        focus(nextel);
        unfocus(el);
    }
})

document.addEventListener('mousedown', function(e) {
    if (Array.from(e.target.classList).includes('entrybox')) {
        e.preventDefault();
        unfocus(document.querySelector(`[data-offset="${focused}"]`));
        focus(e.target);
    }
})

function getDailyChallenge() {
    // https://stackoverflow.com/a/8619946
    var now = new Date();
    var start = new Date(now.getFullYear(), 0, 0);
    var diff = now - start;
    var oneDay = 1000 * 60 * 60 * 24;
    var day = Math.floor(diff / oneDay);
    // end snippet
    return challenges[day-57]
}

document.getElementById('copy').addEventListener('click', function(e) {
    e.preventDefault();
    document.getElementById('share').select()
    document.execCommand('copy');
})

function focus(el) {
    focused = parseInt(el.getAttribute('data-offset'))
    el.classList.add('focus')
    document.getElementById('kb').focus()
}

function unfocus(el) {
    el.classList.remove('focus')
}


var guesses = []
var challenge = getDailyChallenge()
entryEl.innerHTML = renderLine(challenge.line)
focus(document.querySelector(`[data-offset="0"]`));