word/memory: celebration animation on completion
[sheet.git] / word / memory.js
1 class WordMemory {
2         turn(click) {
3                 let target = click.currentTarget;
4                 if (!target.classList.contains('turn')) {
5                         // show an open card
6                         this.turned.push(target);
7                         put(target, '.turn');
8                 }
9                 else if (this.turned.length < 2) {
10                         return; // keep open
11                 }
12
13                 if (this.turned.length <= 1) {
14                         return; // first choice
15                 }
16
17                 // compare two cards
18                 let match = this.pairs[this.turned[0].id] == this.turned[1].id
19                         || this.pairs[this.turned[1].id] == this.turned[0].id;
20                 if (!match && !this.turned[0].classList.contains('bad')) {
21                         put(this.turned[0], '.bad'); // indicate failure on first card
22                         return;
23                 }
24
25                 if (match) {
26                         // lock both as correct
27                         this.turned.forEach(card => put(card, '.good![onclick]'));
28                         this.turned = [];
29                         if (Array.from(this.form.children).every(card => card.classList.contains('good'))) {
30                                 put(this.form, '.good');
31                         }
32                         return;
33                 }
34
35                 // fold back earlier cards
36                 this.turned.splice(0, 2)
37                 .forEach(card => put(card, '!.turn!.bad'));
38         }
39
40         constructor() {
41                 this.dataurl = '/data/wordpairs.json';
42                 fetch(this.dataurl).then(res => res.json()).then(pairs => {
43                         this.turned = [];
44                         this.pairs = pairs;
45                         this.form = document.getElementById('quiz');
46                         this.cards = Object.entries(pairs).flat()
47                                 .map(e => e.toString())
48                                 .sort(() => {return .5 - Math.random()}) // shuffle
49                         this.cards.forEach(word => {
50                                 put(this.form,
51                                         'figure>img[src=$]<', `/data/word/en/${word}.jpg`,
52                                         {onclick: e => this.turn(e), id: word}
53                                 );
54                         });
55                 });
56         }
57 };
58
59 new WordMemory();