|
|
@@ -0,0 +1,507 @@
|
|
|
+document.documentElement.classList.replace('no-js', 'js');
|
|
|
+
|
|
|
+/* ===================== УТИЛИТЫ ===================== */
|
|
|
+const $ = (s, r = document) => r.querySelector(s);
|
|
|
+const $$ = (s, r = document) => [...r.querySelectorAll(s)];
|
|
|
+const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
|
|
+const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
|
+const setTxt = (el, t) => { if (el.textContent !== t) el.textContent = t; };
|
|
|
+const fmtCm = v => String(v).replace('.', ',') + ' см';
|
|
|
+
|
|
|
+/* Палитра «печатного листа» */
|
|
|
+const INK = '#2b2118', RED = '#b0161a', PAPER = '#f6ecd0', WALL = '#d7bd7c', SOFT = '#6a5a3e', SOIL = '#e6d49c';
|
|
|
+
|
|
|
+/* Единый цикл анимации */
|
|
|
+const loops = new Map();
|
|
|
+let lastTs = performance.now();
|
|
|
+function frame(ts) {
|
|
|
+ const dt = Math.min((ts - lastTs) / 1000, .05);
|
|
|
+ lastTs = ts;
|
|
|
+ loops.forEach(fn => fn(dt));
|
|
|
+ requestAnimationFrame(frame);
|
|
|
+}
|
|
|
+requestAnimationFrame(frame);
|
|
|
+const addLoop = (name, fn) => loops.set(name, fn);
|
|
|
+
|
|
|
+/* Холст с учётом плотности пикселей */
|
|
|
+function setupCanvas(canvas) {
|
|
|
+ const c = { canvas, ctx: canvas.getContext('2d'), w: 0, h: 0 };
|
|
|
+ c.resize = () => {
|
|
|
+ const r = canvas.getBoundingClientRect();
|
|
|
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
|
|
|
+ canvas.width = Math.max(1, Math.round(r.width * dpr));
|
|
|
+ canvas.height = Math.max(1, Math.round(r.height * dpr));
|
|
|
+ c.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
|
+ c.w = r.width; c.h = r.height;
|
|
|
+ };
|
|
|
+ c.resize();
|
|
|
+ if ('ResizeObserver' in window) new ResizeObserver(c.resize).observe(canvas);
|
|
|
+ else window.addEventListener('resize', c.resize);
|
|
|
+ return c;
|
|
|
+}
|
|
|
+function say(ctx, s, x, y, color, sz = 10, align = 'left', bold = false) {
|
|
|
+ ctx.fillStyle = color;
|
|
|
+ ctx.font = `${bold ? '700 ' : ''}${sz}px "PT Serif", Georgia, serif`;
|
|
|
+ ctx.textAlign = align; ctx.textBaseline = 'middle';
|
|
|
+ ctx.fillText(s, x, y);
|
|
|
+}
|
|
|
+
|
|
|
+/* Аудио: один контекст на страницу, создаётся только после действия пользователя */
|
|
|
+let AC = null;
|
|
|
+function getAC() {
|
|
|
+ if (!AC) AC = new (window.AudioContext || window.webkitAudioContext)();
|
|
|
+ if (AC.state === 'suspended') AC.resume();
|
|
|
+ return AC;
|
|
|
+}
|
|
|
+
|
|
|
+/* Материалы: k — доля сигнала относительно стали (ферромагнетик).
|
|
|
+ У каждого металла свой «голос»: форма волны, тон и ритм. */
|
|
|
+const METALS = {
|
|
|
+ steel: { name: 'сталь', k: 1, wave: 'square', f: [180], dur: .16, col: '#4b4a46' },
|
|
|
+ alu: { name: 'алюминий', k: .55, wave: 'sine', f: [1100], dur: .08, col: '#9fb0b5' },
|
|
|
+ copper: { name: 'медь', k: .7, wave: 'triangle', f: [700], dur: .12, col: '#b06a3a',
|
|
|
+ note: 'Немагнитная, хорошо проводит ток: сигнал средний. Звук мягкий, как колокольчик.' },
|
|
|
+ brass: { name: 'латунь', k: .6, wave: 'sawtooth', f: [520], dur: .12, col: '#b8963a',
|
|
|
+ note: 'Сплав меди и цинка: сигнал средний. Звук резкий, «жужжащий».' },
|
|
|
+ gold: { name: 'золото', k: .6, wave: 'sine', f: [1400, 1800], dur: .1, col: '#c9a227',
|
|
|
+ note: 'Блестит, но прибор не различает ценность: сигнал такой же, как у латуни. Звук из двух нот.' }
|
|
|
+};
|
|
|
+METALS.steel.note = 'Ферромагнетик: даёт самый сильный сигнал. Звучит низким двойным гудком.';
|
|
|
+METALS.alu.note = 'Немагнитный, но проводит ток: сигнал заметно слабее. Звук короткий и высокий.';
|
|
|
+
|
|
|
+/* Звук металла: форма и тон зависят от материала, громкость от силы сигнала */
|
|
|
+function playMetal(key, level = 1) {
|
|
|
+ const m = METALS[key];
|
|
|
+ if (!m) return;
|
|
|
+ try {
|
|
|
+ const ac = getAC(), t0 = ac.currentTime;
|
|
|
+ m.f.forEach((f, i) => {
|
|
|
+ const o = ac.createOscillator(), g = ac.createGain();
|
|
|
+ const a = t0 + i * m.dur, b = a + m.dur;
|
|
|
+ o.type = m.wave; o.frequency.value = f;
|
|
|
+ g.gain.setValueAtTime(.0001, a);
|
|
|
+ g.gain.exponentialRampToValueAtTime(.02 + .08 * clamp(level, 0, 1), a + .01);
|
|
|
+ g.gain.exponentialRampToValueAtTime(.0001, b);
|
|
|
+ o.connect(g); g.connect(ac.destination);
|
|
|
+ o.start(a); o.stop(b + .02);
|
|
|
+ });
|
|
|
+ } catch (e) { /* звук недоступен: прибор работает без него */ }
|
|
|
+}
|
|
|
+
|
|
|
+/* ===================== НАВИГАЦИЯ И ПОЯВЛЕНИЕ ===================== */
|
|
|
+const progressEl = $('#progress');
|
|
|
+const onScroll = () => {
|
|
|
+ const max = document.documentElement.scrollHeight - innerHeight;
|
|
|
+ progressEl.style.transform = `scaleX(${max > 0 ? scrollY / max : 0})`;
|
|
|
+};
|
|
|
+addEventListener('scroll', onScroll, { passive: true });
|
|
|
+onScroll();
|
|
|
+
|
|
|
+const revealIO = new IntersectionObserver(entries => entries.forEach(e => {
|
|
|
+ if (e.isIntersecting) { e.target.classList.add('in'); revealIO.unobserve(e.target); }
|
|
|
+}), { threshold: .08 });
|
|
|
+$$('.reveal').forEach(el => revealIO.observe(el));
|
|
|
+
|
|
|
+/* ===================== ЖУРНАЛ СРАБАТЫВАНИЙ ===================== */
|
|
|
+const jList = $('#jList');
|
|
|
+const jPlace = $('#jPlace');
|
|
|
+
|
|
|
+function jEmpty() {
|
|
|
+ jList.innerHTML = '<li class="jempty">Записей пока нет.</li>';
|
|
|
+}
|
|
|
+function jLog(place, status) {
|
|
|
+ const empty = $('.jempty', jList);
|
|
|
+ if (empty) empty.remove();
|
|
|
+ const t = new Date().toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
|
|
+ const li = document.createElement('li');
|
|
|
+ li.innerHTML = `<span class="jt">${t}</span><span class="jp">${esc(place || 'место не указано')}</span><span class="js">${esc(status)}</span>`;
|
|
|
+ jList.appendChild(li);
|
|
|
+ jList.scrollTop = jList.scrollHeight; // прокручиваем только сам список, не страницу
|
|
|
+}
|
|
|
+function jAdd() {
|
|
|
+ jLog(jPlace.value.trim(), 'запись вручную');
|
|
|
+ jPlace.value = '';
|
|
|
+}
|
|
|
+$('#jAdd').addEventListener('click', jAdd);
|
|
|
+$('#jClear').addEventListener('click', jEmpty);
|
|
|
+jPlace.addEventListener('keydown', e => { if (e.key === 'Enter') jAdd(); });
|
|
|
+
|
|
|
+/* ===================== РАЗДЕЛ IV. ТРЕНАЖЁР: ПОИСК КЛАДА ===================== */
|
|
|
+/*
|
|
|
+ Вид сверху. Поле 100 × 60 см. Курсор мыши = катушка ACE 300.
|
|
|
+ Колесо мыши: высота 0–5 см (шаг 0.5). Скорость: по движению курсора, см/с.
|
|
|
+ Щелчок: метка. Игра показывает, что было под катушкой.
|
|
|
+
|
|
|
+ Модель сигнала (учебная):
|
|
|
+ d — расстояние от центра катушки до предмета по поверхности (для трубы — до отрезка)
|
|
|
+ dist = √(d² + (h + глубина)²)
|
|
|
+ s = k(материал) · размер · 1/(1 + (h/2)²) · k(скорость) / (1 + (dist / 7)²)
|
|
|
+ k(скорость) = 1 до 6 см/с, далее снижается до 0.5 при 10 см/с
|
|
|
+ Порог срабатывания: 0.3
|
|
|
+*/
|
|
|
+const FIELD_W = 100, FIELD_H = 60; // поле, см
|
|
|
+const RD = 7; // масштаб дальности, см
|
|
|
+const COIL_R = 6; // радиус катушки (след прохода), см
|
|
|
+const THR = .3; // порог срабатывания
|
|
|
+const TIME_LIMIT = 180; // длительность поиска, с
|
|
|
+const IDLE_MS = 150; // без движения дольше этого скорость падает
|
|
|
+const CELL = 2; // ячейка покрытия, см
|
|
|
+
|
|
|
+const TREASURE_TOTAL = 4;
|
|
|
+const OBJS = [
|
|
|
+ { id: 'chest', label: 'сундук с монетами (клад)', kind: 'treasure', value: 20, mat: 'steel', size: 1.3, depth: 6, shape: 'box', x: 72, y: 18, w: 10, h: 6 },
|
|
|
+ { id: 'gold1', label: 'золотая монета (клад)', kind: 'treasure', value: 10, mat: 'gold', size: 1, depth: 3, shape: 'dot', x: 28, y: 12 },
|
|
|
+ { id: 'gold2', label: 'золотая монета (клад)', kind: 'treasure', value: 10, mat: 'gold', size: 1, depth: 4, shape: 'dot', x: 62, y: 6 },
|
|
|
+ { id: 'copper', label: 'медная монета (клад)', kind: 'treasure', value: 5, mat: 'copper', size: 1, depth: 4, shape: 'dot', x: 50, y: 48 },
|
|
|
+ { id: 'nail', label: 'гвоздь (мусор)', kind: 'trash', value: -5, mat: 'steel', size: .5, depth: 2, shape: 'dot', x: 12, y: 30 },
|
|
|
+ { id: 'can', label: 'банка (мусор)', kind: 'trash', value: -5, mat: 'alu', size: .8, depth: 3, shape: 'box', x: 88, y: 50, w: 5, h: 5 },
|
|
|
+ { id: 'pipe', label: 'труба (мусор)', kind: 'trash', value: -5, mat: 'steel', size: 1, depth: 6, shape: 'seg', x1: 36, y1: 34, x2: 100, y2: 34 }
|
|
|
+];
|
|
|
+
|
|
|
+const kH = h => 1 / (1 + (h / 2) ** 2);
|
|
|
+const kV = v => v <= 6 ? 1 : Math.max(.5, 1 - (v - 6) * .1);
|
|
|
+function segDist(px, py, x1, y1, x2, y2) {
|
|
|
+ const dx = x2 - x1, dy = y2 - y1;
|
|
|
+ const t = clamp(((px - x1) * dx + (py - y1) * dy) / (dx * dx + dy * dy), 0, 1);
|
|
|
+ return Math.hypot(px - (x1 + t * dx), py - (y1 + t * dy));
|
|
|
+}
|
|
|
+function objDist(o, X, Y) {
|
|
|
+ if (o.shape === 'seg') return segDist(X, Y, o.x1, o.y1, o.x2, o.y2);
|
|
|
+ return Math.hypot(X - o.x, Y - o.y);
|
|
|
+}
|
|
|
+function objSignal(o, X, Y, h, v) {
|
|
|
+ const d = objDist(o, X, Y);
|
|
|
+ const dist = Math.hypot(d, h + o.depth);
|
|
|
+ return METALS[o.mat].k * o.size * kH(h) * kV(v) / (1 + (dist / RD) ** 2);
|
|
|
+}
|
|
|
+
|
|
|
+const gmC = setupCanvas($('#cvGame'));
|
|
|
+const cvGame = gmC.canvas;
|
|
|
+const G = {
|
|
|
+ state: 'idle', // idle | play | end
|
|
|
+ left: TIME_LIMIT, score: 0, found: 0,
|
|
|
+ X: 50, Y: 30, h: 1, v: 0,
|
|
|
+ lastX: null, lastY: null, lastT: 0, lastMove: 0,
|
|
|
+ inside: false, show: false, snd: false, prevAbove: false, wAcc: 0,
|
|
|
+ marks: [], msg: 'Наведите курсор на поле, чтобы начать поиск.',
|
|
|
+ cov: new Uint8Array((FIELD_W / CELL) * (FIELD_H / CELL)), covN: 0, covPct: 0,
|
|
|
+ covCv: document.createElement('canvas'), ph: 0
|
|
|
+};
|
|
|
+G.covCv.width = FIELD_W; G.covCv.height = FIELD_H;
|
|
|
+
|
|
|
+/* Фон грунта: точки постоянные (генератор с фиксированным зерном) */
|
|
|
+const DOTS = (() => {
|
|
|
+ let s = 7;
|
|
|
+ const rnd = () => (s = (s * 16807) % 2147483647) / 2147483647;
|
|
|
+ return Array.from({ length: 260 }, () => [rnd() * FIELD_W, rnd() * FIELD_H]);
|
|
|
+})();
|
|
|
+
|
|
|
+function setH(x) {
|
|
|
+ G.h = clamp(Math.round(x * 2) / 2, 0, 5);
|
|
|
+}
|
|
|
+function startGame() {
|
|
|
+ G.state = 'play';
|
|
|
+ G.msg = 'Поиск начат. Ведите катушку медленно и перекрывайте проходы.';
|
|
|
+}
|
|
|
+function newGame() {
|
|
|
+ G.state = 'idle';
|
|
|
+ G.left = TIME_LIMIT; G.score = 0; G.found = 0;
|
|
|
+ OBJS.forEach(o => { o.found = false; });
|
|
|
+ G.marks = []; G.cov.fill(0); G.covN = 0; G.covPct = 0;
|
|
|
+ G.covCv.getContext('2d').clearRect(0, 0, FIELD_W, FIELD_H);
|
|
|
+ G.msg = 'Новая игра. Наведите курсор на поле, чтобы начать.';
|
|
|
+ G.prevAbove = false;
|
|
|
+}
|
|
|
+function endGame() {
|
|
|
+ if (G.state === 'end') return;
|
|
|
+ G.state = 'end';
|
|
|
+ const total = TREASURE_TOTAL;
|
|
|
+ G.msg = G.found === total
|
|
|
+ ? `Клад найден полностью: ${G.found} из ${total} ценностей. Очки: ${G.score}.`
|
|
|
+ : `Время вышло. Найдено ${G.found} из ${total} ценностей. Очки: ${G.score}.`;
|
|
|
+ jLog('игра «поиск клада» завершена', G.msg);
|
|
|
+}
|
|
|
+
|
|
|
+/* Метка: проверяем сигнал под катушкой и открываем, что там было */
|
|
|
+function mark() {
|
|
|
+ if (G.state === 'idle') startGame();
|
|
|
+ if (G.state === 'end') return;
|
|
|
+ const X = G.X, Y = G.Y;
|
|
|
+ let best = null, bestS = 0, known = null, knownS = 0;
|
|
|
+ for (const o of OBJS) {
|
|
|
+ const s = objSignal(o, X, Y, G.h, G.v);
|
|
|
+ if (s >= THR && !o.found && s > bestS) { best = o; bestS = s; }
|
|
|
+ if (s >= THR && s > knownS) { known = o; knownS = s; }
|
|
|
+ }
|
|
|
+ let result, sig;
|
|
|
+ if (best) {
|
|
|
+ best.found = true;
|
|
|
+ if (best.kind === 'treasure') G.found++;
|
|
|
+ G.score += best.value;
|
|
|
+ result = best.kind === 'treasure'
|
|
|
+ ? `Найдено: ${best.label}, +${best.value}.`
|
|
|
+ : `Открыто: ${best.label}, ${best.value}. Это не клад.`;
|
|
|
+ sig = bestS;
|
|
|
+ } else if (known) {
|
|
|
+ result = `Уже известно: ${known.label}. Очки не меняются.`;
|
|
|
+ sig = knownS;
|
|
|
+ } else {
|
|
|
+ G.score -= 2;
|
|
|
+ result = 'Сигнала нет, метка ложная, −2.';
|
|
|
+ sig = 0;
|
|
|
+ }
|
|
|
+ G.marks.push({ X, Y, ok: !!best });
|
|
|
+ G.msg = result;
|
|
|
+ jLog(`поиск, ${X.toFixed(0)} × ${Y.toFixed(0)} см, высота ${fmtCm(G.h)}`,
|
|
|
+ `${result} Сигнал ${sig.toFixed(2)}.`);
|
|
|
+ if (G.found >= TREASURE_TOTAL) endGame();
|
|
|
+}
|
|
|
+
|
|
|
+/* Ввод: курсор = катушка; колесо = высота; щелчок = метка */
|
|
|
+const cmAt = e => {
|
|
|
+ const r = cvGame.getBoundingClientRect();
|
|
|
+ return [clamp((e.clientX - r.left) / r.width * FIELD_W, 0, FIELD_W),
|
|
|
+ clamp((e.clientY - r.top) / r.height * FIELD_H, 0, FIELD_H)];
|
|
|
+};
|
|
|
+cvGame.addEventListener('pointermove', e => {
|
|
|
+ const [X, Y] = cmAt(e);
|
|
|
+ const now = performance.now();
|
|
|
+ if (G.lastX !== null && G.lastT) {
|
|
|
+ const dt = Math.max((now - G.lastT) / 1000, .008);
|
|
|
+ const inst = Math.min(60, Math.hypot(X - G.lastX, Y - G.lastY) / dt);
|
|
|
+ G.v = G.v * .6 + inst * .4; // сглаживание скорости, см/с
|
|
|
+ }
|
|
|
+ G.lastX = X; G.lastY = Y; G.lastT = now; G.lastMove = now;
|
|
|
+ G.X = X; G.Y = Y; G.inside = true;
|
|
|
+ if (G.state === 'idle') startGame();
|
|
|
+});
|
|
|
+cvGame.addEventListener('pointerleave', () => {
|
|
|
+ G.inside = false; G.lastX = null; G.lastT = 0; G.v = 0;
|
|
|
+});
|
|
|
+cvGame.addEventListener('wheel', e => {
|
|
|
+ e.preventDefault(); // колесо меняет высоту, а не прокручивает страницу
|
|
|
+ G.wAcc += e.deltaY;
|
|
|
+ if (Math.abs(G.wAcc) >= 60) { setH(G.h + (G.wAcc < 0 ? .5 : -.5)); G.wAcc = 0; }
|
|
|
+}, { passive: false });
|
|
|
+cvGame.addEventListener('click', e => {
|
|
|
+ const [X, Y] = cmAt(e);
|
|
|
+ G.X = X; G.Y = Y; G.inside = true; // для касания: точка берётся из щелчка
|
|
|
+ mark();
|
|
|
+});
|
|
|
+cvGame.addEventListener('keydown', e => {
|
|
|
+ if (e.key === 'ArrowUp') { e.preventDefault(); setH(G.h + .5); }
|
|
|
+ else if (e.key === 'ArrowDown') { e.preventDefault(); setH(G.h - .5); }
|
|
|
+ else if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); mark(); }
|
|
|
+});
|
|
|
+
|
|
|
+/* Покрытие: ячейки, которые прошла катушка */
|
|
|
+function markCoverage() {
|
|
|
+ const cols = FIELD_W / CELL, rows = FIELD_H / CELL;
|
|
|
+ const c = G.covCv.getContext('2d');
|
|
|
+ c.fillStyle = 'rgba(43,33,24,.2)';
|
|
|
+ for (let j = 0; j < rows; j++) for (let i = 0; i < cols; i++) {
|
|
|
+ const cx = i * CELL + CELL / 2, cy = j * CELL + CELL / 2;
|
|
|
+ if (Math.hypot(cx - G.X, cy - G.Y) <= COIL_R) {
|
|
|
+ const k = j * cols + i;
|
|
|
+ if (!G.cov[k]) { // ячейка закрашивается один раз
|
|
|
+ G.cov[k] = 1; G.covN++;
|
|
|
+ c.fillRect(i * CELL, j * CELL, CELL, CELL);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ G.covPct = Math.round(G.covN / G.cov.length * 100);
|
|
|
+}
|
|
|
+
|
|
|
+const spdClass = v => v < 1 ? 'warn' : v <= 6 ? 'ok' : v <= 10 ? 'warn' : 'bad';
|
|
|
+function spdNote(v) {
|
|
|
+ if (v < 1) return 'Слишком медленно: проверка долгая. Сигнал при этом надёжный.';
|
|
|
+ if (v <= 6) return 'Рекомендуемая зона 1–6 см/с: сигнал надёжен.';
|
|
|
+ if (v <= 10) return 'Быстро: слабые предметы могут быть пропущены.';
|
|
|
+ return 'Слишком быстро: пропуск предметов вероятен.';
|
|
|
+}
|
|
|
+
|
|
|
+/* Прорисовка поля и катушки */
|
|
|
+function drawGame(dt) {
|
|
|
+ const { ctx, w, h } = gmC;
|
|
|
+ if (!w) return;
|
|
|
+ const s = w / FIELD_W; // пикселей на сантиметр
|
|
|
+ G.ph += dt;
|
|
|
+
|
|
|
+ /* скорость и таймер */
|
|
|
+ if (performance.now() - G.lastMove > IDLE_MS) G.v *= Math.exp(-dt * 9);
|
|
|
+ if (G.state === 'play') {
|
|
|
+ G.left -= dt;
|
|
|
+ if (G.left <= 0) { G.left = 0; endGame(); }
|
|
|
+ }
|
|
|
+ if (G.inside && G.state !== 'end' && G.v > .5) markCoverage();
|
|
|
+
|
|
|
+ /* сильнейший сигнал под катушкой */
|
|
|
+ let best = 0, bestO = null;
|
|
|
+ if (G.inside) for (const o of OBJS) {
|
|
|
+ const v = objSignal(o, G.X, G.Y, G.h, G.v);
|
|
|
+ if (v > best) { best = v; bestO = o; }
|
|
|
+ }
|
|
|
+ const above = G.inside && best >= THR;
|
|
|
+ if (above && !G.prevAbove && G.snd && bestO) playMetal(bestO.mat, Math.min(1, best));
|
|
|
+ G.prevAbove = above;
|
|
|
+
|
|
|
+ /* грунт */
|
|
|
+ ctx.fillStyle = SOIL; ctx.fillRect(0, 0, w, h);
|
|
|
+ ctx.fillStyle = 'rgba(106,90,62,.35)';
|
|
|
+ for (const [dx, dy] of DOTS) { ctx.fillRect(dx * s, dy * s, 1.6, 1.6); }
|
|
|
+ ctx.strokeStyle = 'rgba(43,33,24,.1)'; ctx.lineWidth = 1;
|
|
|
+ for (let x = 10; x < FIELD_W; x += 10) { ctx.beginPath(); ctx.moveTo(x * s, 0); ctx.lineTo(x * s, h); ctx.stroke(); }
|
|
|
+ for (let y = 10; y < FIELD_H; y += 10) { ctx.beginPath(); ctx.moveTo(0, y * s); ctx.lineTo(w, y * s); ctx.stroke(); }
|
|
|
+
|
|
|
+ /* пройденная часть */
|
|
|
+ ctx.imageSmoothingEnabled = false; // ячейки покрытия видны как сетка
|
|
|
+ ctx.drawImage(G.covCv, 0, 0, w, h);
|
|
|
+ ctx.imageSmoothingEnabled = true;
|
|
|
+
|
|
|
+ /* объекты: открытые и (в режиме демонстрации) все */
|
|
|
+ for (const o of OBJS) {
|
|
|
+ if (!(o.found || G.show)) continue;
|
|
|
+ const col = METALS[o.mat].col;
|
|
|
+ const alpha = o.found ? 1 : .55;
|
|
|
+ ctx.globalAlpha = alpha;
|
|
|
+ if (o.shape === 'seg') {
|
|
|
+ ctx.strokeStyle = col; ctx.lineWidth = 3 * s; ctx.lineCap = 'round';
|
|
|
+ ctx.beginPath(); ctx.moveTo(o.x1 * s, o.y1 * s); ctx.lineTo(o.x2 * s, o.y2 * s); ctx.stroke();
|
|
|
+ ctx.lineCap = 'butt'; ctx.lineWidth = 1;
|
|
|
+ } else if (o.shape === 'box') {
|
|
|
+ ctx.fillStyle = col;
|
|
|
+ ctx.fillRect((o.x - o.w / 2) * s, (o.y - o.h / 2) * s, o.w * s, o.h * s);
|
|
|
+ } else {
|
|
|
+ ctx.fillStyle = col;
|
|
|
+ ctx.beginPath(); ctx.arc(o.x * s, o.y * s, 1.3 * s, 0, Math.PI * 2); ctx.fill();
|
|
|
+ }
|
|
|
+ ctx.globalAlpha = 1;
|
|
|
+ /* подпись на бумажной подложке, чтобы читалась на любом фоне */
|
|
|
+ const tx = clamp(o.x * s + 8, 4, w - 4), ty = clamp((o.y - 4) * s, 12, h - 12);
|
|
|
+ const txt = o.found ? o.label : 'под грунтом';
|
|
|
+ ctx.font = (o.found ? '700 ' : '') + '11px "PT Serif", Georgia, serif';
|
|
|
+ const tw = ctx.measureText(txt).width;
|
|
|
+ const lx = tx + tw + 8 > w ? tx - tw - 8 : tx;
|
|
|
+ ctx.fillStyle = 'rgba(246,236,208,.9)';
|
|
|
+ ctx.fillRect(lx - 3, ty - 9, tw + 6, 18);
|
|
|
+ say(ctx, txt, lx, ty, o.found ? (o.kind === 'treasure' ? RED : SOFT) : SOFT, 11, 'left', o.found);
|
|
|
+ }
|
|
|
+
|
|
|
+ /* метки */
|
|
|
+ ctx.strokeStyle = RED; ctx.lineWidth = 2.4;
|
|
|
+ for (const m of G.marks) {
|
|
|
+ const mx = m.X * s, my = m.Y * s, r = 3 * s;
|
|
|
+ ctx.beginPath();
|
|
|
+ ctx.moveTo(mx - r, my - r); ctx.lineTo(mx + r, my + r);
|
|
|
+ ctx.moveTo(mx + r, my - r); ctx.lineTo(mx - r, my + r);
|
|
|
+ ctx.stroke();
|
|
|
+ }
|
|
|
+ ctx.lineWidth = 1;
|
|
|
+
|
|
|
+ /* катушка */
|
|
|
+ const cx = G.X * s, cy = G.Y * s, rr = COIL_R * s;
|
|
|
+ if (G.inside) {
|
|
|
+ ctx.fillStyle = `rgba(176,22,26,${(.08 + .45 * Math.min(1, best)).toFixed(2)})`;
|
|
|
+ ctx.beginPath(); ctx.arc(cx, cy, rr, 0, Math.PI * 2); ctx.fill();
|
|
|
+ if (above) {
|
|
|
+ for (let i = 0; i < 3; i++) {
|
|
|
+ const k = ((G.ph * 1.4 + i / 3) % 1);
|
|
|
+ ctx.strokeStyle = `rgba(176,22,26,${(1 - k).toFixed(2)})`; ctx.lineWidth = 1.6;
|
|
|
+ ctx.beginPath(); ctx.arc(cx, cy, rr * (.5 + k), 0, Math.PI * 2); ctx.stroke();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ ctx.strokeStyle = INK; ctx.lineWidth = 2.2;
|
|
|
+ ctx.beginPath(); ctx.arc(cx, cy, rr, 0, Math.PI * 2); ctx.stroke();
|
|
|
+ ctx.lineWidth = 1;
|
|
|
+ ctx.fillStyle = RED; ctx.beginPath(); ctx.arc(cx, cy, 2.6, 0, Math.PI * 2); ctx.fill();
|
|
|
+ const lx = cx + rr + 6 > w - 110 ? cx - rr - 6 : cx + rr + 6;
|
|
|
+ say(ctx, 'высота ' + fmtCm(G.h), lx, clamp(cy - rr, 10, h - 10), INK, 11,
|
|
|
+ lx < cx ? 'right' : 'left', true);
|
|
|
+ } else {
|
|
|
+ ctx.setLineDash([4, 4]); ctx.strokeStyle = 'rgba(43,33,24,.45)'; ctx.lineWidth = 1.2;
|
|
|
+ ctx.beginPath(); ctx.arc(cx, cy, rr, 0, Math.PI * 2); ctx.stroke();
|
|
|
+ ctx.setLineDash([]); ctx.lineWidth = 1;
|
|
|
+ }
|
|
|
+
|
|
|
+ /* подписи краёв и состояние игры */
|
|
|
+ say(ctx, '0', 6, h - 10, INK, 11, 'left');
|
|
|
+ say(ctx, '50 см', w / 2, h - 10, INK, 11, 'center');
|
|
|
+ say(ctx, '100 см', w - 6, h - 10, INK, 11, 'right');
|
|
|
+ if (G.state === 'idle') {
|
|
|
+ ctx.fillStyle = 'rgba(246,236,208,.85)';
|
|
|
+ ctx.fillRect(w * .18, h * .4, w * .64, h * .2);
|
|
|
+ ctx.strokeStyle = INK; ctx.lineWidth = 2; ctx.strokeRect(w * .18, h * .4, w * .64, h * .2);
|
|
|
+ say(ctx, 'Наведите курсор на поле: игра начнётся', w / 2, h * .5, INK, Math.max(12, w / 50), 'center', true);
|
|
|
+ }
|
|
|
+ ctx.lineWidth = 1;
|
|
|
+
|
|
|
+ updateHud(best, above);
|
|
|
+}
|
|
|
+
|
|
|
+function updateHud(best, above) {
|
|
|
+ const v = G.v;
|
|
|
+ const cell = $('#cSpd');
|
|
|
+ cell.className = 'hud-c ' + (G.inside || G.v > .05 ? spdClass(v) : '');
|
|
|
+ setTxt($('#hSpd'), v.toFixed(1).replace('.', ',') + ' см/с');
|
|
|
+ setTxt($('#hSpdNote'), spdNote(v));
|
|
|
+ setTxt($('#hH'), fmtCm(G.h));
|
|
|
+ $('#hSigBar > i').style.width = Math.min(100, best * 100).toFixed(0) + '%';
|
|
|
+ setTxt($('#hSigVal'), G.inside ? best.toFixed(2) : '—');
|
|
|
+ const sec = Math.ceil(G.left);
|
|
|
+ setTxt($('#hTime'), `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`);
|
|
|
+ setTxt($('#hScore'), String(G.score));
|
|
|
+ setTxt($('#hFound'), `${G.found} из ${TREASURE_TOTAL}`);
|
|
|
+ setTxt($('#hCov'), G.covPct + '%');
|
|
|
+
|
|
|
+ let read;
|
|
|
+ if (G.state === 'end') read = 'Игра окончена. Нажмите «Новая игра», чтобы начать заново.';
|
|
|
+ else if (!G.inside) read = 'Курсор за пределами поля: катушка не работает.';
|
|
|
+ else if (above) read = 'Сигнал выше порога: остановите катушку и щёлкните, чтобы отметить место.';
|
|
|
+ else read = 'Сигнал ниже порога. Ведите катушку дальше, перекрывая проходы.';
|
|
|
+ if (G.inside && G.h > 3) read += ' Высота больше 3 см: слабые предметы почти не видны.';
|
|
|
+ setTxt($('#gmRead'), read);
|
|
|
+ setTxt($('#gmLast'), G.msg);
|
|
|
+ const f = $('#gmFlag');
|
|
|
+ f.classList.toggle('on', above);
|
|
|
+ setTxt(f, above ? 'СРАБАТЫВАНИЕ' : 'сигнала нет');
|
|
|
+}
|
|
|
+
|
|
|
+/* управление */
|
|
|
+$('#gmUp').addEventListener('click', () => setH(G.h + .5));
|
|
|
+$('#gmDown').addEventListener('click', () => setH(G.h - .5));
|
|
|
+$('#gmNew').addEventListener('click', newGame);
|
|
|
+$('#gmShow').addEventListener('change', e => { G.show = e.target.checked; });
|
|
|
+$('#snd').addEventListener('change', e => {
|
|
|
+ G.snd = e.target.checked;
|
|
|
+ if (G.snd) playMetal('steel', .8); // подтверждение включения звука
|
|
|
+});
|
|
|
+$$('.tone').forEach(b => b.addEventListener('click', () => playMetal(b.dataset.tone, .8)));
|
|
|
+
|
|
|
+newGame();
|
|
|
+addLoop('game', drawGame);
|
|
|
+
|
|
|
+/* ===================== ПОКАЗ ПО ШАГАМ ===================== */
|
|
|
+/* Шаги выставляют высоту и звук; подсвечивают нужный элемент */
|
|
|
+const GUIDE = [
|
|
|
+ { t: 'Поставьте катушку на высоту 1 см: прокрутите колесо мыши над полем или нажмите «Выше» / «Ниже».', hl: '#cvGame', act: () => setH(1) },
|
|
|
+ { t: 'Ведите курсор медленно: скорость должна быть в зоне 1–6 см/с, индикатор зелёный.', hl: '#cSpd' },
|
|
|
+ { t: 'Включите звуковой сигнал: тон подскажет, когда катушка над металлом.', hl: '#snd', act: () => setChk('#snd', true) },
|
|
|
+ { t: 'Проведите катушку полосами, перекрывая предыдущий проход. Заливка показывает пройденную часть.', hl: '#cvGame' },
|
|
|
+ { t: 'Когда сигнал выше порога, остановите катушку и щёлкните: игра покажет, что было в грунте, а место попадёт в журнал.', hl: '#cvGame' }
|
|
|
+];
|
|
|
+let gi = 0;
|
|
|
+function setChk(sel, v) { const el = $(sel); el.checked = v; el.dispatchEvent(new Event('change')); }
|
|
|
+function showStep(apply) {
|
|
|
+ const st = GUIDE[gi];
|
|
|
+ if (apply && st.act) st.act();
|
|
|
+ $('#gN').textContent = `Шаг ${gi + 1} из ${GUIDE.length}`;
|
|
|
+ $('#gT').textContent = st.t;
|
|
|
+ $('#gPrev').disabled = gi === 0;
|
|
|
+ $('#gNext').disabled = gi === GUIDE.length - 1;
|
|
|
+ $$('.hl').forEach(e => e.classList.remove('hl'));
|
|
|
+ $(st.hl).classList.add('hl');
|
|
|
+}
|
|
|
+$('#gPrev').addEventListener('click', () => { gi--; showStep(true); });
|
|
|
+$('#gNext').addEventListener('click', () => { gi++; showStep(true); });
|
|
|
+$('#gRestart').addEventListener('click', () => { gi = 0; showStep(true); });
|
|
|
+showStep(false); // при загрузке ничего не включаем: звук только по действию пользователя
|