/* * Sixchat Memory — игра на поиск пар для РусФФ. * Ежедневный уровень настраивается в HTML-верхе через window.kdMemoryGameConfig. * Файл загрузить через «Администрирование > Файлы», сохранить в UTF-8. */ (() => { 'use strict'; const defaults = { title: 'Память на сегодня', subtitle: 'Открывайте карточки и находите одинаковые пары.', columns: 6, cardBack: '', pairs: [] }; const css = ` :host{all:initial;display:block;width:100%;max-width:850px;margin:18px auto;color-scheme:light;font:14px/1.5 Pragmatica,Arial,sans-serif} *,*::before,*::after{box-sizing:border-box} [hidden]{display:none!important} .game{overflow:hidden;border:1px solid #d5d5d5;border-radius:12px;background:#e8e7e7;color:#222a35;box-shadow:0 10px 28px #222a3520} .head{padding:24px clamp(18px,4vw,36px);background:linear-gradient(115deg,#4f5d69,#64707a);color:#fff} h2{margin:0 0 7px;font:600 clamp(27px,5vw,42px)/1.15 "Playfair Display",Georgia,serif;letter-spacing:-.02em} .subtitle{margin:0;max-width:65ch;font-size:13px;opacity:.9} .body{padding:18px clamp(12px,3vw,26px) 22px} .toolbar{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-bottom:15px} .stats{display:flex;gap:8px;flex-wrap:wrap} .stat{padding:6px 11px;border:1px solid #d1d1d1;border-radius:999px;background:#f2f2f2;font-size:12px} .stat b{font-variant-numeric:tabular-nums} button{font:inherit} .reset{border:1px solid #af5f46;border-radius:999px;background:#af5f46;color:#fff;padding:8px 14px;font-size:12px;font-weight:700;cursor:pointer} .grid{display:grid;grid-template-columns:repeat(var(--cols),minmax(0,1fr));gap:clamp(7px,1.5vw,12px)} .tile{position:relative;min-width:0;aspect-ratio:1/1.12;padding:0;border:1px solid #c9c9c9;border-radius:9px;background:#f2f2f2;overflow:hidden;cursor:pointer;perspective:700px;touch-action:manipulation} .tile:focus-visible,.reset:focus-visible{outline:3px solid #af5f46;outline-offset:3px} .inner{position:absolute;inset:0;display:grid;place-items:center;transform-style:preserve-3d;transition:transform .32s} .tile.open .inner,.tile.matched .inner{transform:rotateY(180deg)} .face{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;backface-visibility:hidden;-webkit-backface-visibility:hidden} .back{background:radial-gradient(circle at 30% 25%,#ffffff45,transparent 45%),linear-gradient(145deg,#64707a,#4f5d69);color:#f2f2f2} .back:after{content:"";position:absolute;inset:7px;border:1px solid #ffffff55;border-radius:5px} .back-mark{font:italic 600 clamp(24px,5vw,42px)/1 "Playfair Display",Georgia,serif;opacity:.9} .front{transform:rotateY(180deg);background:#f2f2f2;flex-direction:column;gap:5px;padding:7px} .front img{display:block;width:100%;height:100%;min-height:0;object-fit:cover} .front .caption{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:clamp(10px,1.5vw,13px);padding:0 3px} .tile.matched{border-color:#af5f46;box-shadow:inset 0 0 0 2px #af5f46;cursor:default} .tile.matched .front{background:#e8e1dc} .message{min-height:22px;margin:13px 0 0;color:#64707a;font-size:12px} .win{margin-top:14px;padding:13px 15px;border-left:3px solid #af5f46;background:#f2f2f2;border-radius:0 8px 8px 0} .win strong{display:block;color:#222a35} @media(max-width:480px){.grid{gap:6px}.front{padding:4px}.front .caption{font-size:10px}.body{padding:13px 10px 16px}} @media(prefers-reduced-motion:reduce){.inner{transition:none}} `; function safeText(value, fallback, max = 180) { return typeof value === 'string' ? value.trim().slice(0, max) : fallback; } function validUrl(value) { if (typeof value !== 'string' || !value.trim()) return ''; try { const u = new URL(value.trim(), location.href); return u.protocol === 'https:' ? u.href : ''; } catch (_) { return ''; } } function make(tag, className, text) { const node = document.createElement(tag); if (className) node.className = className; if (text !== undefined) node.textContent = text; return node; } function start() { const raw = window.kdMemoryGameConfig; if (!raw || typeof raw !== 'object') return; const configs = Array.isArray(raw) ? raw : [raw]; configs.forEach(config => { try { mount(config); } catch (error) { console.warn('[Sixchat Memory] Не удалось запустить игру:', error); } }); } function mount(config) { const pairs = Array.isArray(config.pairs) ? config.pairs.map((pair, i) => ({ id: i, a: { image: validUrl(pair && pair.a && pair.a.image), label: safeText(pair && pair.a && pair.a.label, `Карточка ${i+1}А`, 80) }, b: { image: validUrl(pair && pair.b && pair.b.image), label: safeText(pair && pair.b && pair.b.label, `Карточка ${i+1}Б`, 80) } })).filter(pair => pair.a.image && pair.b.image) : []; const postId = Number(config.postId); let destination = null; if (Number.isInteger(postId) && postId > 0) { destination = document.querySelector(`#p${postId}, #post${postId}, [id="p${postId}"]`); } if (!destination) { const anchor = document.querySelector('[id^="p"], [id^="post"]'); destination = anchor && anchor.closest('.post, .post-content, .post-box') || document.querySelector('#pun-main') || document.querySelector('#pun'); } if (!destination) return; const host = document.createElement('div'); host.className = 'kd-memory-host'; host.dataset.kdMemory = 'true'; const shadow = host.attachShadow({mode:'open'}); const style = make('style'); style.textContent = css; const game = make('section','game'); const head = make('header','head'); head.append(make('h2','',safeText(config.title,defaults.title,100))); head.append(make('p','subtitle',safeText(config.subtitle,defaults.subtitle,400))); const body = make('div','body'); const toolbar = make('div','toolbar'); const stats = make('div','stats'); const moves = make('span','stat'); moves.innerHTML = 'Ходы: 0'; const found = make('span','stat'); found.innerHTML = 'Пары: 0 / 0'; const clock = make('span','stat'); clock.innerHTML = 'Время: 00:00'; stats.append(moves,found,clock); const reset = make('button','reset','Начать заново'); reset.type = 'button'; toolbar.append(stats,reset); const grid = make('div','grid'); const message = make('p','message','Откройте две карточки и найдите совпадение.'); const win = make('div','win'); win.hidden = true; win.append( make('strong','','Все пары найдены!'), make('span','win-detail','') ); body.append(toolbar,grid,message,win); game.append(head,body); shadow.append(style,game); destination.append(host); const columns = Math.max(2,Math.min(6,Number(config.columns)||defaults.columns)); grid.style.setProperty('--cols',String(columns)); const back = validUrl(config.cardBack); const deck = []; pairs.forEach(pair => { deck.push({pair:pair.id,side:'a',data:pair.a}); deck.push({pair:pair.id,side:'b',data:pair.b}); }); let first=null; let second=null; let locked=false; let moveCount=0; let matched=0; let startedAt=0; let interval=null; let elapsed=0; function timeString(seconds) { const m=String(Math.floor(seconds/60)).padStart(2,'0'); const s=String(seconds%60).padStart(2,'0'); return `${m}:${s}`; } function updateClock() { const seconds=startedAt ? elapsed+Math.floor((Date.now()-startedAt)/1000) : elapsed; clock.querySelector('b').textContent=timeString(seconds); } function startClock() { if (startedAt) return; startedAt=Date.now(); interval=setInterval(updateClock,1000); } function shuffle(items) { const result=items.slice(); for(let i=result.length-1;i>0;i--) { const j=Math.floor(Math.random()*(i+1)); [result[i],result[j]]=[result[j],result[i]]; } return result; } function render() { grid.replaceChildren(); shuffle(deck).forEach((item,index)=>{ const button=make('button','tile'); button.type='button'; button.setAttribute('aria-label','Закрытая карточка'); const inner=make('span','inner'); const rear=make('span','face back'); if(back) { const img=make('img'); img.src=back; img.alt=''; img.style.cssText='width:100%;height:100%;object-fit:cover'; rear.append(img); } else { rear.append(make('span','back-mark','SC')); } const front=make('span','face front'); const img=make('img'); img.src=item.data.image; img.alt=item.data.label; img.addEventListener('error',()=>{ img.alt='Изображение недоступно'; img.style.display='none'; front.append(make('span','caption','Изображение недоступно')); },{once:true}); front.append(img,make('span','caption',item.data.label)); inner.append(rear,front); button.append(inner); button.addEventListener('click',()=>flip(button,item)); grid.append(button); }); updateStats(); } function updateStats() { moves.querySelector('b').textContent=String(moveCount); found.querySelector('b').textContent=String(matched); found.querySelectorAll('b')[1].textContent=String(pairs.length); updateClock(); } function flip(button,item) { if(locked || button.classList.contains('open') || button.classList.contains('matched')) return; startClock(); button.classList.add('open'); button.setAttribute('aria-label',item.data.label); if(!first) { first={button,item}; return; } second={button,item}; moveCount++; updateStats(); if(first.item.pair===second.item.pair && first.item.side!==second.item.side) { first.button.classList.add('matched'); second.button.classList.add('matched'); first.button.disabled=true; second.button.disabled=true; matched++; first=null; second=null; updateStats(); message.textContent='Совпадение найдено.'; if(matched===pairs.length) { elapsed+=Math.floor((Date.now()-startedAt)/1000); startedAt=0; clearInterval(interval); updateClock(); win.hidden=false; win.querySelector('.win-detail').textContent= `Решено за ${moveCount} ходов и ${timeString(elapsed)}.`; message.textContent='Уровень пройден.'; } } else { locked=true; message.textContent='Не совпало. Попробуйте ещё раз.'; setTimeout(()=>{ first.button.classList.remove('open'); second.button.classList.remove('open'); first.button.setAttribute('aria-label','Закрытая карточка'); second.button.setAttribute('aria-label','Закрытая карточка'); first=null; second=null; locked=false; },850); } } function restart() { clearInterval(interval); interval=null; first=null; second=null; locked=false; moveCount=0; matched=0; startedAt=0; elapsed=0; win.hidden=true; message.textContent='Откройте две карточки и найдите совпадение.'; render(); } reset.addEventListener('click',restart); if(!pairs.length) { grid.hidden=true; message.textContent='В настройках не добавлены пары изображений.'; reset.disabled=true; } else { render(); } } if(document.readyState==='loading') { document.addEventListener('DOMContentLoaded',start,{once:true}); } else { start(); } })();