-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
681 lines (586 loc) · 24.4 KB
/
script.js
File metadata and controls
681 lines (586 loc) · 24.4 KB
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
/* =============================================
KEYWAVE — Piano Engine + Learn Mode
Web Audio API — No external files needed
============================================= */
// ══ AUDIO CONTEXT ══════════════════════════════
const AudioContext = window.AudioContext || window.webkitAudioContext;
let audioCtx = null;
function getCtx() {
if (!audioCtx) audioCtx = new AudioContext();
if (audioCtx.state === 'suspended') audioCtx.resume();
return audioCtx;
}
// ══ STATE ══════════════════════════════════════
let octave = 4;
let volume = 0.8;
let waveform = 'sine';
let sustain = 1.0;
const activeOscillators = {};
// ══ NOTE DATA ══════════════════════════════════
const WHITE_NOTES = ['C','D','E','F','G','A','B'];
const BLACK_NOTES = ['C#','D#',null,'F#','G#','A#',null];
const NOTE_SEMITONES = { C:0,'C#':1,D:2,'D#':3,E:4,F:5,'F#':6,G:7,'G#':8,A:9,'A#':10,B:11 };
const KEY_BINDINGS_WHITE = ['a','s','d','f','g','h','j','k','l',';',"'",'\\',']','['];
const KEY_BINDINGS_BLACK = ['w','e',null,'t','y','u',null,'o','p',null,null,null,null,null];
// Finger hints for white keys (left hand C D E F G A B)
const FINGER_HINTS_WHITE = ['Thumb','Index','Middle','Ring','Pinky','Index','Middle','Thumb','Index','Middle','Ring','Pinky','Index','Middle'];
function noteFreq(note, oct) {
const midi = (oct + 1) * 12 + NOTE_SEMITONES[note];
return 440 * Math.pow(2, (midi - 69) / 12);
}
// ══ PLAY / STOP ════════════════════════════════
function playNote(noteId, freq, vol) {
if (activeOscillators[noteId]) return;
const ctx = getCtx();
const gain = ctx.createGain();
gain.gain.setValueAtTime(0, ctx.currentTime);
gain.gain.linearRampToValueAtTime(vol ?? volume, ctx.currentTime + 0.01);
gain.gain.linearRampToValueAtTime((vol ?? volume) * 0.75, ctx.currentTime + 0.08);
const osc = ctx.createOscillator();
osc.type = waveform;
osc.frequency.setValueAtTime(freq, ctx.currentTime);
const osc2 = ctx.createOscillator();
osc2.type = waveform;
osc2.frequency.setValueAtTime(freq * 1.003, ctx.currentTime);
const gain2 = ctx.createGain();
gain2.gain.value = 0.3;
osc.connect(gain);
osc2.connect(gain2);
gain.connect(ctx.destination);
gain2.connect(ctx.destination);
osc.start(); osc2.start();
activeOscillators[noteId] = { osc, osc2, gain, ctx };
}
function stopNote(noteId) {
const n = activeOscillators[noteId];
if (!n) return;
const now = n.ctx.currentTime;
n.gain.gain.cancelScheduledValues(now);
n.gain.gain.setValueAtTime(n.gain.gain.value, now);
n.gain.gain.linearRampToValueAtTime(0, now + sustain * 0.4);
n.osc.stop(now + sustain * 0.4 + 0.05);
n.osc2.stop(now + sustain * 0.4 + 0.05);
delete activeOscillators[noteId];
}
// Play a note for a short burst (for quiz / auto-play)
function playSingleNote(noteId, duration = 0.7) {
const data = keysMap[noteId];
if (!data) return;
const freq = noteFreq(data.note, data.oct);
playNote(noteId, freq);
setTimeout(() => stopNote(noteId), duration * 1000);
}
// ══ BUILD PIANO ════════════════════════════════
const piano = document.getElementById('piano');
const legendWhite = document.getElementById('legend-white');
const legendBlack = document.getElementById('legend-black');
const keysMap = {}; // noteId -> { el, note, oct, kbdKey, fingerHint, whiteIndex }
const kbdMap = {}; // keyboard key -> noteId
function buildPiano() {
piano.innerHTML = '';
legendWhite.innerHTML = '';
legendBlack.innerHTML = '';
Object.keys(keysMap).forEach(k => delete keysMap[k]);
Object.keys(kbdMap).forEach(k => delete kbdMap[k]);
const WHITE_W = 55; // key width + gap
for (let o = 0; o < 2; o++) {
const oct = octave + o;
WHITE_NOTES.forEach((note, i) => {
const noteId = `${note}${oct}`;
const wIdx = o * 7 + i;
const kbdKey = KEY_BINDINGS_WHITE[wIdx];
const finger = FINGER_HINTS_WHITE[wIdx] ?? '—';
const el = document.createElement('div');
el.classList.add('key');
el.dataset.noteId = noteId;
const labelEl = document.createElement('span');
labelEl.classList.add('label');
labelEl.textContent = note + oct;
const kbdEl = document.createElement('span');
kbdEl.classList.add('kbd');
kbdEl.textContent = kbdKey ? kbdKey.toUpperCase() : '';
el.appendChild(labelEl);
el.appendChild(kbdEl);
piano.appendChild(el);
keysMap[noteId] = { el, note, oct, kbdKey, finger };
if (kbdKey) kbdMap[kbdKey] = noteId;
addKeyListeners(el, noteId);
if (kbdKey) {
const chip = document.createElement('div');
chip.classList.add('legend-chip');
chip.textContent = kbdKey.toUpperCase();
legendWhite.appendChild(chip);
}
});
// Black keys
const baseOffset = o * 7 * WHITE_W;
WHITE_NOTES.forEach((_, i) => {
const blackNote = BLACK_NOTES[i];
if (!blackNote) return;
const noteId = `${blackNote}${oct}`;
const bIdx = o * 7 + i;
const kbdKey = KEY_BINDINGS_BLACK[bIdx];
const el = document.createElement('div');
el.classList.add('key','black');
el.dataset.noteId = noteId;
const leftPos = baseOffset + i * WHITE_W + (WHITE_W - 17);
el.style.left = leftPos + 'px';
const labelEl = document.createElement('span');
labelEl.classList.add('label');
labelEl.textContent = blackNote;
const kbdEl = document.createElement('span');
kbdEl.classList.add('kbd');
kbdEl.textContent = kbdKey ? kbdKey.toUpperCase() : '';
el.appendChild(labelEl);
el.appendChild(kbdEl);
piano.appendChild(el);
keysMap[noteId] = { el, note: blackNote, oct, kbdKey, finger: 'Index' };
if (kbdKey) kbdMap[kbdKey] = noteId;
addKeyListeners(el, noteId);
if (kbdKey) {
const chip = document.createElement('div');
chip.classList.add('legend-chip');
chip.textContent = kbdKey.toUpperCase();
legendBlack.appendChild(chip);
}
});
}
}
function addKeyListeners(el, noteId) {
el.addEventListener('mousedown', (e) => { e.preventDefault(); triggerNote(noteId, true); });
el.addEventListener('mouseup', () => triggerNote(noteId, false));
el.addEventListener('mouseleave', () => triggerNote(noteId, false));
el.addEventListener('touchstart', (e) => { e.preventDefault(); triggerNote(noteId, true); }, { passive:false });
el.addEventListener('touchend', (e) => { e.preventDefault(); triggerNote(noteId, false); });
}
// ══ TRIGGER ════════════════════════════════════
const noteDisplay = document.getElementById('note-display');
let noteDisplayTimer = null;
function triggerNote(noteId, on) {
const data = keysMap[noteId];
if (!data) return;
if (on) {
const freq = noteFreq(data.note, data.oct);
playNote(noteId, freq);
data.el.classList.add('active');
showNoteFlash(noteId);
document.getElementById('octave-display').textContent = `OCT ${data.oct}`;
// Free learn mode update
if (learnMode === 'free') updateFreeLearnUI(data, freq);
// Quiz mode — check answer
if (learnMode === 'quiz' && quizActive) handleQuizAnswer(noteId);
// Song mode — check note
if (learnMode === 'song' && songActive && !songAuto) checkSongNote(noteId);
} else {
stopNote(noteId);
data.el.classList.remove('active');
}
}
function showNoteFlash(noteId) {
const data = keysMap[noteId];
if (!data) return;
noteDisplay.textContent = noteId;
noteDisplay.classList.remove('show');
void noteDisplay.offsetWidth;
noteDisplay.classList.add('show');
clearTimeout(noteDisplayTimer);
noteDisplayTimer = setTimeout(() => noteDisplay.classList.remove('show'), 600);
}
// ══ KEYBOARD ═══════════════════════════════════
const pressedKeys = new Set();
document.addEventListener('keydown', (e) => {
if (e.repeat || e.target.tagName === 'SELECT') return;
const key = e.key.toLowerCase();
const noteId = kbdMap[key];
if (noteId && !pressedKeys.has(key)) {
pressedKeys.add(key);
triggerNote(noteId, true);
}
});
document.addEventListener('keyup', (e) => {
const key = e.key.toLowerCase();
const noteId = kbdMap[key];
if (noteId) { pressedKeys.delete(key); triggerNote(noteId, false); }
});
// ══ PIANO CONTROLS ═════════════════════════════
document.getElementById('oct-down').addEventListener('click', () => {
if (octave > 1) { octave--; rebuildPiano(); }
});
document.getElementById('oct-up').addEventListener('click', () => {
if (octave < 6) { octave++; rebuildPiano(); }
});
function rebuildPiano() {
Object.keys(activeOscillators).forEach(id => stopNote(id));
pressedKeys.clear();
document.getElementById('oct-val').textContent = octave;
document.getElementById('octave-display').textContent = `OCT ${octave}`;
buildPiano();
if (songActive) stopSong();
}
document.getElementById('volume').addEventListener('input', (e) => {
volume = e.target.value / 100;
document.getElementById('vol-val').textContent = e.target.value;
});
document.getElementById('sustain').addEventListener('input', (e) => {
sustain = parseFloat(e.target.value);
});
document.querySelectorAll('.wave-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.wave-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
waveform = btn.dataset.wave;
});
});
// ══ LEARN MODE TOGGLE ══════════════════════════
let learnPanelOpen = false;
let learnMode = 'song'; // 'song' | 'free' | 'quiz'
const learnToggleBtn = document.getElementById('learn-toggle');
const learnPanel = document.getElementById('learn-panel');
const modeIndicator = document.getElementById('mode-indicator');
learnToggleBtn.addEventListener('click', () => {
learnPanelOpen = !learnPanelOpen;
learnPanel.classList.toggle('hidden', !learnPanelOpen);
learnToggleBtn.classList.toggle('active', learnPanelOpen);
modeIndicator.textContent = learnPanelOpen ? '🎓 LEARN MODE' : '🎹 PLAY MODE';
if (!learnPanelOpen) {
learnMode = 'song';
stopSong();
stopQuiz();
clearAllHighlights();
}
});
// ── Tab switching ──
document.querySelectorAll('.learn-tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.learn-tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
learnMode = tab.dataset.mode;
document.querySelectorAll('.learn-section').forEach(s => s.classList.add('hidden'));
document.getElementById(`section-${learnMode}`).classList.remove('hidden');
stopSong();
stopQuiz();
clearAllHighlights();
});
});
function clearAllHighlights() {
Object.values(keysMap).forEach(({ el }) => {
el.classList.remove('learn-highlight','quiz-correct','quiz-wrong');
});
}
// ══════════════════════════════════════════════
// 🎵 SONG MODE
// ══════════════════════════════════════════════
// Songs: array of { note, oct } objects (null = rest)
const SONGS = {
twinkle: {
name: 'Twinkle Twinkle',
notes: [
{n:'C',o:4},{n:'C',o:4},{n:'G',o:4},{n:'G',o:4},{n:'A',o:4},{n:'A',o:4},{n:'G',o:4},null,
{n:'F',o:4},{n:'F',o:4},{n:'E',o:4},{n:'E',o:4},{n:'D',o:4},{n:'D',o:4},{n:'C',o:4},null,
{n:'G',o:4},{n:'G',o:4},{n:'F',o:4},{n:'F',o:4},{n:'E',o:4},{n:'E',o:4},{n:'D',o:4},null,
{n:'G',o:4},{n:'G',o:4},{n:'F',o:4},{n:'F',o:4},{n:'E',o:4},{n:'E',o:4},{n:'D',o:4},null,
{n:'C',o:4},{n:'C',o:4},{n:'G',o:4},{n:'G',o:4},{n:'A',o:4},{n:'A',o:4},{n:'G',o:4},null,
{n:'F',o:4},{n:'F',o:4},{n:'E',o:4},{n:'E',o:4},{n:'D',o:4},{n:'D',o:4},{n:'C',o:4}
]
},
happy: {
name: 'Happy Birthday',
notes: [
{n:'C',o:4},{n:'C',o:4},{n:'D',o:4},{n:'C',o:4},{n:'F',o:4},{n:'E',o:4},null,
{n:'C',o:4},{n:'C',o:4},{n:'D',o:4},{n:'C',o:4},{n:'G',o:4},{n:'F',o:4},null,
{n:'C',o:4},{n:'C',o:4},{n:'C',o:5},{n:'A',o:4},{n:'F',o:4},{n:'E',o:4},{n:'D',o:4},null,
{n:'A#',o:4},{n:'A#',o:4},{n:'A',o:4},{n:'F',o:4},{n:'G',o:4},{n:'F',o:4}
]
},
ode: {
name: 'Ode To Joy',
notes: [
{n:'E',o:4},{n:'E',o:4},{n:'F',o:4},{n:'G',o:4},{n:'G',o:4},{n:'F',o:4},{n:'E',o:4},{n:'D',o:4},
{n:'C',o:4},{n:'C',o:4},{n:'D',o:4},{n:'E',o:4},{n:'E',o:4},{n:'D',o:4},{n:'D',o:4},null,
{n:'E',o:4},{n:'E',o:4},{n:'F',o:4},{n:'G',o:4},{n:'G',o:4},{n:'F',o:4},{n:'E',o:4},{n:'D',o:4},
{n:'C',o:4},{n:'C',o:4},{n:'D',o:4},{n:'E',o:4},{n:'D',o:4},{n:'C',o:4},{n:'C',o:4}
]
},
mary: {
name: 'Mary Had A Little Lamb',
notes: [
{n:'E',o:4},{n:'D',o:4},{n:'C',o:4},{n:'D',o:4},{n:'E',o:4},{n:'E',o:4},{n:'E',o:4},null,
{n:'D',o:4},{n:'D',o:4},{n:'D',o:4},null,{n:'E',o:4},{n:'G',o:4},{n:'G',o:4},null,
{n:'E',o:4},{n:'D',o:4},{n:'C',o:4},{n:'D',o:4},{n:'E',o:4},{n:'E',o:4},{n:'E',o:4},{n:'E',o:4},
{n:'D',o:4},{n:'D',o:4},{n:'E',o:4},{n:'D',o:4},{n:'C',o:4}
]
},
jingle: {
name: 'Jingle Bells',
notes: [
{n:'E',o:4},{n:'E',o:4},{n:'E',o:4},null,
{n:'E',o:4},{n:'E',o:4},{n:'E',o:4},null,
{n:'E',o:4},{n:'G',o:4},{n:'C',o:4},{n:'D',o:4},{n:'E',o:4},null,
{n:'F',o:4},{n:'F',o:4},{n:'F',o:4},{n:'F',o:4},
{n:'F',o:4},{n:'E',o:4},{n:'E',o:4},{n:'E',o:4},
{n:'E',o:4},{n:'D',o:4},{n:'D',o:4},{n:'E',o:4},{n:'D',o:4},{n:'G',o:4}
]
}
};
let songActive = false;
let songAuto = false;
let currentSongNotes = [];
let songStep = 0;
let autoTimer = null;
let currentHighlightId = null;
document.getElementById('song-start').addEventListener('click', startSong);
document.getElementById('song-stop').addEventListener('click', stopSong);
document.getElementById('song-auto').addEventListener('click', () => {
songAuto = true;
startSong();
runAutoPlay();
});
function startSong() {
stopSong();
const songKey = document.getElementById('song-select').value;
const song = SONGS[songKey];
currentSongNotes = song.notes;
songStep = 0;
songActive = true;
buildNoteQueue();
updateSongUI();
highlightCurrentNote();
}
function stopSong() {
songActive = false;
songAuto = false;
clearTimeout(autoTimer);
clearAllHighlights();
currentHighlightId = null;
document.getElementById('hint-note').textContent = '—';
document.getElementById('hint-key').textContent = '—';
document.getElementById('hint-finger').textContent = '—';
document.getElementById('progress-fill').style.width = '0%';
document.getElementById('song-step').textContent = 'Step 0';
document.getElementById('note-queue').innerHTML = '';
}
function buildNoteQueue() {
const queue = document.getElementById('note-queue');
queue.innerHTML = '';
currentSongNotes.forEach((note, i) => {
const chip = document.createElement('div');
chip.classList.add('nq-chip');
chip.id = `nq-${i}`;
if (note) {
chip.innerHTML = `<span class="nq-note">${note.n}${note.o}</span><span class="nq-key">${getNoteKbdKey(note.n, note.o)}</span>`;
} else {
chip.innerHTML = `<span class="nq-note" style="opacity:0.4">—</span><span class="nq-key">rest</span>`;
}
queue.appendChild(chip);
});
}
function getNoteKbdKey(note, oct) {
const noteId = `${note}${oct}`;
return keysMap[noteId]?.kbdKey?.toUpperCase() ?? '?';
}
function updateSongUI() {
const total = currentSongNotes.filter(n => n !== null).length;
const done = currentSongNotes.slice(0, songStep).filter(n => n !== null).length;
document.getElementById('song-step').textContent = `Step ${done}`;
document.getElementById('song-total').textContent = `/ ${total}`;
document.getElementById('progress-fill').style.width = `${total ? (done / total) * 100 : 0}%`;
// Update chips
currentSongNotes.forEach((_, i) => {
const chip = document.getElementById(`nq-${i}`);
if (!chip) return;
chip.classList.remove('current','done','upcoming');
if (i < songStep) chip.classList.add('done');
else if (i === songStep) chip.classList.add('current');
else chip.classList.add('upcoming');
});
// Scroll queue to current
const currentChip = document.getElementById(`nq-${songStep}`);
if (currentChip) currentChip.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' });
}
function highlightCurrentNote() {
clearAllHighlights();
if (!songActive || songStep >= currentSongNotes.length) return;
// Skip rests
while (songStep < currentSongNotes.length && currentSongNotes[songStep] === null) {
songStep++;
}
if (songStep >= currentSongNotes.length) {
completeSong(); return;
}
const n = currentSongNotes[songStep];
const noteId = `${n.n}${n.o}`;
currentHighlightId = noteId;
const data = keysMap[noteId];
if (data) {
data.el.classList.add('learn-highlight');
document.getElementById('hint-note').textContent = noteId;
document.getElementById('hint-key').textContent = data.kbdKey?.toUpperCase() ?? '?';
document.getElementById('hint-finger').textContent = data.finger ?? '—';
}
updateSongUI();
}
function checkSongNote(pressedId) {
if (!songActive || pressedId !== currentHighlightId) return;
clearAllHighlights();
songStep++;
setTimeout(() => {
if (songStep < currentSongNotes.length) highlightCurrentNote();
else completeSong();
}, 150);
}
function completeSong() {
songActive = false;
clearAllHighlights();
document.getElementById('hint-note').textContent = '🎉';
document.getElementById('hint-key').textContent = 'DONE!';
document.getElementById('hint-finger').textContent = 'Great job!';
document.getElementById('progress-fill').style.width = '100%';
// Flash all keys
Object.values(keysMap).forEach(({ el }) => {
el.classList.add('quiz-correct');
setTimeout(() => el.classList.remove('quiz-correct'), 800);
});
}
// Auto-play mode
function runAutoPlay() {
if (!songActive || !songAuto) return;
if (songStep >= currentSongNotes.length) { completeSong(); return; }
const n = currentSongNotes[songStep];
if (n) {
const noteId = `${n.n}${n.o}`;
highlightCurrentNote();
playSingleNote(noteId, 0.4);
const data = keysMap[noteId];
if (data) {
data.el.classList.add('active');
setTimeout(() => data.el.classList.remove('active'), 350);
}
songStep++;
updateSongUI();
autoTimer = setTimeout(runAutoPlay, 500);
} else {
// rest
songStep++;
autoTimer = setTimeout(runAutoPlay, 250);
}
}
// ══════════════════════════════════════════════
// 📖 FREE LEARN MODE
// ══════════════════════════════════════════════
function updateFreeLearnUI(data, freq) {
document.getElementById('free-note').textContent = `${data.note}${data.oct}`;
document.getElementById('free-kbdkey').textContent = data.kbdKey?.toUpperCase() ?? '—';
document.getElementById('free-finger').textContent = data.finger ?? '—';
document.getElementById('free-freq').textContent = `${freq.toFixed(1)} Hz`;
}
// ══════════════════════════════════════════════
// ❓ QUIZ MODE
// ══════════════════════════════════════════════
let quizActive = false;
let quizAnswer = null; // expected noteId
let quizScore = 0;
let quizStreak = 0;
let quizBest = 0;
let quizRound = 0;
let quizAnswered = false;
let difficulty = 'easy';
// Difficulty pools
const DIFF_POOLS = {
easy: ['C4','D4','E4','F4','G4','A4','B4'],
medium: ['C4','D4','E4','F4','G4','A4','B4','C5','D5','E5','F5','G5'],
hard: ['C4','C#4','D4','D#4','E4','F4','F#4','G4','G#4','A4','A#4','B4','C5','C#5','D5']
};
document.querySelectorAll('.diff-btn').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.diff-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
difficulty = btn.dataset.diff;
});
});
document.getElementById('quiz-start').addEventListener('click', startQuiz);
document.getElementById('quiz-replay').addEventListener('click', () => {
if (quizAnswer) playSingleNote(quizAnswer, 0.7);
});
function startQuiz() {
quizActive = true;
quizScore = 0;
quizStreak = 0;
quizRound = 0;
updateQuizScores();
nextQuizQuestion();
document.getElementById('quiz-start').textContent = '↺ RESTART';
document.getElementById('quiz-replay').disabled = false;
}
function stopQuiz() {
quizActive = false;
quizAnswer = null;
quizAnswered = false;
document.getElementById('quiz-prompt').textContent = 'Press START to begin!';
document.getElementById('quiz-sub').textContent = 'Listen to the note and press the matching key on the piano below';
document.getElementById('quiz-feedback').textContent = '';
document.getElementById('quiz-feedback').className = 'quiz-feedback';
document.getElementById('quiz-replay').disabled = true;
document.getElementById('quiz-start').textContent = '▶ START QUIZ';
}
function nextQuizQuestion() {
if (!quizActive) return;
quizAnswered = false;
clearAllHighlights();
const pool = DIFF_POOLS[difficulty];
// Filter to only notes that exist on current piano
const available = pool.filter(nid => keysMap[nid]);
if (!available.length) {
document.getElementById('quiz-prompt').textContent = 'Change octave — no matching keys!';
return;
}
quizAnswer = available[Math.floor(Math.random() * available.length)];
quizRound++;
updateQuizScores();
document.getElementById('quiz-prompt').textContent = '🎵 WHAT NOTE IS THIS?';
document.getElementById('quiz-sub').textContent = 'Listen carefully and press the matching key';
document.getElementById('quiz-feedback').textContent = '';
document.getElementById('quiz-feedback').className = 'quiz-feedback';
// Play the note
setTimeout(() => playSingleNote(quizAnswer, 0.8), 300);
}
function handleQuizAnswer(pressedId) {
if (quizAnswered) return;
quizAnswered = true;
const fb = document.getElementById('quiz-feedback');
const pressedEl = keysMap[pressedId]?.el;
const answerEl = keysMap[quizAnswer]?.el;
if (pressedId === quizAnswer) {
// Correct!
quizScore++;
quizStreak++;
if (quizStreak > quizBest) quizBest = quizStreak;
fb.textContent = `✅ CORRECT! +1`;
fb.className = 'quiz-feedback correct';
if (pressedEl) { pressedEl.classList.add('quiz-correct'); setTimeout(() => pressedEl.classList.remove('quiz-correct'), 700); }
setTimeout(() => nextQuizQuestion(), 1100);
} else {
// Wrong
quizStreak = 0;
fb.textContent = `❌ WRONG — It was ${quizAnswer}`;
fb.className = 'quiz-feedback wrong';
if (pressedEl) { pressedEl.classList.add('quiz-wrong'); setTimeout(() => pressedEl.classList.remove('quiz-wrong'), 700); }
if (answerEl) { answerEl.classList.add('learn-highlight'); setTimeout(() => answerEl.classList.remove('learn-highlight'), 1200); }
// Replay correct note so student learns
setTimeout(() => playSingleNote(quizAnswer, 0.7), 400);
setTimeout(() => nextQuizQuestion(), 1800);
}
updateQuizScores();
}
function updateQuizScores() {
document.getElementById('quiz-score').textContent = quizScore;
document.getElementById('quiz-streak').textContent = quizStreak + (quizStreak >= 3 ? '🔥' : '');
document.getElementById('quiz-best').textContent = quizBest;
document.getElementById('quiz-round').textContent = quizRound || '-';
}
// ══ INIT ═══════════════════════════════════════
document.addEventListener('click', () => getCtx(), { once: true });
document.addEventListener('keydown', () => getCtx(), { once: true });
buildPiano();
document.getElementById('oct-val').textContent = octave;
document.getElementById('octave-display').textContent = `OCT ${octave}`;
console.log('%cKEYWAVE 🎓 Learn Mode loaded!', 'color:#00e5ff;font-size:14px;font-family:monospace;');