« get me outta code hell

main.js - guess-the-character - Unnamed repository; edit this file 'description' to name the repository.
summary refs log tree commit diff
path: root/main.js
blob: dc5d39854fbacf2bb6154dc58742a837e715ac14 (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
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
/**
 *
 * IDEAS LOL
 *
 * - make the game, dummy
 *
 * - hide the image, or the name -- i.e. force the user to guess based on one
 *   or the other, not both
 *
 * - pick __ HARD __ selections of choices, not just totally random ones
 *
 */

// initializy stuff --------------------------------------------------------ooo

'use strict';

// sorry this is cursed
const { gameData } = window;

document.body.classList.add('js-enabled');

// resource loading --------------------------------------------------------o.o

const resources = {
    imageMap: new Map(),
    soundMap: new Map()
};

let loadTotal = 0;
let loadSoFar = 0;

function loadResources() {
    // 2 assets for each character: image, sound.
    loadTotal = gameData.characters.length * 2;

    return Promise.all([
        loadImages(),
        loadSounds()
    ]);
}

async function loadImages() {
    for (const character of gameData.characters) {
        const image = new Image();
        resources.imageMap.set(character, image);

        const path = `faces/${getCharacterPath(character)}.png`;
        image.src = path;

        await new Promise((resolve, reject) => {
            image.addEventListener('load', () => resolve());

            image.addEventListener('error', () => {
                reject(new Error('Failed to load image from path ' + path));
            });
        });

        loadSoFar++;
        updateLoadProgress();
    }
}

async function loadSounds() {
    for (const character of gameData.characters) {
        const audio = new Audio();
        resources.soundMap.set(character, audio);

        const path = `sounds/${getCharacterPath(character)}.wav`;
        audio.src = path;

        await new Promise((resolve, reject) => {
            audio.addEventListener('canplaythrough', () => resolve());

            audio.addEventListener('error', () => {
                reject(new Error('Failed to load audio from path ' + path));
            });
        });

        loadSoFar++;
        updateLoadProgress();
    }
}

function updateLoadProgress() {
    const el = document.getElementById('load-progress');
    if (loadSoFar < loadTotal) {
        el.innerHTML = Math.floor(loadSoFar / loadTotal * 100);
    } else {
        el.parentElement.innerHTML = 'Loaded!';
    }
}

function getCharacterPath(character) {
    let path = '';
    if (character.games.length >= 2) {
        path += 'common/';
    } else if (character.games.length === 1) {
        path += character.games[0] + '/';
    } else {
        // uhhhh what
        throw new error(character.name + " isn't actually part of any games??");
    }
    path += character.file;
    return path;
}

// talky talky -------------------------------------------------------------oWo

function wrapMessage(msg, length = 23) {
    // so h*ck, apparently word wrapping is Not Automatic in undertale
    // best we just specify word-wraps in the unmodified message text.
    // keeping this function around just in case though.
    const words = msg.split(' ');
    const lines = [[]];
    let col = 0;
    for (let i = 0; i < words.length; i++) {
        const word = words[i];
        col += word.length + 1;
        if (col > length) {
            lines.push([word]);
            col = 0;
        } else {
            lines[lines.length - 1].push(word);
        }
    }
    return lines.map(l => l.join(' ')).join('\n');
}

const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 256;
analyser.connect(audioCtx.destination);

async function doSpeech(character, msg) {
    const audio = resources.soundMap.get(character);
    if (!audio) {
        return;
    }

    for (let i = 0; i < msg.length; i++) {
        const char = msg[i];
        // Yeah all these timings are wrong but they're decent estimations.
        if (char === ',' || char === '.') {
            await delay(300);
            while (msg[i + 1] === ',') i++; // Deal with ellipsis
        } else if (char === '\n') {
            await delay(80);
        } else if (char === ' ') {
            await delay(30);
        } else {
            const a = audio.cloneNode();
            a.volume = character.volume || 0.5;

            const source = audioCtx.createMediaElementSource(a);
            source.connect(analyser);

            a.play();
            await delay(character.speed || 50);
        }
    }
}

const canvas = document.getElementById('canvas');
const streamData = new Uint8Array(128);

function sampleAudioStream() {
    analyser.getByteFrequencyData(streamData);

    const rect = document.body.getBoundingClientRect();
    canvas.width = rect.width;
    canvas.height = rect.height;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    let lastTop = null;
    for (let i = 0; i < 60; i++) { // i < N is arbitrary, this value seems pretty good for most voices
        const w = canvas.width / 60;
        const x = w * i;
        const h = (0.9 * canvas.height / 255) * streamData[i];
        ctx.fillStyle = 'white';

        const top = h / 2;
        if (lastTop) ctx.fillRect(x, canvas.height / 2 + top, 1, lastTop - top);
        ctx.fillRect(x, canvas.height / 2 + top, w, 2);
        if (lastTop) ctx.fillRect(x, canvas.height / 2 - top, 1, top - lastTop);
        ctx.fillRect(x, canvas.height / 2 - top, w, 2);
        lastTop = top;
    }

    requestAnimationFrame(sampleAudioStream);
}

requestAnimationFrame(sampleAudioStream);

// display choices ---------------------------------------------------------www

function displayChoices(characters, confirmCharacterCb) {
    return new Promise(async resolve => {
        const container = document.getElementById('choice-container');
        while (container.firstChild) {
            container.removeChild(container.firstChild);
        }
        container.classList.remove('hide');

        let selected = false;
        for (const character of characters) {
            const el = document.createElement('a');
            el.href = '#';
            el.classList.add('character-choice');
            el.appendChild(resources.imageMap.get(character));
            const span = document.createElement('span');
            span.appendChild(document.createTextNode(character.name));
            el.appendChild(span);
            container.appendChild(el);

            el.addEventListener('click', () => {
                if (!selected) {
                    selected = true;
                    resolve(character);
                }
            });
        }

        container.children[0].focus();
        for (const el of container.children) {
            el.classList.add('visible');
            await delay(800 / container.children.length);
        }
    });
}

// utilitylol --------------------------------------------------------------uwu

function characterWithName(name) {
    return gameData.characters.find(chr => chr.name === name);
}

function pickRandom(array) {
    return array[Math.floor(Math.random() * array.length)];
}

function spliceRandom(array) {
    const val = pickRandom(array);
    array.splice(array.indexOf(val), 1);
    return val;
}

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function waitForEvent(el, eventName) {
    return new Promise(resolve => {
        el.addEventListener(eventName, function cb(evt) {
            el.removeEventListener(eventName, cb);
            resolve(evt);
        }); // if only {once: true} were "more supported"
        //     as   if   that' s   something  I  care  about  in this game
    });
}

// scorekeeper -------------------------------------------------------------***

function setupScorekeeper(numCharacters) {
    const container = document.getElementById('scorekeeper');
    for (let i = 0; i < numCharacters; i++) {
        const el = document.createElement('div')
        el.classList.add('marker');
        el.classList.add('unset');
        container.appendChild(el);
    }
}

function markScorekeeper(cls, character) {
    const el = scorekeeper.querySelector('.unset');
    el.classList.remove('unset');
    el.classList.add(cls);
    el.appendChild(resources.imageMap.get(character).cloneNode());
    el.title = character.name
}

// uh start it now ---------------------------------------------------------aA!

async function mainLol() {
    const testChar = 'Noellef';

    await loadResources();

    document.body.classList.add('resources-loaded');

    document.body.addEventListener('keydown', evt => {
        const choiceContainer = document.getElementById('choice-container');
        if (!choiceContainer.classList.contains('hide')) {
            if (/^[0-9]$/.test(evt.key)) {
                const el = choiceContainer.children[evt.key - 1];
                if (document.activeElement === el) {
                    el.click();
                } else if (el) {
                    el.focus();
                }
            } else if (event.key === 'ArrowRight') {
                const el = document.activeElement;
                if (el.parentElement === choiceContainer && el.nextSibling) {
                    el.nextSibling.focus();
                }
            } else if (event.key === 'ArrowLeft') {
                const el = document.activeElement;
                if (el.parentElement === choiceContainer && el.previousSibling) {
                    el.previousSibling.focus();
                }
            }
        }

        if (event.which === 90) { // Z
            if (document.activeElement.click) {
                document.activeElement.click();
            }
        }
    });

    const gameEl = document.getElementById('game');

    const playLink = document.getElementById('play-link');
    playLink.focus();
    await waitForEvent(playLink, 'click');

    document.body.classList.add('game');

    const deckGames = ['deltarune'];
    const hardMode = false;

    const characterDeck = gameData.characters.filter(chr => chr.games.some(g => deckGames.includes(g)));

    setupScorekeeper(characterDeck.length);

    while (characterDeck.length) {
        gameEl.classList.remove('correct');
        gameEl.classList.remove('incorrect');

        const correctCharacter = characterWithName(testChar) || spliceRandom(characterDeck);

        const numChoices = 6;
        const potentialOptions = characterDeck.slice().filter(chr => chr !== correctCharacter);
        const correctIndex = Math.min(Math.floor(Math.random() * numChoices), potentialOptions.length);
        const allCharacters = [];
        for (let i = 0; i < numChoices; i++) {
            if (i === correctIndex) {
                allCharacters.push(correctCharacter);
            } else if (potentialOptions.length) {
                let choice;
                allCharacters.push(spliceRandom(potentialOptions));
            } else {
                break
            }
        }

        let msg;
        if (hardMode) {
            msg = pickRandom(['Oh?', 'Hello!']);
        } else {
            msg = pickRandom(correctCharacter.messages);
        }

        await doSpeech(correctCharacter, msg);
        await delay(500);

        const choice = await displayChoices(allCharacters);

        const container = document.getElementById('choice-container');
        for (let i = 0; i < allCharacters.length; i++) {
            const el = container.children[i];
            if (i === correctIndex) {
                el.classList.add('correct');
            } else {
                el.classList.add('incorrect');
            }
            if (i === allCharacters.indexOf(choice)) {
                el.classList.add('chosen');
            } else {
                el.classList.add('not-chosen');
            }
        }

        if (choice === correctCharacter) {
            markScorekeeper('correct', correctCharacter);
        } else {
            markScorekeeper('incorrect', correctCharacter);
        }

        await delay(200);

        if (choice === correctCharacter) {
            gameEl.classList.add('correct');
        } else {
            gameEl.classList.add('incorrect');
            const el = document.getElementById('correct-character');
            el.innerHTML = '';
            el.appendChild(document.createTextNode(correctCharacter.name));
        }

        document.getElementById('results').classList.remove('hide');

        const nextLink = document.getElementById('next-link');
        nextLink.focus();
        await waitForEvent(nextLink, 'click');

        document.getElementById('choice-container').classList.add('hide');
        document.getElementById('results').classList.add('hide');

        await delay(400);
    }
}

mainLol().catch(error => {
    document.body.classList.add('crashed');
    document.getElementById('crash-trace').appendChild(document.createTextNode(
        error.message + '\n' +
        error.stack
    ));
});