'use strict'; /* ═══════════════════════════════════════════════════════════════ RLE-художник — интерактив для 11 класса ═══════════════════════════════════════════════════════════════ */ (function () { const SIZE = 16; const TOTAL = SIZE * SIZE; // Холст: массив 256 (0 — белый, 1 — синий) const pixels = new Uint8Array(TOTAL); // Режим кисти let mode = 'brush'; // 'brush' | 'eraser' let isDrawing = false; let drawValue = 1; // ── Ссылки на DOM ───────────────────────────────────────── function q(id) { return document.getElementById(id); } // ── Отрисовка холста ────────────────────────────────────── function buildCanvas() { const c = q('rleCanvas'); if (!c) return; c.innerHTML = ''; for (let i = 0; i < TOTAL; i++) { const px = document.createElement('div'); px.className = 'rle-px'; px.dataset.i = i; c.appendChild(px); } } function paintCell(i, value) { if (i < 0 || i >= TOTAL) return; if (pixels[i] === value) return; pixels[i] = value; const el = q('rleCanvas').children[i]; if (el) el.classList.toggle('rle-on', value === 1); } function repaintAll() { const c = q('rleCanvas'); for (let i = 0; i < TOTAL; i++) { c.children[i].classList.toggle('rle-on', pixels[i] === 1); } } // ── RLE-кодирование ─────────────────────────────────────── // Возвращает массив строк: для каждой строки холста — { runs: [{n, color}], size } function rleEncode() { const lines = []; for (let y = 0; y < SIZE; y++) { const runs = []; let prev = pixels[y * SIZE]; let count = 1; for (let x = 1; x < SIZE; x++) { const cur = pixels[y * SIZE + x]; if (cur === prev) { count++; } else { runs.push({ n: count, color: prev }); prev = cur; count = 1; } } runs.push({ n: count, color: prev }); lines.push(runs); } return lines; } // ── Обновление статистики и вывода ──────────────────────── function update() { // Счётчики let onCount = 0; for (let i = 0; i < TOTAL; i++) if (pixels[i]) onCount++; q('rlePixelCount').textContent = onCount; // RLE const lines = rleEncode(); let totalRuns = 0; for (const runs of lines) totalRuns += runs.length; q('rleRuns').textContent = totalRuns; q('rleCompressed').textContent = totalRuns; q('rleCompressedSub').textContent = totalRuns === 1 ? 'байт (1 байт на серию)' : 'байт (' + totalRuns + ' серий × 1 байт)'; // Коэффициент const raw = 32; // 32 байта const ratio = totalRuns === 0 ? 0 : raw / totalRuns; const coefBox = q('rleStatCoef'); const coefVal = q('rleCoefficient'); const coefSub = q('rleCoefficientSub'); coefBox.classList.remove('hi', 'bad'); if (totalRuns === 0) { coefVal.textContent = '—'; coefSub.textContent = 'сжатие'; } else if (totalRuns < raw) { coefBox.classList.add('hi'); coefVal.textContent = ratio.toFixed(1) + '×'; coefSub.textContent = 'меньше сырого размера'; } else if (totalRuns === raw) { coefVal.textContent = '1.0×'; coefSub.textContent = 'без изменений'; } else { coefBox.classList.add('bad'); coefVal.textContent = (totalRuns / raw).toFixed(1) + '×'; coefSub.textContent = 'RLE увеличил файл!'; } // Вывод построчно renderLines(lines, totalRuns); } function renderLines(lines, totalRuns) { const wrap = q('rleLines'); const summary = q('rleLinesTotal'); wrap.innerHTML = ''; summary.textContent = 'серий: ' + totalRuns; for (let y = 0; y < SIZE; y++) { const runs = lines[y]; const row = document.createElement('div'); row.className = 'rle-line'; const num = document.createElement('div'); num.className = 'rle-line-num'; num.textContent = 'R' + String(y + 1).padStart(2, '0'); const content = document.createElement('div'); // Текст серий: 5B 3W 8B... const parts = runs.map(r => { const cls = r.color === 1 ? 'blk' : 'wht'; return '' + r.n + '' + (r.color === 1 ? 'B' : 'W') + ''; }); const text = document.createElement('div'); text.className = 'rle-line-content'; text.innerHTML = parts.join(' '); // Визуальная полоса серий const bar = document.createElement('div'); bar.className = 'rle-bar'; for (const r of runs) { const seg = document.createElement('div'); seg.className = 'seg'; seg.style.flex = r.n + ' 1 0'; seg.style.background = r.color === 1 ? 'linear-gradient(90deg, #4d8ef7, #6aa9ff)' : 'linear-gradient(90deg, #2a2f3d, #3a4051)'; bar.appendChild(seg); } content.appendChild(text); content.appendChild(bar); row.appendChild(num); row.appendChild(content); wrap.appendChild(row); } } // ── Рисование мышью / тачем ─────────────────────────────── function setMode(m) { mode = m; q('rleModeLabel').textContent = m === 'brush' ? 'Кисть' : 'Ластик'; q('rleModeBrush').classList.toggle('active', m === 'brush'); q('rleModeEraser').classList.toggle('active', m === 'eraser'); } function startDraw(i) { isDrawing = true; drawValue = (mode === 'brush') ? 1 : 0; paintCell(i, drawValue); update(); } function continueDraw(i) { if (!isDrawing) return; paintCell(i, drawValue); update(); } function stopDraw() { isDrawing = false; } // ── Заготовки ───────────────────────────────────────────── function clearAll() { pixels.fill(0); repaintAll(); update(); } function fillAll() { pixels.fill(1); repaintAll(); update(); } function invertAll() { for (let i = 0; i < TOTAL; i++) pixels[i] = pixels[i] ? 0 : 1; repaintAll(); update(); } // Паттерны: половина, шахматка, диагональ, шум const PRESETS = { empty: () => { pixels.fill(0); }, solid: () => { pixels.fill(1); }, half: () => { for (let y = 0; y < SIZE; y++) for (let x = 0; x < SIZE; x++) pixels[y * SIZE + x] = y < SIZE / 2 ? 1 : 0; }, stripes: () => { for (let y = 0; y < SIZE; y++) for (let x = 0; x < SIZE; x++) pixels[y * SIZE + x] = (y % 2 === 0) ? 1 : 0; }, checker: () => { for (let y = 0; y < SIZE; y++) for (let x = 0; x < SIZE; x++) pixels[y * SIZE + x] = ((x + y) % 2 === 0) ? 1 : 0; }, diagonal: () => { for (let y = 0; y < SIZE; y++) for (let x = 0; x < SIZE; x++) pixels[y * SIZE + x] = (y === x) ? 1 : 0; }, noise: () => { for (let i = 0; i < TOTAL; i++) pixels[i] = Math.random() < 0.5 ? 1 : 0; }, }; function applyPreset(name) { if (PRESETS[name]) { PRESETS[name](); repaintAll(); update(); } } // Случайная картинка: случайный выбор одного из «живописных» пресетов function randomArt() { const choices = ['half', 'stripes', 'checker', 'diagonal', 'noise']; const pick = choices[Math.floor(Math.random() * choices.length)]; applyPreset(pick); } // ── Делегирование событий ───────────────────────────────── document.addEventListener('mousedown', function (e) { const px = e.target.closest && e.target.closest('.rle-px'); if (!px) return; e.preventDefault(); startDraw(parseInt(px.dataset.i, 10)); }); document.addEventListener('mouseover', function (e) { if (!isDrawing) return; const px = e.target.closest && e.target.closest('.rle-px'); if (!px) return; continueDraw(parseInt(px.dataset.i, 10)); }); document.addEventListener('mouseup', stopDraw); // Тач document.addEventListener('touchstart', function (e) { const t = e.touches[0]; if (!t) return; const el = document.elementFromPoint(t.clientX, t.clientY); const px = el && el.closest && el.closest('.rle-px'); if (!px) return; e.preventDefault(); startDraw(parseInt(px.dataset.i, 10)); }, { passive: false }); document.addEventListener('touchmove', function (e) { if (!isDrawing) return; const t = e.touches[0]; if (!t) return; const el = document.elementFromPoint(t.clientX, t.clientY); const px = el && el.closest && el.closest('.rle-px'); if (!px) return; e.preventDefault(); continueDraw(parseInt(px.dataset.i, 10)); }, { passive: false }); document.addEventListener('touchend', stopDraw); // ── Делегирование кликов по кнопкам ─────────────────────── document.addEventListener('click', function (e) { if (!e.target || !e.target.closest) return; if (e.target.closest('#rleModeBrush')) { setMode('brush'); return; } if (e.target.closest('#rleModeEraser')) { setMode('eraser'); return; } if (e.target.closest('#rleClear')) { clearAll(); return; } if (e.target.closest('#rleFill')) { fillAll(); return; } if (e.target.closest('#rleInvert')) { invertAll(); return; } if (e.target.closest('#rleRandom')) { randomArt(); return; } }); // ── Инициализация ───────────────────────────────────────── function init() { if (!q('rleCanvas')) return; buildCanvas(); setMode('brush'); // Стартовая картинка — «диагональ», чтобы сразу было что смотреть applyPreset('diagonal'); update(); if (window.console && console.debug) { console.debug('[rle-artist] скрипт загружен'); } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();