'use strict'; (function () { var CHARACTERS = [ { emoji: '🦊', name: 'Лиса' }, { emoji: '🐻', name: 'Медведь' }, { emoji: '🐸', name: 'Лягушка' }, { emoji: '🦁', name: 'Лев' }, { emoji: '🐺', name: 'Волк' }, { emoji: '🦉', name: 'Сова' }, { emoji: '🐰', name: 'Заяц' }, { emoji: '🐿️', name: 'Белка' }, { emoji: '🦔', name: 'Ёж' } ]; var state = { mode: 'draw', sequence: [], expected: null, drawing: false }; var grid, svg, sequenceEl, hintEl, doneBtn, resetBtn; var layout = []; // текущая раскладка эмодзи [emoji, emoji, ...] /* ═══ ИНИЦИАЛИЗАЦИЯ ═══════════════════════════════════ */ function init() { grid = document.getElementById('gpGrid'); svg = document.getElementById('gpSvg'); sequenceEl = document.getElementById('gpSequence'); hintEl = document.getElementById('gpHint'); doneBtn = document.getElementById('gpDone'); resetBtn = document.getElementById('gpReset'); if (!grid) return; for (var i = 0; i < 9; i++) { var cell = document.createElement('div'); cell.className = 'gp-cell'; cell.dataset.idx = i; cell.textContent = CHARACTERS[i].emoji; cell.title = CHARACTERS[i].name; grid.appendChild(cell); } layout = CHARACTERS.map(function (ch) { return ch.emoji; }); bindEvents(); } function bindEvents() { grid.addEventListener('pointerdown', onPointerDown); document.addEventListener('pointermove', onPointerMove); document.addEventListener('pointerup', onPointerUp); resetBtn.addEventListener('click', resetDraw); doneBtn.addEventListener('click', onDone); document.addEventListener('keydown', function (e) { if (e.key === 'Escape') resetDraw(); }); } /* ═══ РИСОВАНИЕ ПАРОЛЯ ═════════════════════════════════ */ function onPointerDown(e) { if (state.mode !== 'draw' && state.mode !== 'test') return; var idx = getCellAt(e.clientX, e.clientY); if (idx < 0) return; e.preventDefault(); if (state.sequence.indexOf(idx) !== -1) return; addCell(idx); state.drawing = true; } function onPointerMove(e) { if (!state.drawing) return; if (state.mode !== 'draw' && state.mode !== 'test') return; var idx = getCellAt(e.clientX, e.clientY); if (idx < 0) return; if (state.sequence.indexOf(idx) !== -1) return; addCell(idx); } function onPointerUp() { state.drawing = false; } function addCell(idx) { var prev = state.sequence[state.sequence.length - 1]; state.sequence.push(idx); grid.children[idx].classList.add('active'); if (prev !== undefined) { var a = cellCenter(prev); var b = cellCenter(idx); var line = document.createElementNS('http://www.w3.org/2000/svg', 'line'); line.setAttribute('x1', a.x); line.setAttribute('y1', a.y); line.setAttribute('x2', b.x); line.setAttribute('y2', b.y); line.setAttribute('stroke', '#6aa9ff'); line.setAttribute('stroke-width', '6'); line.setAttribute('stroke-linecap', 'round'); svg.appendChild(line); } updateSequenceView(); updateDoneBtn(); // ← вместо прямого присваивания doneBtn.disabled } function getCellAt(clientX, clientY) { var rect = grid.getBoundingClientRect(); if (clientX < rect.left || clientX > rect.right) return -1; if (clientY < rect.top || clientY > rect.bottom) return -1; var x = clientX - rect.left; var y = clientY - rect.top; var cw = rect.width / 3; var ch = rect.height / 3; var col = Math.floor(x / cw); var row = Math.floor(y / ch); if (col < 0 || col > 2 || row < 0 || row > 2) return -1; return row * 3 + col; } function cellCenter(idx) { return { x: (idx % 3) * 100 + 50, y: Math.floor(idx / 3) * 100 + 50 }; } function updateSequenceView() { if (state.sequence.length === 0) { sequenceEl.innerHTML = ''; return; } var parts = []; state.sequence.forEach(function (idx, i) { if (i > 0) parts.push('→'); parts.push('' + layout[idx] + ''); }); sequenceEl.innerHTML = parts.join(''); } /* ═══ УПРАВЛЕНИЕ КНОПКОЙ ═══════════════════════════════ Учитывает два условия: длину цепочки и состояние таймера. */ function updateDoneBtn() { if (!doneBtn || doneBtn.classList.contains('hidden')) return; // Если таймер идёт — кнопка заблокирована if (breakTimer.running) { doneBtn.disabled = true; doneBtn.title = 'Таймер идёт. Сделайте паузу или дождитесь окончания.'; return; } doneBtn.title = ''; // Обычная логика: активна только в фазах draw/test при длине >= 4 if (state.mode === 'draw' || state.mode === 'test') { doneBtn.disabled = state.sequence.length < 4; } else { doneBtn.disabled = true; } } /* ═══ СБРОС И ПЕРЕХОДЫ МЕЖДУ ФАЗАМИ ═══════════════════ */ function resetDraw() { state.mode = 'draw'; state.sequence = []; state.expected = null; state.drawing = false; svg.innerHTML = ''; sequenceEl.innerHTML = ''; Array.prototype.forEach.call(grid.children, function (c, i) { c.classList.remove('active', 'highlight', 'wrong'); c.textContent = CHARACTERS[i].emoji; c.title = CHARACTERS[i].name; }); layout = CHARACTERS.map(function (ch) { return ch.emoji; }); doneBtn.classList.remove('hidden'); doneBtn.textContent = 'Готово'; hintEl.textContent = 'Проведите линию через 4–6 персонажей. Это будет ваш пароль.'; hintEl.classList.remove('ok', 'err'); updateDoneBtn(); } function shuffle(arr) { var a = arr.slice(); for (var i = a.length - 1; i > 0; i--) { var j = Math.floor(Math.random() * (i + 1)); var tmp = a[i]; a[i] = a[j]; a[j] = tmp; } return a; } function onDone() { if (state.mode === 'draw') { startShowPhase(); } else if (state.mode === 'test') { checkTest(); } } function startShowPhase() { state.expected = state.sequence.slice(); state.mode = 'show'; hintEl.textContent = '👀 Запоминай порядок!'; hintEl.classList.remove('ok', 'err'); // Перемешать эмодзи перед показом var shuffled = shuffle(CHARACTERS.map(function (ch, idx) { return { emoji: ch.emoji, name: ch.name }; })); layout = shuffled.map(function (ch) { return ch.emoji; }); Array.prototype.forEach.call(grid.children, function (c, i) { c.textContent = shuffled[i].emoji; c.title = shuffled[i].name; c.classList.remove('active'); }); svg.innerHTML = ''; updateDoneBtn(); var i = 0; function next() { if (i >= state.expected.length) { setTimeout(function () { Array.prototype.forEach.call(grid.children, function (c) { c.classList.remove('highlight'); }); startTestPhase(); }, 600); return; } grid.children[state.expected[i]].classList.add('highlight'); i++; setTimeout(next, 600); } setTimeout(next, 300); } function startTestPhase() { state.mode = 'test'; state.sequence = []; sequenceEl.innerHTML = ''; svg.innerHTML = ''; hintEl.textContent = 'Теперь повтори по памяти!'; doneBtn.textContent = 'Проверить'; doneBtn.classList.remove('hidden'); updateDoneBtn(); } function checkTest() { var expected = state.expected; var actual = state.sequence; var correct = expected.length === actual.length && expected.every(function (v, i) { return v === actual[i]; }); state.mode = 'result'; doneBtn.classList.add('hidden'); if (correct) { hintEl.textContent = '✓ Молодец! Порядок запомнен правильно!'; hintEl.classList.add('ok'); actual.forEach(function (idx) { grid.children[idx].classList.add('highlight'); }); } else { var names = expected.map(function (idx) { return CHARACTERS[idx].emoji; }).join(' → '); hintEl.textContent = '✗ Правильно было: ' + names; hintEl.classList.add('err'); expected.forEach(function (idx) { grid.children[idx].classList.add('highlight'); }); } } /* ═══ ТАЙМЕР ПЕРЕРЫВА ═════════════════════════════════ */ var BREAK_SECONDS = 10 * 60; var breakTimer = { remaining: BREAK_SECONDS, intervalId: null, running: false }; function initBreakTimer() { var display = document.getElementById('gpTimer'); var btn = document.getElementById('gpTimerBtn'); if (!display || !btn) return; btn.addEventListener('click', function () { if (breakTimer.running) { stopBreakTimer(); display.textContent = formatBreak(BREAK_SECONDS); display.className = 'gp-break-timer'; btn.textContent = '⏱ Старт'; } else { breakTimer.remaining = BREAK_SECONDS; breakTimer.running = true; display.className = 'gp-break-timer running'; btn.textContent = '⏸ Пауза'; updateDoneBtn(); // блокируем кнопку Проверить tickBreak(); breakTimer.intervalId = setInterval(tickBreak, 1000); } }); } function tickBreak() { var display = document.getElementById('gpTimer'); var btn = document.getElementById('gpTimerBtn'); if (!display) return; display.textContent = formatBreak(breakTimer.remaining); display.className = 'gp-break-timer running'; if (breakTimer.remaining <= 60) { display.className = 'gp-break-timer danger'; } else if (breakTimer.remaining <= 180) { display.className = 'gp-break-timer warn'; } if (breakTimer.remaining <= 0) { stopBreakTimer(); display.textContent = 'Время вышло!'; display.className = 'gp-break-timer done'; if (btn) btn.textContent = '⏱ Ещё раз'; return; } breakTimer.remaining--; } function stopBreakTimer() { if (breakTimer.intervalId) { clearInterval(breakTimer.intervalId); breakTimer.intervalId = null; } breakTimer.running = false; updateDoneBtn(); // разблокируем кнопку Проверить } function formatBreak(sec) { if (sec < 0) sec = 0; var m = Math.floor(sec / 60); var s = sec % 60; return (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s; } /* ═══ ЗАПУСК ═══════════════════════════════════════════ */ var _origInit = init; init = function () { _origInit(); initBreakTimer(); }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();