Просмотр исходного кода

Загрузить файлы 'js'

u23-27eroshko 1 месяц назад
Родитель
Сommit
81ed6f71a6
5 измененных файлов с 693 добавлено и 0 удалено
  1. 156 0
      js/activities.js
  2. 88 0
      js/app.js
  3. 307 0
      js/arcade.js
  4. 49 0
      js/flight.js
  5. 93 0
      js/weather.js

+ 156 - 0
js/activities.js

@@ -0,0 +1,156 @@
+/* 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;
+  }
+})();

+ 88 - 0
js/app.js

@@ -0,0 +1,88 @@
+/* app.js — interaction layer: code validation, visual state, sound, dialogs and local persistence. */
+const $ = (selector) => document.querySelector(selector);
+const stages = [...document.querySelectorAll('.stage')];
+let activeCode = localStorage.getItem('zke-code') || '1234';
+let entered = [];
+let timerId;
+let soundEnabled = localStorage.getItem('zke-sound') === 'true';
+const quiz = [
+  ['Что происходит при неверной цифре?', ['Цепь продолжает работу', 'Цепь сбрасывается', 'Дверь открывается'], 1],
+  ['Какой элемент физически убирает защёлку?', ['Электромагнит', 'Тиристор', 'Клавиша'], 0],
+  ['Сколько каскадов в этой учебной модели?', ['Два', 'Четыре', 'Десять'], 1]
+];
+const secretCode = '1984';
+
+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); }
+function setLog(text) { $('#eventLog').textContent = text; }
+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 ? 'проводит' : 'ожидание'; }); }
+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); }
+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); }
+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); }
+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(); }
+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('Настройки применены. Можно проверить новый код.'); }
+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))); }
+
+$('#codeInput').value = activeCode; updateScreen();
+$('#keypad').addEventListener('click', e => { const key = e.target.dataset.key; if (key) input(key); });
+$('#keypadReset').onclick = () => reset(); $('#resetButton').onclick = () => reset(); $('#backspaceButton').onclick = () => { if (!entered.length || timerId) return; entered.pop(); updateScreen(); setLog('Последний каскад снят вручную.'); };
+$('#applyCode').onclick = applyCode; $('#codeInput').addEventListener('keydown', e => { if (e.key === 'Enter') applyCode(); });
+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()); });
+$('#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(); };
+$('#themeButton').onclick = () => { document.body.classList.toggle('light-theme'); $('#themeButton').textContent = document.body.classList.contains('light-theme') ? '◑' : '◐'; };
+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());
+
+// Compact minesweeper: mines are placed after the first move, so it is always safe.
+const mineBoard = $('#minesweeperBoard');
+const mineMessage = $('#minesweeperMessage');
+const mineCounter = $('#minesweeperMines');
+const mineFlagToggle = $('#minesweeperFlagToggle');
+const mineSize = 9;
+const mineTotal = 10;
+let mineCells = [];
+let mineGameOver = false;
+let mineFlagMode = false;
+const mineIndex = (row, column) => row * mineSize + column;
+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; }
+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 = '⚑'; } }
+function updateMineCounter() { mineCounter.textContent = `МИНЫ: ${mineTotal - mineCells.filter(cell => cell.flagged).length}`; }
+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); }
+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'); } }
+function flagMineCell(index) { const cell = mineCells[index]; if (mineGameOver || cell.open) return; cell.flagged = !cell.flagged; renderMineCell(index); updateMineCounter(); }
+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(); }
+$('#minesweeperReset').onclick = newMinesweeper;
+mineFlagToggle.onclick = () => { mineFlagMode = !mineFlagMode; mineFlagToggle.textContent = mineFlagMode ? 'Режим: ставить флажки' : 'Режим: открыть клетки'; mineFlagToggle.setAttribute('aria-pressed', String(mineFlagMode)); };
+newMinesweeper();
+
+// Radio uses the selected public stream directly, so the volume slider is a native draggable control.
+const radioAudio = $('#radioAudio');
+const radioStation = $('#radioStation');
+const radioPlay = $('#radioPlay');
+const radioVolume = $('#radioVolume');
+const radioVolumeValue = $('#radioVolumeValue');
+const radioStations = $('#radioStations');
+const radioOptions = [...radioStation.options];
+function setRadioVolume() { radioAudio.volume = Number(radioVolume.value) / 100; radioVolumeValue.textContent = `${radioVolume.value}%`; }
+function updateRadioButton() { const isPlaying = !radioAudio.paused; radioPlay.textContent = isPlaying ? '❚❚' : '▶'; radioPlay.setAttribute('aria-label', isPlaying ? 'Поставить радио на паузу' : 'Включить радио'); }
+function updateRadioCards() { [...radioStations.children].forEach(card => card.classList.toggle('is-selected', card.dataset.value === radioStation.value)); }
+function selectRadioStation(value) { radioStation.value = value; radioStation.dispatchEvent(new Event('change')); }
+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); });
+radioAudio.src = radioStation.value;
+setRadioVolume();
+radioVolume.addEventListener('input', setRadioVolume);
+radioPlay.onclick = async () => { if (radioAudio.paused) { try { await radioAudio.play(); } catch { radioPlay.title = 'Не удалось включить этот поток. Выберите другую станцию.'; } } else radioAudio.pause(); updateRadioButton(); };
+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(); };
+radioAudio.onplay = updateRadioButton;
+radioAudio.onpause = updateRadioButton;
+updateRadioCards();
+
+// Hidden story sequence: code 1984 opens a short archive and reaction test.
+const archiveModal = $('#archiveModal');
+const archiveReader = $('#archiveReader');
+let archiveInterval;
+let archiveTimeout;
+function clearArchiveTest() { clearInterval(archiveInterval); clearTimeout(archiveTimeout); archiveInterval = undefined; archiveTimeout = undefined; }
+function openArchive() { reset('Обнаружен архив №1984. Доступ предоставлен на один сеанс.'); archiveModal.showModal(); }
+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; }
+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); }
+document.querySelectorAll('[data-archive-file]').forEach(file => file.onclick = () => showArchiveFile(+file.dataset.archiveFile));
+archiveModal.addEventListener('close', clearArchiveTest);

+ 307 - 0
js/arcade.js

@@ -0,0 +1,307 @@
+(() => {
+  'use strict';
+  const modal = document.querySelector('#arcadeModal');
+  const canvas = document.querySelector('#arcadeCanvas');
+  const ctx = canvas.getContext('2d');
+  const ui = name => document.querySelector('#arcade' + name);
+  const W = 360, H = 480;
+  const held = new Set(), pointers = new Map();
+  let mode, state, paused = false, over = false, raf = 0, last = 0, accumulator = 0, best = 0;
+  const random = (a,b) => a + Math.random() * (b-a);
+  const clamp = (v,a,b) => Math.max(a,Math.min(b,v));
+  function record() {
+    if (state.score > best) {
+      best = state.score;
+      try { localStorage.setItem('zke-arcade-' + mode, String(best)); } catch {}
+    }
+    ui('Score').textContent = 'Счёт: ' + state.score;
+    if (mode === 'jump') ui('Score').textContent += ' · Уровень ' + (1 + Math.floor(difficulty(state.score) * 5));
+    ui('Best').textContent = 'Рекорд: ' + best;
+  }
+  function end(message) {
+    over = true; record(); held.clear(); pointers.clear();
+    ui('Status').textContent = message + ' Счёт: ' + state.score;
+    ui('Pause').disabled = true;
+  }
+  function pause(value = !paused) {
+    if (over || !modal.open) return;
+    paused = value; held.clear(); pointers.clear();
+    ui('Pause').textContent = paused ? 'Продолжить' : 'Пауза';
+    ui('Status').textContent = paused ? 'Пауза' : 'Игра идёт';
+    last = 0; accumulator = 0; draw();
+  }
+  function restart() {
+    cancelAnimationFrame(raf); paused = false; over = false; held.clear(); pointers.clear();
+    last = 0; accumulator = 0;
+    try { best = Number(localStorage.getItem('zke-arcade-' + mode)) || 0; } catch { best = 0; }
+    ui('Pause').textContent = 'Пауза'; ui('Pause').disabled = false;
+    ui('Status').textContent = 'Игра идёт';
+    state = mode === 'snake' ? newSnake() : newJump();
+    record(); draw(); raf = requestAnimationFrame(frame); canvas.focus();
+  }
+  function open(type) {
+    mode = type;
+    ui('Title').textContent = type === 'jump' ? 'Прыжок оператора' : 'Змейка';
+    ui('Help').textContent = type === 'jump'
+      ? '← → или A/D — движение · W / Пробел — огонь · P — пауза. Края соединены. Зелёные площадки прочные, голубые движутся, рыжие ломаются, белые исчезают. Пружина ↑, ранец J, щит S.'
+      : 'Стрелки или WASD — поворот · P — пауза. Собирайте еду, избегайте стен и своего хвоста.';
+    document.querySelectorAll('[data-control]').forEach(button => {
+      button.hidden = type === 'jump' ? ['up','down'].includes(button.dataset.control) : button.dataset.control === 'shoot';
+    });
+    if (!modal.open) modal.showModal();
+    restart();
+  }
+  // All input and animation belong to the open game only.
+  document.querySelectorAll('[data-arcade]').forEach(button => button.addEventListener('click', () => open(button.dataset.arcade)));
+  ui('Restart').onclick = restart; ui('Pause').onclick = () => pause();
+  ui('Close').onclick = () => modal.close();
+  modal.addEventListener('close', () => { cancelAnimationFrame(raf); held.clear(); pointers.clear(); last = 0; });
+  window.addEventListener('blur', () => pause(true));
+  document.addEventListener('visibilitychange', () => { if (document.hidden) pause(true); });
+  const keys = { ArrowLeft:'left', ArrowRight:'right', ArrowUp:'up', ArrowDown:'down', KeyA:'left', KeyD:'right', KeyW:'up', KeyS:'down', Space:'shoot' };
+  document.addEventListener('keydown', event => {
+    if (!modal.open) return;
+    if (event.code === 'Escape') return;
+    event.stopImmediatePropagation();
+    if (event.code === 'KeyP') { event.preventDefault(); if (!event.repeat) pause(); return; }
+    const control = mode === 'jump' && event.code === 'KeyW' ? 'shoot' : keys[event.code];
+    if (!control) return;
+    event.preventDefault();
+    if (paused || over) return;
+    held.add(event.code);
+    if (mode === 'snake') turn(control);
+  }, true);
+  document.addEventListener('keyup', event => { if (modal.open) held.delete(event.code); });
+  document.querySelectorAll('[data-control]').forEach(button => {
+    button.addEventListener('pointerdown', event => {
+      if (paused || over) return;
+      event.preventDefault(); button.setPointerCapture(event.pointerId);
+      pointers.set(event.pointerId, button.dataset.control);
+      if (mode === 'snake') turn(button.dataset.control);
+    });
+    const release = event => pointers.delete(event.pointerId);
+    button.addEventListener('pointerup', release);
+    button.addEventListener('pointercancel', release);
+    button.addEventListener('lostpointercapture', release);
+  });
+  const pressed = key => [...held].some(code => (mode === 'jump' && code === 'KeyW' ? 'shoot' : keys[code]) === key) || [...pointers.values()].includes(key);
+  function frame(time) {
+    if (!modal.open) return;
+    const dt = last ? Math.min((time-last)/1000, .05) : 0; last = time;
+    if (!paused && !over) {
+      accumulator += dt;
+      while (accumulator >= 1/120 && !over) {
+        mode === 'jump' ? stepJump(1/120) : stepSnake(1/120);
+        accumulator -= 1/120;
+      }
+      record();
+    }
+    draw();
+    raf = requestAnimationFrame(frame);
+  }
+  function newSnake() {
+    const s = { body:[{x:9,y:12},{x:8,y:12},{x:7,y:12}], dir:{x:1,y:0}, queue:[], elapsed:0, score:0 };
+    food(s); return s;
+  }
+  function food(s) {
+    const free = [];
+    for(let y=0;y<24;y++) for(let x=0;x<18;x++)
+      if(!s.body.some(p => p.x===x && p.y===y)) free.push({x,y});
+    s.food = free[Math.floor(Math.random()*free.length)] || null;
+  }
+  function turn(control) {
+    const dirs = {left:{x:-1,y:0},right:{x:1,y:0},up:{x:0,y:-1},down:{x:0,y:1}};
+    const next = dirs[control], previous = state.queue.at(-1) || state.dir;
+    if (!next || state.queue.length >= 2 || (next.x===previous.x && next.y===previous.y) || (next.x===-previous.x && next.y===-previous.y)) return;
+    state.queue.push(next);
+  }
+  function stepSnake(dt) {
+    const s=state; s.elapsed+=dt;
+    const interval=Math.max(.065,.17-s.score*.003);
+    if(s.elapsed<interval) return;
+    s.elapsed-=interval;
+    if(s.queue.length) s.dir=s.queue.shift();
+    const head={x:s.body[0].x+s.dir.x,y:s.body[0].y+s.dir.y};
+    const eating=s.food && head.x===s.food.x && head.y===s.food.y;
+    const occupied=eating?s.body:s.body.slice(0,-1);
+    if(head.x<0||head.x>=18||head.y<0||head.y>=24||occupied.some(p=>p.x===head.x&&p.y===head.y)) return end('Игра окончена.');
+    s.body.unshift(head);
+    if(eating) { s.score++; food(s); if(!s.food) end('Всё поле заполнено. Победа!'); }
+    else s.body.pop();
+  }
+  // World Y grows downward; upward progress moves the camera, never the physics.
+  function newJump() {
+    const s={player:{x:170,y:390,vy:-520}, platforms:[{x:135,y:430,w:90,type:'solid',item:null}], enemies:[], shots:[], debris:[], time:0, camera:0, top:430, anchor:135, score:0, boost:0, shield:0, cooldown:0, generated:0};
+    generate(s); return s;
+  }
+  // Difficulty rises over 600 points, then stays within normal jump reach.
+  function difficulty(score) { return clamp(score / 600, 0, 1); }
+  function generate(s) {
+    const d = difficulty(s.score);
+    while(s.top>s.camera-110) {
+      s.top-=random(50+24*d,68+18*d); s.generated++;
+      s.anchor=clamp(s.anchor+random(-60-10*d,60+10*d),12,W-88);
+      const roll=Math.random();
+      // Permanent landing in every row keeps the main route reachable.
+      const platform={x:s.anchor,y:s.top,w:86-30*d,type:'solid',item:null};
+      if(s.generated>5 && roll<.12+.48*d) { platform.type='moving'; platform.base=platform.x; platform.phase=random(0,6); platform.speed=1+1.3*d; }
+      if(s.generated%8===0) platform.item=['spring','jet','shield'][Math.floor(Math.random()*3)];
+      s.platforms.push(platform);
+      if(s.generated>5 && Math.random()<.25+.4*d) s.platforms.push({x:clamp(s.anchor+(s.anchor<180?130:-130),0,300),y:s.top+25,w:56-10*d,type:Math.random()<.5?'break':'vanish',item:null});
+      const enemyInterval = Math.max(3,8-Math.floor(d*5));
+      if(s.generated>14 && s.generated%enemyInterval===0) s.enemies.push({x:s.anchor<180?280:55,y:s.top-30,base:s.anchor<180?280:55,phase:random(0,6),r:16,speed:1.5+2*d,range:18+20*d});
+    }
+  }
+  function stepJump(dt) {
+    const s=state,p=s.player;
+    s.time += dt;
+    s.debris.forEach(d => { d.life -= dt; d.x += d.vx*dt; d.y += d.vy*dt; d.vy += d.gravity*dt; d.angle += d.spin*dt; });
+    s.debris = s.debris.filter(d => d.life > 0);
+    s.boost=Math.max(0,s.boost-dt); s.shield=Math.max(0,s.shield-dt); s.cooldown-=dt;
+    const speed=240;
+    p.x+=((pressed('right')?1:0)-(pressed('left')?1:0))*speed*dt;
+    if(p.x>W) p.x=-24; if(p.x<-24) p.x=W;
+    const oldBottom=p.y+30;
+    p.vy=s.boost>0?-640:p.vy+1450*dt;
+    p.y+=p.vy*dt;
+    s.platforms.forEach(a => {
+      if(a.type==='moving') { a.phase+=dt*(a.speed||1); a.x=clamp(a.base+Math.sin(a.phase)*22,0,W-a.w); }
+    });
+    if(p.vy>0) {
+      const landing=s.platforms.filter(a=>!a.dead&&oldBottom<=a.y&&p.y+30>=a.y&&p.x+24>a.x&&p.x<a.x+a.w).sort((a,b)=>a.y-b.y)[0];
+      if(landing) {
+        if(landing.type==='break') shatter(landing);
+        else {
+          p.y=landing.y-30; p.vy=-520;
+          if(landing.type==='vanish') shatter(landing);
+          if(landing.item==='spring') p.vy=-850;
+          if(landing.item==='jet') s.boost=2.5;
+          if(landing.item==='shield') s.shield=7;
+          if(landing.item!=='spring') landing.item=null;
+        }
+      }
+    }
+    if(pressed('shoot')&&s.cooldown<=0) { s.shots.push({x:p.x+12,y:p.y}); s.cooldown=.2; }
+    s.shots.forEach(b=>b.y-=750*dt);
+    s.enemies.forEach(e=>{
+      e.phase+=dt*(e.speed||2); e.x=e.base+Math.sin(e.phase)*(e.range||22);
+      s.shots.forEach(b=>{ if(!b.dead&&!e.dead&&Math.hypot(b.x-e.x,b.y-e.y)<e.r+6) {e.dead=true;b.dead=true;} });
+      if(!e.dead&&p.x+24>e.x-e.r&&p.x<e.x+e.r&&p.y+30>e.y-e.r&&p.y<e.y+e.r) {
+        if(s.shield>0||s.boost>0) e.dead=true;
+        else if(p.vy>0&&oldBottom<=e.y) {e.dead=true;p.vy=-520;}
+        else end('Столкновение с охранным дроном.');
+      }
+    });
+    s.camera=Math.min(s.camera,p.y-H*.42);
+    s.score=Math.max(s.score,Math.floor(-s.camera/10));
+    s.platforms=s.platforms.filter(a=>!a.dead&&a.y<s.camera+H+70);
+    s.enemies=s.enemies.filter(e=>!e.dead&&e.y<s.camera+H+60);
+    s.shots=s.shots.filter(b=>!b.dead&&b.y>s.camera-30);
+    generate(s);
+    if(p.y>s.camera+H+30) end('Падение. Попробуйте ещё раз!');
+  }
+  function shatter(platform) {
+    if(platform.dead) return;
+    platform.dead=true;
+    const ghost=platform.type==='vanish';
+    for(let i=0;i<8;i++) {
+      state.debris.push({
+        x:platform.x+(i+.5)*platform.w/8,y:platform.y+5,
+        w:platform.w/8-1,h:ghost?5:10,
+        vx:(i-3.5)*random(12,24),vy:ghost?random(-65,-15):random(-120,-45),
+        gravity:ghost?30:550,angle:0,spin:random(-5,5),
+        life:ghost?.65:1.1,color:ghost?'#b2e9ea':'#bd8151',
+        highlight:ghost?'#ffffff':'#f5c68a'
+      });
+    }
+  }
+  function rounded(x,y,w,h,r,color) {
+    ctx.fillStyle=color; ctx.beginPath(); ctx.roundRect(x,y,w,h,r); ctx.fill();
+  }
+  function drawOperator(x,y,vy,cooldown) {
+    // Outlined suit, helmet visor and boots retain the 24 × 30 collision silhouette.
+    ctx.save(); ctx.translate(x+12,y+15);
+    ctx.rotate(clamp(((pressed('right')?1:0)-(pressed('left')?1:0))*.09,-.09,.09));
+    rounded(-12,-3,24,18,5,'#15262a');
+    rounded(-10,-2,20,15,4,'#e6d5a5');
+    rounded(-14,0,5,10,2,'#789a83'); rounded(9,0,5,10,2,'#789a83');
+    rounded(-9,10,7,5,2,'#405a5f'); rounded(2,10,7,5,2,'#405a5f');
+    rounded(-12,-16,24,20,8,'#15262a');
+    rounded(-10,-15,20,18,7,'#f2e7c9');
+    rounded(-8,-12,16,11,4,'#255769');
+    rounded(-6,-11,12,4,2,'#67bbcd');
+    rect(-5,-10,4,2,'#d9faff');
+    rounded(-6,4,12,6,2,'#526c64');
+    circle(-3,7,1.3,'#c9ff6b'); circle(2,7,1.3,'#ffa967');
+    rect(-1,-18,3,5,'#b8cbd1');
+    if(cooldown>.14) { circle(.5,-20,4,'#ffe98a'); circle(.5,-20,2,'#fffbea'); }
+    ctx.restore();
+  }
+  function drawDrone(x,y,time) {
+    ctx.save(); ctx.translate(x,y);
+    // Wide rotor arms, armoured shell and one red sensor distinguish enemies.
+    rect(-25,-6,50,4,'#738395');
+    [-23,23].forEach(dx=>{
+      rect(dx-2,-12,4,10,'#a0b0b9');
+      const span=8+Math.sin(time*50)*4;
+      rounded(dx-span,-13,span*2,3,1,'#c1d6df');
+    });
+    rounded(-17,-12,34,26,9,'#18222f');
+    rounded(-15,-10,30,22,8,'#718496');
+    rounded(-12,-9,24,6,3,'#afbec8');
+    rounded(-12,-3,24,11,5,'#293345');
+    circle(0,2,7,'#752a46'); circle(0,2,4.5,'#ff526e'); circle(-1,0,1.7,'#ffe4d1');
+    rect(-10,11,5,4,'#344959'); rect(5,11,5,4,'#344959');
+    rect(-11,-5,3,2,'#ffcb77'); rect(8,-5,3,2,'#ffcb77');
+    ctx.restore();
+  }
+  function rect(x,y,w,h,color) {ctx.fillStyle=color;ctx.fillRect(x,y,w,h);}
+  function circle(x,y,r,color) {ctx.fillStyle=color;ctx.beginPath();ctx.arc(x,y,r,0,Math.PI*2);ctx.fill();}
+  function draw() {
+    rect(0,0,W,H,'#0d191c');
+    ctx.strokeStyle='#1a3033';ctx.lineWidth=1;
+    const grid = mode === 'snake' ? 20 : 24;
+    const offset=mode==='jump'?((-state.camera)%grid):0;
+    for(let x=0;x<W;x+=grid){ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,H);ctx.stroke();}
+    for(let y=offset;y<H;y+=grid){ctx.beginPath();ctx.moveTo(0,y);ctx.lineTo(W,y);ctx.stroke();}
+    if(mode==='snake') drawSnake(); else drawJump();
+    if(paused||over) {
+      rect(0,0,W,H,'rgba(4,10,12,.72)');
+      ctx.fillStyle='#dfffbd';ctx.font='bold 24px monospace';ctx.textAlign='center';
+      ctx.fillText(paused?'ПАУЗА':'КОНЕЦ ИГРЫ',W/2,H/2-10);
+      ctx.font='14px monospace';ctx.fillText('Счёт: '+state.score,W/2,H/2+22);ctx.textAlign='left';
+    }
+  }
+  function drawSnake() {
+    const s=state;
+    if(s.food) {circle(s.food.x*20+10,s.food.y*20+10,7,'#ff965e');}
+    s.body.forEach((p,i)=>rect(p.x*20+1,p.y*20+1,18,18,i===0?'#dfff91':'#77b86c'));
+    const h=s.body[0];rect(h.x*20+5,h.y*20+5,3,3,'#13201c');rect(h.x*20+12,h.y*20+5,3,3,'#13201c');
+  }
+  function drawJump() {
+    const s=state,p=s.player,cy=s.camera;
+    s.platforms.forEach(a=>{
+      const y=a.y-cy;
+      rect(a.x,y,a.w,9,({solid:'#9ce578',moving:'#65c5e6',break:'#c68d62',vanish:'#e0e9df'})[a.type]);
+      rect(a.x+3,y+9,a.w-6,3,'#38524c');
+      if(a.type==='break') {ctx.strokeStyle='#302522';ctx.beginPath();ctx.moveTo(a.x+20,y);ctx.lineTo(a.x+29,y+5);ctx.lineTo(a.x+22,y+9);ctx.stroke();}
+      if(a.item) {rect(a.x+a.w/2-9,y-20,18,18,a.item==='spring'?'#ffe38a':a.item==='jet'?'#ff986e':'#8cdeed');ctx.fillStyle='#152322';ctx.font='bold 14px monospace';ctx.fillText(({spring:'↑',jet:'J',shield:'S'})[a.item],a.x+a.w/2-4,y-6);}
+    });
+    s.debris.forEach(d => {
+      ctx.save(); ctx.globalAlpha = Math.min(1,d.life/.35);
+      ctx.translate(d.x,d.y-cy); ctx.rotate(d.angle);
+      rect(-d.w/2,-d.h/2,d.w,d.h,d.color);
+      rect(-d.w/2,-d.h/2,d.w,2,d.highlight);
+      ctx.restore();
+    });
+    s.enemies.forEach(e=>drawDrone(e.x,e.y-cy,s.time));
+    s.shots.forEach(b=>rect(b.x-2,b.y-cy,4,12,'#fff2a1'));
+    const y=p.y-cy;
+    if(s.shield>0){ctx.strokeStyle='#8cdeed';ctx.lineWidth=2;ctx.beginPath();ctx.arc(p.x+12,y+15,25,0,Math.PI*2);ctx.stroke();}
+    if(s.boost>0){rect(p.x+5,y+28,14,18+Math.sin(performance.now()/50)*5,'#ff965e');}
+    drawOperator(p.x,y,p.vy,s.cooldown);
+    ctx.fillStyle='#95b5aa';ctx.font='11px monospace';
+    if(s.boost>0)ctx.fillText('РАНЕЦ '+s.boost.toFixed(1),10,20);
+    else if(s.shield>0)ctx.fillText('ЩИТ '+Math.ceil(s.shield),10,20);
+  }
+})();

Разница между файлами не показана из-за своего большого размера
+ 49 - 0
js/flight.js


+ 93 - 0
js/weather.js

@@ -0,0 +1,93 @@
+(() => {
+  const modal = document.querySelector('#weatherModal');
+  const status = document.querySelector('#weatherStatus');
+  const content = document.querySelector('#weatherContent');
+  const refresh = document.querySelector('#weatherRefresh');
+  let loadedAt = 0;
+  let pending = false;
+  const url = 'https://api.open-meteo.com/v1/forecast?' + new URLSearchParams({
+    latitude: '54.2093', longitude: '79.7477',
+    current: 'temperature_2m,apparent_temperature,is_day,precipitation,weather_code',
+    daily: 'temperature_2m_max,temperature_2m_min,weather_code,sunrise,sunset',
+    forecast_days: '3', timezone: 'Europe/Moscow'
+  });
+  const degrees = value => Number.isFinite(value) ? Math.round(value) + '°' : '—';
+  function sky(code, day = 1) {
+    if (code === 0) return [day ? '☀' : '☾', 'Ясно'];
+    if ([1, 2].includes(code)) return ['⛅', 'Переменная облачность'];
+    if (code === 3) return ['☁', 'Пасмурно'];
+    if ([45, 48].includes(code)) return ['≋', 'Туман'];
+    if ([51, 53, 55, 56, 57].includes(code)) return ['☂', 'Морось'];
+    if ([61, 63, 65, 66, 67, 80, 81, 82].includes(code)) return ['☂', 'Дождь'];
+    if ([71, 73, 75, 77, 85, 86].includes(code)) return ['❄', 'Снег'];
+    if ([95, 96, 99].includes(code)) return ['ϟ', 'Гроза'];
+    return ['◇', 'Нет данных'];
+  }
+  function clock(value) { return typeof value === 'string' && value.includes('T') ? value.split('T')[1].slice(0, 5) : '—'; }
+  function render(data) {
+    const current = data.current;
+    const daily = data.daily;
+    if (!current || !Number.isFinite(current.temperature_2m) || !daily || !Array.isArray(daily.time)) throw new Error('Incomplete forecast');
+    const [icon, label] = sky(current.weather_code, current.is_day);
+    const card = document.createElement('div');
+    card.className = 'weather-current';
+    const symbol = document.createElement('span');
+    symbol.className = 'weather-icon';
+    symbol.textContent = icon;
+    symbol.setAttribute('aria-hidden', 'true');
+    const summary = document.createElement('div');
+    const temperature = document.createElement('strong');
+    temperature.textContent = degrees(current.temperature_2m);
+    const description = document.createElement('p');
+    description.textContent = label + ' · ощущается как ' + degrees(current.apparent_temperature);
+    summary.append(temperature, description);
+    card.append(symbol, summary);
+    const details = document.createElement('p');
+    details.className = 'weather-details';
+    details.textContent = 'Осадки: ' + (Number.isFinite(current.precipitation) ? current.precipitation + ' мм' : '—') + ' · Восход ' + clock(daily.sunrise?.[0]) + ' · Закат ' + clock(daily.sunset?.[0]);
+    const forecast = document.createElement('div');
+    forecast.className = 'weather-forecast';
+    daily.time.slice(0, 3).forEach((date, index) => {
+      const day = document.createElement('div');
+      const title = document.createElement('span');
+      title.textContent = index === 0 ? 'Сегодня' : index === 1 ? 'Завтра' : new Date(date + 'T12:00:00Z').toLocaleDateString('ru-RU', { day: 'numeric', month: 'short', timeZone: 'UTC' });
+      const weather = document.createElement('span');
+      const [symbol, label] = sky(daily.weather_code?.[index]);
+      weather.textContent = symbol;
+      weather.setAttribute('aria-label', label);
+      weather.title = label;
+      const range = document.createElement('strong');
+      range.textContent = degrees(daily.temperature_2m_max?.[index]) + ' / ' + degrees(daily.temperature_2m_min?.[index]);
+      day.append(title, weather, range);
+      forecast.append(day);
+    });
+    content.replaceChildren(card, details, forecast);
+    content.hidden = false;
+    status.textContent = 'Данные на ' + clock(current.time) + ' МСК';
+  }
+  async function load(force = false) {
+    if (pending || (!force && Date.now() - loadedAt < 600000)) return;
+    pending = true;
+    refresh.disabled = true;
+    status.textContent = 'Загрузка прогноза…';
+    const controller = new AbortController();
+    const timeout = setTimeout(() => controller.abort(), 12000);
+    try {
+      const response = await fetch(url, { signal: controller.signal });
+      if (!response.ok) throw new Error('Weather unavailable');
+      render(await response.json());
+      loadedAt = Date.now();
+    } catch {
+      status.textContent = loadedAt ? 'Не удалось обновить. Показан предыдущий прогноз — попробуйте ещё раз.' : 'Погода сейчас недоступна. Проверьте интернет и нажмите «Обновить».';
+    } finally {
+      clearTimeout(timeout);
+      pending = false;
+      refresh.disabled = false;
+    }
+  }
+  document.querySelector('#weatherButton').addEventListener('click', () => {
+    modal.showModal();
+    load();
+  });
+  refresh.addEventListener('click', () => load(true));
+})();

Некоторые файлы не были показаны из-за большого количества измененных файлов