| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156 |
- /* activities.js — extensible mini-game catalogue layered on the existing lab UI. */
- (() => {
- 'use strict';
- const $ = (selector, root = document) => root.querySelector(selector);
- const grid = $('#activityGrid');
- const bannerGrid = $('#bannerGrid');
- const sideBannerLeft = $('#sideBannerLeft');
- const sideBannerRight = $('#sideBannerRight');
- const modal = $('#activityModal');
- const body = $('#activityBody');
- const title = $('#activityTitle');
- const subtitle = $('#activitySubtitle');
- const scoreLabel = $('#activityScore');
- const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
- let cleanup = () => {};
- const activities = [
- { id:'reaction', category:'skill', icon:'⚡', name:'Импульс реакции', description:'Поймайте сигнал пять раз и улучшите собственное время.', level:'быстро', type:'Реакция' },
- { id:'memory', category:'skill', icon:'◈', name:'Код памяти', description:'Запомните последовательность световых ячеек.', level:'средне', type:'Память' },
- { id:'logic', category:'skill', icon:'⌘', name:'Логический ряд', description:'Найдите недостающий элемент в инженерной последовательности.', level:'средне', type:'Логика' },
- { id:'catch', category:'arcade', icon:'✦', name:'Сбор сигнала', description:'Двигайте контейнер и собирайте падающие импульсы.', level:'динамично', type:'Аркада' },
- { id:'maze', category:'arcade', icon:'⌗', name:'Технический лабиринт', description:'Доведите индикатор до выхода за минимальное число ходов.', level:'точно', type:'Лабиринт' },
- { id:'balance', category:'skill', icon:'◒', name:'Баланс гироскопа', description:'Удерживайте отметку в зелёной зоне десять секунд.', level:'выдержка', type:'Тайминг' },
- { id:'drone', category:'simulator', icon:'✈', name:'Симулятор Герани', description:'Аркадная миссия дрона: контрольные точки, препятствия и время.', level:'миссия', type:'Симулятор' },
- { id:'sequence', category:'skill', icon:'↯', name:'Быстрый протокол', description:'Повторите меняющийся порядок команд до сбоя.', level:'растёт', type:'Последовательность' }
- ];
- const bannerConfig = [
- { image:'assets/banners/alabuga.png', url:'https://alabuga.ru/politech/', title:'Алабуга Политех — поступление' },
- { image:'assets/banners/tanks.png', url:'https://tanki.su/', title:'Мир танков' },
- { image:'assets/banners/edros.png', url:'https://er.ru/', title:'Единая Россия' },
- { image:'assets/banners/cook.png', url:'https://защитники-родины.рф/', title:'Вакансии повара в тыловые войска' },
- { image:'assets/banners/contract.png', url:'https://службапоконтракту.рф/', title:'Военная служба по контракту' },
- { image:'assets/banners/geranium-training.png', url:'https://alabuga.ru/politech/', title:'Обучение работе с «Геранями»' },
- { image:'assets/banners/recruit.png', url:'https://защитники-родины.рф/', title:'Информация для защитников' }
- ];
- function renderBanners() {
- const markup = item => `<a class="banner-card" href="${item.url}" target="_blank" rel="noopener noreferrer" aria-label="${item.title}"><img src="${item.image}" alt="${item.title}" loading="lazy"></a>`;
- bannerGrid.innerHTML = bannerConfig.map(markup).join('');
- sideBannerLeft.innerHTML = bannerConfig.filter((_, index) => index % 2 === 0).map(markup).join('');
- sideBannerRight.innerHTML = bannerConfig.filter((_, index) => index % 2 === 1).map(markup).join('');
- }
- function renderCatalog(filter = 'all') {
- grid.innerHTML = activities.map(item => `<article class="activity-card" data-category="${item.category}" data-hidden="${filter !== 'all' && item.category !== filter}"><div class="activity-card__icon" aria-hidden="true">${item.icon}</div><h3>${item.name}</h3><p>${item.description}</p><div class="activity-card__meta"><span>${item.type}</span><span>${item.level}</span></div><button class="button button--ghost" data-activity="${item.id}">Запустить</button></article>`).join('');
- grid.querySelectorAll('[data-activity]').forEach(button => button.onclick = () => openActivity(button.dataset.activity));
- }
- document.querySelectorAll('[data-activity-filter]').forEach(button => button.onclick = () => {
- document.querySelectorAll('[data-activity-filter]').forEach(item => item.classList.toggle('is-active', item === button));
- renderCatalog(button.dataset.activityFilter);
- });
- document.querySelectorAll('[data-activity-launch]').forEach(button => button.onclick = () => openActivity(button.dataset.activityLaunch));
- renderCatalog(); renderBanners();
- function setScore(value) { scoreLabel.textContent = String(value); }
- function openActivity(id) {
- cleanup(); cleanup = () => {};
- const item = activities.find(activity => activity.id === id);
- if (!item) return;
- title.textContent = item.name; subtitle.textContent = item.description; setScore(localStorage.getItem(`zke-activity-${id}`) || 0);
- if (!modal.open) modal.showModal();
- ({ reaction: initReaction, memory: initMemory, logic: initLogic, catch: initCatch, maze: initMaze, balance: initBalance, drone: initDrone, sequence: initSequence }[id])();
- }
- $('#activityClose').onclick = () => modal.close();
- modal.addEventListener('close', () => { cleanup(); cleanup = () => {}; });
- function saveBest(id, value) {
- const current = Number(localStorage.getItem(`zke-activity-${id}`) || 0);
- if (value > current) localStorage.setItem(`zke-activity-${id}`, String(value));
- setScore(Math.max(current, value));
- }
- function shell(html) { body.innerHTML = `<div class="activity-stage">${html}</div>`; return $('.activity-stage'); }
- function actionButton(label, fn, primary = false) { const button = document.createElement('button'); button.className = `button button--${primary ? 'primary' : 'ghost'}`; button.textContent = label; button.onclick = fn; return button; }
- function initReaction() {
- const stage = shell('<div class="activity-stage__top"><span id="reactionRound">РАУНД 1 / 7</span><span id="reactionTime">—</span></div><button class="reaction-target" id="reactionTarget">Нажмите «Старт»</button><div class="activity-actions" id="reactionActions"></div>');
- const target = $('#reactionTarget', stage), roundLabel = $('#reactionRound', stage), timeLabel = $('#reactionTime', stage), actions = $('#reactionActions', stage);
- let round = 0, startedAt = 0, timer = 0, total = 0, penalty = 0, active = false, finished = false;
- const start = () => { if (finished) return; active = false; target.classList.remove('is-ready'); target.textContent = 'Ждите сигнала…'; target.style.transform = `translate(${Math.round(Math.random()*14-7)}px,${Math.round(Math.random()*10-5)}px)`; clearTimeout(timer); timer = setTimeout(() => { active = true; startedAt = performance.now(); target.classList.add('is-ready'); target.textContent = 'ЖМИТЕ!'; }, 450 + Math.random() * 1450); };
- const restart = () => { round = 0; total = 0; penalty = 0; finished = false; roundLabel.textContent = 'РАУНД 1 / 7'; timeLabel.textContent = '—'; actions.innerHTML = ''; start(); };
- target.onclick = () => { if (!active) { if (round > 0) { penalty += 300; timeLabel.textContent = 'Фальстарт +300 мс'; target.textContent = 'Фальстарт — снова ждите'; start(); } return; } const ms = Math.round(performance.now() - startedAt); active = false; total += ms; round++; timeLabel.textContent = `${ms} мс`; if (round >= 7) { finished = true; const result = Math.max(1, Math.round(9000 - total - penalty)); setScore(result); saveBest('reaction', result); target.textContent = `Готово · среднее ${Math.round(total / 7)} мс`; actions.append(actionButton('Повторить', restart, true)); } else { roundLabel.textContent = `РАУНД ${round + 1} / 7`; start(); } };
- actions.append(actionButton('Начать заново', restart)); restart();
- cleanup = () => clearTimeout(timer);
- }
- function initMemory() {
- const stage = shell('<div class="activity-stage__top"><span id="memoryRound">УРОВЕНЬ 1</span><span id="memoryHint">Смотрите</span></div><div class="memory-sequence" id="memorySequence"></div><div class="memory-pad" id="memoryPad"></div><div class="activity-actions" id="memoryActions"></div>');
- const sequenceEl = $('#memorySequence', stage), pad = $('#memoryPad', stage), label = $('#memoryRound', stage), hint = $('#memoryHint', stage), actions = $('#memoryActions', stage);
- let sequence = [], entered = [], level = 1, accepting = false, timers = [];
- const clearTimers = () => { timers.forEach(clearTimeout); timers = []; }; const cells = ['1','2','3','4','5','6','7','8','9','A','B','C'];
- const showSequence = () => { accepting = false; hint.textContent = 'Смотрите'; sequenceEl.innerHTML = sequence.map(value => `<span>${value}</span>`).join(''); const pace = Math.max(290,470-level*18); sequence.forEach((value, index) => timers.push(setTimeout(() => { const button = pad.children[cells.indexOf(value)]; button?.classList.add('is-lit'); setTimeout(() => button?.classList.remove('is-lit'), 210); if (index === sequence.length - 1) { accepting = true; hint.textContent = 'Повторите'; } }, pace * index + 280))); };
- const next = () => { level++; sequence.push(cells[Math.floor(Math.random() * cells.length)]); if (level >= 7) sequence.push(cells[Math.floor(Math.random() * cells.length)]); label.textContent = `УРОВЕНЬ ${level}`; entered = []; showSequence(); };
- const finish = success => { accepting = false; clearTimers(); hint.textContent = success ? 'Протокол памяти пройден!' : 'Сбой последовательности'; setScore(level - (success ? 0 : 1)); saveBest('memory', Math.max(0, level - (success ? 0 : 1))); actions.innerHTML = ''; actions.append(actionButton('Повторить', restart, true)); };
- const restart = () => { clearTimers(); level = 1; sequence = [cells[Math.floor(Math.random() * cells.length)]]; entered = []; label.textContent = 'УРОВЕНЬ 1'; actions.innerHTML = ''; showSequence(); };
- cells.forEach((value, index) => { const button = document.createElement('button'); button.textContent = value; button.setAttribute('aria-label', `Ячейка ${value}`); button.onclick = () => { if (!accepting) return; entered.push(value); if (value !== sequence[entered.length - 1]) return finish(false); if (entered.length === sequence.length) { if (level >= 9) finish(true); else next(); } }; pad.append(button); });
- actions.append(actionButton('Начать заново', restart)); restart(); cleanup = clearTimers;
- }
- function initLogic() {
- const stage = shell('<div class="activity-stage__top"><span id="logicRound">ЗАДАЧА 1 / 8</span><span id="logicClock">12.0 c</span></div><div class="memory-sequence" id="logicSequence"></div><div class="logic-options" id="logicOptions"></div><div class="activity-actions" id="logicActions"></div>');
- const sequenceEl = $('#logicSequence', stage), optionsEl = $('#logicOptions', stage), roundEl = $('#logicRound', stage), clock = $('#logicClock', stage), actions = $('#logicActions', stage);
- const tasks = [{seq:'2 · 6 · 18 · 54 · ?', opts:['108','162','216','324'], answer:1}, {seq:'▲ ● ▲ ● ▲ ?', opts:['▲','■','●','◆'], answer:2}, {seq:'4 · 9 · 16 · 25 · ?', opts:['30','32','36','40'], answer:2}, {seq:'А · В · Д · Ж · ?', opts:['З','И','К','Л'], answer:1}, {seq:'1 · 1 · 2 · 3 · 5 · 8 · ?', opts:['11','12','13','14'], answer:2}, {seq:'12 · 10 · 7 · 3 · ?', opts:['0','-1','-2','1'], answer:2}, {seq:'◐ ◑ ◐ ◑ ?', opts:['◐','◑','●','○'], answer:0}, {seq:'5 · 8 · 14 · 26 · ?', opts:['38','44','50','52'], answer:2}];
- let index = 0, score = 0, left = 12, timer = 0;
- const finish = () => { clearInterval(timer); setScore(score); saveBest('logic', score); optionsEl.innerHTML = ''; sequenceEl.innerHTML = `<span style="width:auto;padding:0 18px">Результат: ${score} / ${tasks.length}</span>`; clock.textContent = 'ГОТОВО'; actions.innerHTML = ''; actions.append(actionButton('Повторить', restart, true)); };
- const draw = () => { if (index >= tasks.length) return finish(); const task = tasks[index]; left = Math.max(5.5, 12 - index * .55); clock.textContent = `${left.toFixed(1)} c`; roundEl.textContent = `ЗАДАЧА ${index + 1} / ${tasks.length}`; sequenceEl.innerHTML = `<span style="width:auto;padding:0 18px">${task.seq}</span>`; optionsEl.innerHTML = task.opts.map((option, i) => `<button data-answer="${i}">${option}</button>`).join(''); optionsEl.querySelectorAll('button').forEach(button => button.onclick = () => { if (+button.dataset.answer === task.answer) score++; index++; draw(); }); };
- const restart = () => { clearInterval(timer); index = 0; score = 0; left = 12; timer = setInterval(() => { if (index >= tasks.length) return; left -= .1; clock.textContent = `${Math.max(0,left).toFixed(1)} c`; if (left <= 0) { index++; draw(); } }, 100); actions.innerHTML = ''; draw(); };
- actions.append(actionButton('Сбросить', restart)); restart(); cleanup = () => clearInterval(timer);
- }
- function initCatch() {
- const stage = shell('<div class="activity-stage__top"><span id="catchTime">25.0 c</span><span id="catchCount">СИГНАЛЫ: 0 · КОМБО 0</span></div><div class="catch-field" id="catchField"><div class="catch-basket" id="catchBasket"></div></div><div class="activity-actions" id="catchActions"></div>');
- const field = $('#catchField', stage), basket = $('#catchBasket', stage), timeLabel = $('#catchTime', stage), countLabel = $('#catchCount', stage), actions = $('#catchActions', stage);
- let x = .5, count = 0, combo = 0, left = 25, raf = 0, last = 0, items = [], finished = false, spawnClock = 0;
- const move = clientX => { const rect = field.getBoundingClientRect(); x = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)); basket.style.left = `calc(${x * 100}% - 31px)`; };
- const spawn = () => { if (finished || items.length > 4) return; const el = document.createElement('i'), roll = Math.random(); const kind = roll < .12 ? 'hazard' : roll < .28 ? 'bonus' : 'signal'; el.className = `catch-item is-${kind}`; el.style.left = `${8 + Math.random() * 84}%`; el.style.top = '-15px'; field.append(el); items.push({el,y:-15,kind,speed:105 + Math.min(90,(25-left)*4) + Math.random()*45}); };
- const end = () => { finished = true; cancelAnimationFrame(raf); items.forEach(item => item.el.remove()); items=[]; const result = Math.max(0,count*10+combo*3); setScore(result); saveBest('catch', result); actions.innerHTML = ''; actions.append(actionButton('Повторить', restart, true)); timeLabel.textContent = 'Время вышло'; };
- const frame = time => { if (finished) return; const dt = last ? (time - last) / 1000 : 0; last = time; left -= dt; spawnClock += dt; timeLabel.textContent = `${Math.max(0, left).toFixed(1)} c`; if (left <= 0) return end(); if (spawnClock > Math.max(.26,.72-left*.012)) { spawnClock=0; spawn(); if (left<15 && Math.random()<.35) spawn(); } const basketLeft=x*field.clientWidth; items.forEach(item=>{item.y += item.speed*dt; item.el.style.top=`${item.y}px`; const itemLeft=item.el.offsetLeft+6; if(item.y>field.clientHeight-45 && Math.abs(itemLeft-basketLeft)<42){if(item.kind==='hazard'){combo=0;count=Math.max(0,count-2);}else{count += item.kind==='bonus'?2:1;combo++;}item.el.remove();item.dead=true;countLabel.textContent=`СИГНАЛЫ: ${count} · КОМБО ${combo}`;}else if(item.y>field.clientHeight+15){if(item.kind==='signal')combo=0;item.el.remove();item.dead=true;}});items=items.filter(item=>!item.dead);raf=requestAnimationFrame(frame); };
- const restart = () => { cancelAnimationFrame(raf); items.forEach(item=>item.el.remove()); items=[]; count=0;combo=0;left=25;finished=false;spawnClock=0;last=0;countLabel.textContent='СИГНАЛЫ: 0 · КОМБО 0'; raf=requestAnimationFrame(frame); };
- field.onpointermove = event => { if (event.buttons || event.pointerType === 'touch') move(event.clientX); }; field.onpointerdown = event => { field.setPointerCapture(event.pointerId); move(event.clientX); }; const keydown = event => { if (!modal.open || title.textContent !== 'Сбор сигнала') return; if (event.key === 'ArrowLeft') x = Math.max(0, x - .06); if (event.key === 'ArrowRight') x = Math.min(1, x + .06); move(field.getBoundingClientRect().left + x * field.clientWidth); }; window.addEventListener('keydown', keydown); actions.append(actionButton('Начать заново', restart)); restart(); cleanup = () => { cancelAnimationFrame(raf); window.removeEventListener('keydown', keydown); };
- }
- function initMaze() {
- const stage = shell('<div class="activity-stage__top"><span id="mazeMoves">УРОВЕНЬ 1 · ХОДЫ 0</span><span id="mazeClock">35.0 c</span></div><div class="maze-board" id="mazeBoard"></div><div class="drone-controls maze-controls" aria-label="Управление лабиринтом"><button data-maze="up">▲</button><button data-maze="left">◀</button><button data-maze="down">▼</button><button data-maze="right">▶</button></div><div class="activity-actions" id="mazeActions"></div>');
- const board = $('#mazeBoard', stage), movesLabel = $('#mazeMoves', stage), clock = $('#mazeClock', stage), actions = $('#mazeActions', stage);
- const maps = [['111111111','100000001','101111101','101000101','101011101','101010101','101010001','1000000E1','111111111'],['111111111','100010001','101010101','101010101','101000101','111011101','100000001','1011110E1','111111111'],['111111111','100000001','111110101','100010101','101010101','101010101','101010001','1000000E1','111111111']];
- let map = maps[0], level = 1, player = {x:1,y:1}, moves = 0, left = 35, done = false, timer = 0;
- const draw = () => { board.innerHTML = ''; map.forEach((row,y) => [...row].forEach((cell,x) => { const el = document.createElement('i'); el.className = `maze-cell${cell === '1' ? ' is-wall' : ''}${cell === 'E' ? ' is-exit' : ''}${player.x === x && player.y === y ? ' is-player' : ''}`; board.append(el); })); movesLabel.textContent = `УРОВЕНЬ ${level} · ХОДЫ ${moves}`; clock.textContent = `${Math.max(0,left).toFixed(1)} c`; };
- const restart = () => { clearInterval(timer); map = maps[level-1]; player = {x:1,y:1}; moves = 0; left = 35 - (level-1)*5; done = false; actions.innerHTML = ''; timer = setInterval(() => { if(done)return; left-=.1; draw(); if(left<=0){done=true;clearInterval(timer);actions.append(actionButton('Повторить',restart,true));} },100); draw(); };
- const keydown = event => { if (!modal.open || title.textContent !== 'Технический лабиринт' || done) return; const dirs = {ArrowUp:[0,-1],ArrowDown:[0,1],ArrowLeft:[-1,0],ArrowRight:[1,0],w:[0,-1],s:[0,1],a:[-1,0],d:[1,0]}; const dir = dirs[event.key]; if (!dir) return; event.preventDefault(); const nx = player.x + dir[0], ny = player.y + dir[1]; if (map[ny]?.[nx] === '1') return; player = {x:nx,y:ny}; moves++; draw(); if (map[ny][nx] === 'E') { if(level<maps.length){level++;restart();}else{done=true;clearInterval(timer);const result=Math.max(1,220-moves*3+Math.round(left));setScore(result);saveBest('maze',result);actions.append(actionButton('Пройти ещё раз',()=>{level=1;restart();},true));} } };
- window.addEventListener('keydown', keydown); stage.querySelectorAll('[data-maze]').forEach(button => button.onclick = () => { const eventKey = {up:'ArrowUp',down:'ArrowDown',left:'ArrowLeft',right:'ArrowRight'}[button.dataset.maze]; keydown({key:eventKey, preventDefault(){}}); }); actions.append(actionButton('Сбросить',()=>{level=1;restart();})); restart(); cleanup = () => { clearInterval(timer); window.removeEventListener('keydown', keydown); };
- }
- function initBalance() {
- const stage = shell('<div class="activity-stage__top"><span id="balanceTime">12.0 c</span><span id="balanceState">стабилизация</span></div><div class="balance-track" id="balanceTrack"><i class="balance-zone"></i><b class="balance-dot" id="balanceDot"></b></div><input id="balanceInput" type="range" min="0" max="100" value="50" aria-label="Положение гироскопа"><div class="activity-actions" id="balanceActions"></div>');
- const input = $('#balanceInput', stage), dot = $('#balanceDot', stage), timeLabel = $('#balanceTime', stage), stateLabel = $('#balanceState', stage), actions = $('#balanceActions', stage); let left = 10, raf = 0, last = 0, finished = false, stability = 0;
- const draw = () => { const value = Number(input.value); dot.style.left = `${value}%`; const good = value >= 38 && value <= 62; stateLabel.textContent = good ? 'стабильно' : 'исправьте курс'; stateLabel.style.color = good ? 'var(--lime)' : 'var(--orange)'; };
- const end = success => { finished = true; cancelAnimationFrame(raf); const score = success ? Math.round(stability * 10) : Math.round(stability * 10); setScore(score); saveBest('balance', score); stateLabel.textContent = success ? 'баланс удержан' : 'срыв баланса'; actions.innerHTML = ''; actions.append(actionButton('Повторить', restart, true)); };
- const frame = time => { if (finished) return; const dt = last ? (time - last) / 1000 : 0; last = time; left -= dt; const drift = Math.sin(time*.0017)*9 + Math.sin(time*.0041)*4; const value = Math.max(0,Math.min(100,Number(input.value) + drift*dt)); input.value = value; draw(); if (value >= 38 && value <= 62) stability += dt; timeLabel.textContent = `${Math.max(0,left).toFixed(1)} c`; if (left <= 0) return end(stability >= 9.2); raf = requestAnimationFrame(frame); };
- const restart = () => { cancelAnimationFrame(raf); left = 12; stability = 0; finished = false; input.value = 50; draw(); actions.innerHTML = ''; last = 0; raf = requestAnimationFrame(frame); };
- input.oninput = draw; actions.append(actionButton('Начать заново', restart)); restart(); cleanup = () => cancelAnimationFrame(raf);
- }
- function initSequence() {
- const stage = shell('<div class="activity-stage__top"><span id="sequenceRound">РАУНД 1 / 8</span><span id="sequenceStatus">готово</span></div><div class="memory-pad" id="sequencePad"></div><div class="activity-actions" id="sequenceActions"></div>');
- const pad = $('#sequencePad', stage), roundLabel = $('#sequenceRound', stage), status = $('#sequenceStatus', stage), actions = $('#sequenceActions', stage); let order = [], expected = 0, round = 1, locked = false, deadline = 0;
- const next = () => { order = [0,1,2,3,4,5].sort(() => Math.random() - .5); expected = 0; locked = false; deadline = performance.now() + Math.max(1900,3600-round*180); roundLabel.textContent = `РАУНД ${round} / 8`; status.textContent = 'нажмите по порядку'; [...pad.children].forEach((button, i) => { button.textContent = order[i] + 1; button.dataset.value = order[i]; }); };
- const fail = message => { locked = true; status.textContent = message; actions.innerHTML = ''; actions.append(actionButton('Повторить', restart, true)); };
- const restart = () => { round = 1; actions.innerHTML = ''; next(); };
- [...Array(6)].forEach((_, index) => { const button = document.createElement('button'); button.textContent = index + 1; button.onclick = () => { if (locked) return; if (performance.now()>deadline) return fail('время вышло'); if (+button.dataset.value !== expected) return fail('сбой протокола'); expected++; if (expected === 6) { if (round === 8) { locked = true; setScore(round); saveBest('sequence', round); status.textContent = 'протокол завершён'; actions.append(actionButton('Ещё раз', restart, true)); } else { round++; next(); } } }; pad.append(button); });
- actions.append(actionButton('Сбросить', restart)); restart();
- }
- function initDrone() {
- cleanup = window.GeraniumFlight.mount(body, score => saveBest('drone', score));
- return;
- }
- })();
|