app.js 17 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* app.js — interaction layer: code validation, visual state, sound, dialogs and local persistence. */
  2. const $ = (selector) => document.querySelector(selector);
  3. const stages = [...document.querySelectorAll('.stage')];
  4. let activeCode = localStorage.getItem('zke-code') || '1234';
  5. let entered = [];
  6. let timerId;
  7. let soundEnabled = localStorage.getItem('zke-sound') === 'true';
  8. const quiz = [
  9. ['Что происходит при неверной цифре?', ['Цепь продолжает работу', 'Цепь сбрасывается', 'Дверь открывается'], 1],
  10. ['Какой элемент физически убирает защёлку?', ['Электромагнит', 'Тиристор', 'Клавиша'], 0],
  11. ['Сколько каскадов в этой учебной модели?', ['Два', 'Четыре', 'Десять'], 1]
  12. ];
  13. const secretCode = '1984';
  14. function tone(type = 'click') { if (!soundEnabled || !window.AudioContext) return; const ctx = new AudioContext(); const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.connect(gain); gain.connect(ctx.destination); const now = ctx.currentTime; osc.type = type === 'error' ? 'sawtooth' : 'sine'; osc.frequency.setValueAtTime(type === 'success' ? 780 : type === 'error' ? 140 : 350, now); if (type === 'success') osc.frequency.exponentialRampToValueAtTime(1180, now + .12); gain.gain.setValueAtTime(.06, now); gain.gain.exponentialRampToValueAtTime(.001, now + (type === 'error' ? .3 : .12)); osc.start(now); osc.stop(now + .35); }
  15. function setLog(text) { $('#eventLog').textContent = text; }
  16. function updateScreen() { const symbols = [...entered, ...Array(4 - entered.length).fill('—')]; $('#codeDisplay').textContent = symbols.join(' '); $('#progressNumber').textContent = `${entered.length}/4`; stages.forEach((stage, i) => { stage.classList.toggle('is-active', i < entered.length); stage.classList.remove('is-error'); stage.querySelector('small').textContent = i < entered.length ? 'проводит' : 'ожидание'; }); }
  17. function reset(message = 'Система сброшена. Ожидание нового ввода.') { clearTimeout(timerId); timerId = undefined; entered = []; stages.forEach(s => { s.classList.remove('is-active', 'is-error'); s.querySelector('small').textContent = 'ожидание'; }); $('#relayNode').classList.remove('is-active'); $('#lockStage').classList.remove('is-open'); $('#lockPill').classList.remove('is-open'); $('#lockPill').textContent = 'ЗАКРЫТ'; $('#lamp').className = 'lamp'; $('#powerDot').classList.remove('is-on'); $('#timerReadout').textContent = '—.— c'; $('#logicText').textContent = 'Каждая правильная цифра открывает следующий тиристор. Последовательность задаётся в настройках стенда.'; updateScreen(); setLog(message); }
  18. function openLock() { $('#relayNode').classList.add('is-active'); $('#lockStage').classList.add('is-open'); $('#lockPill').classList.add('is-open'); $('#lockPill').textContent = 'ОТКРЫТ'; $('#lamp').className = 'lamp is-success'; $('#powerDot').classList.add('is-on'); $('#logicText').textContent = 'Все четыре каскада открыты. Реле времени подало импульс на электромагнит.'; setLog('Код подтверждён. Защёлка открыта на 2,4 секунды.'); tone('success'); let left = 2.4; $('#timerReadout').textContent = `${left.toFixed(1)} c`; const ticker = setInterval(() => { left -= .1; $('#timerReadout').textContent = `${Math.max(0,left).toFixed(1)} c`; if (left <= 0) clearInterval(ticker); }, 100); timerId = setTimeout(() => reset('Время реле истекло. Защёлка вернулась в закрытое положение.'), 2400); }
  19. function incorrect() { const fault = Math.min(entered.length, 3); stages[fault]?.classList.add('is-error'); $('#lamp').className = 'lamp is-error'; setLog('Неверная цифра — защитная цепь мгновенно сбросила состояние.'); tone('error'); setTimeout(() => reset(), 700); }
  20. function input(key) { if (timerId) return; if (entered.length >= 4) return; tone(); const possibleSecret = `${entered.join('')}${key}`; if (secretCode.startsWith(possibleSecret)) { entered.push(key); updateScreen(); if (possibleSecret === secretCode) return openArchive(); setLog(`Каскад V${entered.length} открыт. Сигнал передан дальше.`); return; } const expected = activeCode[entered.length]; if (key !== expected) return incorrect(); entered.push(key); updateScreen(); setLog(`Каскад V${entered.length} открыт. Сигнал передан дальше.`); if (entered.length === 4) openLock(); }
  21. function applyCode() { const value = $('#codeInput').value.replace(/\D/g, '').slice(0,4); if (value.length !== 4) { $('#codeHint').textContent = 'Нужны ровно четыре цифры — настройка не сохранена.'; $('#codeHint').style.color = '#ffaaa3'; return; } activeCode = value; localStorage.setItem('zke-code', value); $('#codeInput').value = value; $('#codeHint').textContent = 'Код сохранён локально в этом браузере.'; $('#codeHint').style.color = ''; $('#saveNote').textContent = 'сохранено сейчас'; reset('Настройки применены. Можно проверить новый код.'); }
  22. function renderQuiz(index = 0, score = 0) { const host = $('#quizContent'); if (index === quiz.length) { host.innerHTML = `<h2>Готово</h2><p class="quiz-result">${score} из ${quiz.length} — ${score === quiz.length ? 'идеально!' : 'ещё один заход?'}</p><button class="button button--primary" id="restartQuiz">Пройти ещё раз</button>`; $('#restartQuiz').onclick = () => renderQuiz(); return; } const [question, options, answer] = quiz[index]; host.innerHTML = `<p class="quiz-progress">ВОПРОС ${index + 1} / ${quiz.length}</p><h2>${question}</h2><div class="quiz-options">${options.map((option, i) => `<button data-answer="${i}">${option}</button>`).join('')}</div>`; host.querySelectorAll('button').forEach(button => button.onclick = () => renderQuiz(index + 1, score + (+button.dataset.answer === answer))); }
  23. $('#codeInput').value = activeCode; updateScreen();
  24. $('#keypad').addEventListener('click', e => { const key = e.target.dataset.key; if (key) input(key); });
  25. $('#keypadReset').onclick = () => reset(); $('#resetButton').onclick = () => reset(); $('#backspaceButton').onclick = () => { if (!entered.length || timerId) return; entered.pop(); updateScreen(); setLog('Последний каскад снят вручную.'); };
  26. $('#applyCode').onclick = applyCode; $('#codeInput').addEventListener('keydown', e => { if (e.key === 'Enter') applyCode(); });
  27. document.addEventListener('keydown', e => { if (e.key >= '0' && e.key <= '9' && !document.activeElement.matches('input')) input(e.key); if (e.key === 'Escape') document.querySelectorAll('dialog[open]').forEach(d => d.close()); });
  28. $('#soundButton').classList.toggle('is-active', soundEnabled); $('#soundButton').onclick = () => { soundEnabled = !soundEnabled; localStorage.setItem('zke-sound', soundEnabled); $('#soundButton').classList.toggle('is-active', soundEnabled); $('#soundButton').style.color = soundEnabled ? 'var(--lime)' : ''; tone(); };
  29. $('#themeButton').onclick = () => { document.body.classList.toggle('light-theme'); $('#themeButton').textContent = document.body.classList.contains('light-theme') ? '◑' : '◐'; };
  30. document.querySelectorAll('[data-open-modal]').forEach(button => button.onclick = () => { const modal = $(`#${button.dataset.openModal}`); if (modal.id === 'quizModal') renderQuiz(); modal.showModal(); }); document.querySelectorAll('.modal-close').forEach(button => button.onclick = () => button.closest('dialog').close());
  31. // Compact minesweeper: mines are placed after the first move, so it is always safe.
  32. const mineBoard = $('#minesweeperBoard');
  33. const mineMessage = $('#minesweeperMessage');
  34. const mineCounter = $('#minesweeperMines');
  35. const mineFlagToggle = $('#minesweeperFlagToggle');
  36. const mineSize = 9;
  37. const mineTotal = 10;
  38. let mineCells = [];
  39. let mineGameOver = false;
  40. let mineFlagMode = false;
  41. const mineIndex = (row, column) => row * mineSize + column;
  42. function mineNeighbours(index) { const row = Math.floor(index / mineSize); const column = index % mineSize; const result = []; for (let r = row - 1; r <= row + 1; r++) for (let c = column - 1; c <= column + 1; c++) if (r >= 0 && r < mineSize && c >= 0 && c < mineSize && (r !== row || c !== column)) result.push(mineIndex(r, c)); return result; }
  43. function renderMineCell(index) { const cell = mineCells[index]; const button = mineBoard.children[index]; button.className = 'mine-cell'; button.textContent = ''; if (cell.open) { button.classList.add('is-open'); if (cell.mine) { button.classList.add('is-mine'); button.textContent = '✹'; } else if (cell.count) { button.classList.add(`number-${Math.min(cell.count, 4)}`); button.textContent = cell.count; } } else if (cell.flagged) { button.classList.add('is-flagged'); button.textContent = '⚑'; } }
  44. function updateMineCounter() { mineCounter.textContent = `МИНЫ: ${mineTotal - mineCells.filter(cell => cell.flagged).length}`; }
  45. function prepareMines(safeIndex) { const forbidden = new Set([safeIndex, ...mineNeighbours(safeIndex)]); const candidates = Array.from({ length: mineSize * mineSize }, (_, i) => i).filter(i => !forbidden.has(i)); for (let i = candidates.length - 1; i > 0; i--) { const swap = Math.floor(Math.random() * (i + 1)); [candidates[i], candidates[swap]] = [candidates[swap], candidates[i]]; } candidates.slice(0, mineTotal).forEach(index => mineCells[index].mine = true); mineCells.forEach((cell, index) => cell.count = mineNeighbours(index).filter(neighbour => mineCells[neighbour].mine).length); }
  46. function openMineCell(index) { const cell = mineCells[index]; if (mineGameOver || cell.open || cell.flagged) return; if (!mineCells.some(item => item.mine)) prepareMines(index); cell.open = true; if (cell.mine) { mineGameOver = true; mineMessage.textContent = 'Мина. Попробуйте ещё раз.'; mineCells.forEach((item, i) => { if (item.mine) { item.open = true; renderMineCell(i); } }); tone('error'); return; } renderMineCell(index); if (!cell.count) mineNeighbours(index).forEach(openMineCell); if (!mineCells.some(item => !item.mine && !item.open)) { mineGameOver = true; mineMessage.textContent = 'Поле очищено — отлично!'; tone('success'); } }
  47. function flagMineCell(index) { const cell = mineCells[index]; if (mineGameOver || cell.open) return; cell.flagged = !cell.flagged; renderMineCell(index); updateMineCounter(); }
  48. function newMinesweeper() { mineGameOver = false; mineFlagMode = false; mineCells = Array.from({ length: mineSize * mineSize }, () => ({ mine: false, open: false, flagged: false, count: 0 })); mineBoard.innerHTML = ''; mineCells.forEach((_, index) => { const button = document.createElement('button'); button.type = 'button'; button.className = 'mine-cell'; button.setAttribute('role', 'gridcell'); button.setAttribute('aria-label', `Клетка ${index + 1}`); button.onclick = () => mineFlagMode ? flagMineCell(index) : openMineCell(index); button.oncontextmenu = event => { event.preventDefault(); flagMineCell(index); }; mineBoard.append(button); }); mineMessage.textContent = 'Поле готово'; mineFlagToggle.textContent = 'Режим: открыть клетки'; mineFlagToggle.setAttribute('aria-pressed', 'false'); updateMineCounter(); }
  49. $('#minesweeperReset').onclick = newMinesweeper;
  50. mineFlagToggle.onclick = () => { mineFlagMode = !mineFlagMode; mineFlagToggle.textContent = mineFlagMode ? 'Режим: ставить флажки' : 'Режим: открыть клетки'; mineFlagToggle.setAttribute('aria-pressed', String(mineFlagMode)); };
  51. newMinesweeper();
  52. // Radio uses the selected public stream directly, so the volume slider is a native draggable control.
  53. const radioAudio = $('#radioAudio');
  54. const radioStation = $('#radioStation');
  55. const radioPlay = $('#radioPlay');
  56. const radioVolume = $('#radioVolume');
  57. const radioVolumeValue = $('#radioVolumeValue');
  58. const radioStations = $('#radioStations');
  59. const radioOptions = [...radioStation.options];
  60. function setRadioVolume() { radioAudio.volume = Number(radioVolume.value) / 100; radioVolumeValue.textContent = `${radioVolume.value}%`; }
  61. function updateRadioButton() { const isPlaying = !radioAudio.paused; radioPlay.textContent = isPlaying ? '❚❚' : '▶'; radioPlay.setAttribute('aria-label', isPlaying ? 'Поставить радио на паузу' : 'Включить радио'); }
  62. function updateRadioCards() { [...radioStations.children].forEach(card => card.classList.toggle('is-selected', card.dataset.value === radioStation.value)); }
  63. function selectRadioStation(value) { radioStation.value = value; radioStation.dispatchEvent(new Event('change')); }
  64. radioOptions.forEach(option => { const card = document.createElement('button'); card.type = 'button'; card.className = 'radio-station-card'; card.dataset.value = option.value; card.title = option.textContent; card.setAttribute('aria-label', `Включить ${option.textContent}`); card.innerHTML = `<img src="https://radiobells.com/stations/${option.dataset.logo}_70.webp" alt="" loading="lazy"><span>${option.textContent}</span>`; card.onclick = () => selectRadioStation(option.value); radioStations.append(card); });
  65. radioAudio.src = radioStation.value;
  66. setRadioVolume();
  67. radioVolume.addEventListener('input', setRadioVolume);
  68. radioPlay.onclick = async () => { if (radioAudio.paused) { try { await radioAudio.play(); } catch { radioPlay.title = 'Не удалось включить этот поток. Выберите другую станцию.'; } } else radioAudio.pause(); updateRadioButton(); };
  69. radioStation.onchange = async () => { const shouldResume = !radioAudio.paused; radioAudio.src = radioStation.value; if (shouldResume) { try { await radioAudio.play(); } catch { /* The play button keeps a retry available. */ } } updateRadioButton(); updateRadioCards(); };
  70. radioAudio.onplay = updateRadioButton;
  71. radioAudio.onpause = updateRadioButton;
  72. updateRadioCards();
  73. // Hidden story sequence: code 1984 opens a short archive and reaction test.
  74. const archiveModal = $('#archiveModal');
  75. const archiveReader = $('#archiveReader');
  76. let archiveInterval;
  77. let archiveTimeout;
  78. function clearArchiveTest() { clearInterval(archiveInterval); clearTimeout(archiveTimeout); archiveInterval = undefined; archiveTimeout = undefined; }
  79. function openArchive() { reset('Обнаружен архив №1984. Доступ предоставлен на один сеанс.'); archiveModal.showModal(); }
  80. function showArchiveFile(index) { document.querySelectorAll('[data-archive-file]').forEach(file => file.classList.toggle('is-open', +file.dataset.archiveFile === index)); clearArchiveTest(); if (index === 0) archiveReader.innerHTML = '<p><b>ШИФР СМЕНЫ</b><br>«Если лампа горит слишком ровно — проверьте не лампу, а того, кто на неё смотрит».</p>'; if (index === 1) archiveReader.innerHTML = '<p><b>ЗАПИСКА ОПЕРАТОРА</b><br>03:14. После четвёртого сигнала дверь открылась сама. В журнале этого нет. Не обсуждать по внутренней связи.</p>'; if (index === 2) archiveReader.innerHTML = '<p><b>ПРОВЕРКА ЛИНИИ</b><br>Найдите светящуюся лампу 6 раз за 10 секунд.</p><button class="button button--primary" id="startSignalTest">Запустить проверку</button>'; const startButton = $('#startSignalTest'); if (startButton) startButton.onclick = startSignalTest; }
  81. function startSignalTest() { clearArchiveTest(); let score = 0; let current = -1; let finished = false; archiveReader.innerHTML = '<div class="signal-test"><div class="signal-test__top"><span id="signalTestScore">СИГНАЛЫ: 0 / 6</span><span>10.0 c</span></div><div class="signal-lamps">' + Array.from({ length: 5 }, (_, index) => `<button class="signal-lamp" data-signal-lamp="${index}" aria-label="Сигнальная лампа ${index + 1}"></button>`).join('') + '</div></div>'; const scoreLabel = $('#signalTestScore'); const lamps = [...archiveReader.querySelectorAll('[data-signal-lamp]')]; const nextLamp = () => { lamps[current]?.classList.remove('is-target'); current = Math.floor(Math.random() * lamps.length); lamps[current].classList.add('is-target'); }; lamps.forEach((lamp, index) => lamp.onclick = () => { if (finished || index !== current) return; score++; scoreLabel.textContent = `СИГНАЛЫ: ${score} / 6`; if (score === 6) { finished = true; clearArchiveTest(); archiveReader.innerHTML = '<p><b>ЛИНИЯ ЧИСТА.</b><br>Наблюдатель отключён. Запись автоматически удалится после закрытия архива.</p>'; tone('success'); } else nextLamp(); }); nextLamp(); archiveInterval = setInterval(nextLamp, 850); archiveTimeout = setTimeout(() => { if (finished) return; finished = true; clearArchiveTest(); archiveReader.innerHTML = `<p><b>ПРОВЕРКА ЗАВЕРШЕНА.</b><br>Зафиксировано сигналов: ${score} из 6. Архив остаётся доступен.</p>`; tone('error'); }, 10000); }
  82. document.querySelectorAll('[data-archive-file]').forEach(file => file.onclick = () => showArchiveFile(+file.dataset.archiveFile));
  83. archiveModal.addEventListener('close', clearArchiveTest);