Загрузка данных


(function() {
    console.log("Запуск Бит-Аналитика 6.0...");

    const DELAY = 150;
    // Веса ячеек: прижимаем всё к правому нижнему углу
    const weights = [
        [2, 5, 10, 20],
        [4, 15, 30, 60],
        [8, 25, 100, 500],
        [16, 50, 1000, 10000]
    ];

    function getGrid() {
        let grid = Array(4).fill(0).map(() => Array(4).fill(0));
        // Находим контейнер, где лежат все плитки
        const container = document.querySelector('.cardBody') || document.activeElement.parentElement;
        if (!container) return null;

        const tiles = Array.from(container.querySelectorAll('div')).filter(el => 
            el.innerText && (el.innerText.includes('байт') || el.innerText.includes('бит') || el.innerText.includes('КБ'))
        );

        const cRect = container.getBoundingClientRect();
        const cellW = cRect.width / 4;
        const cellH = cRect.height / 4;

        tiles.forEach(tile => {
            const tRect = tile.getBoundingClientRect();
            // Вычисляем координаты плитки относительно сетки 4x4
            const col = Math.floor((tRect.left - cRect.left + cellW / 2) / cellW);
            const row = Math.floor((tRect.top - cRect.top + cellH / 2) / cellH);
            
            // Получаем числовое значение (обрабатываем байты и биты как числа)
            const val = parseInt(tile.innerText.replace(/[^0-9]/g, '')) || 0;

            if (row >= 0 && row < 4 && col >= 0 && col < 4) {
                grid[row][col] = val;
            }
        });
        return grid;
    }

    function evaluate(grid, move) {
        let score = 0;
        let empty = 0;
        for (let r = 0; r < 4; r++) {
            for (let c = 0; c < 4; c++) {
                if (grid[r][c] > 0) {
                    // Основной вес по матрице
                    score += Math.log2(grid[r][c]) * weights[r][c];
                    // Бонус за соединение (если рядом одинаковые)
                    if (c < 3 && grid[r][c] === grid[r][c+1]) score += grid[r][c] * 2;
                    if (r < 3 && grid[r][c] === grid[r+1][c]) score += grid[r][c] * 2;
                } else {
                    empty++;
                }
            }
        }
        return score + (empty * 50);
    }

    function sendKey(dir) {
        const codes = { 'U': 38, 'R': 39, 'D': 40, 'L': 37 };
        const k = 'Arrow' + (dir==='U'?'Up':dir==='R'?'Right':dir==='D'?'Down':'Left');
        const ev = new KeyboardEvent('keydown', { key: k, code: k, keyCode: codes[dir], bubbles: true });
        window.dispatchEvent(ev);
        document.dispatchEvent(ev);
    }

    const brain = setInterval(() => {
        if (document.body.innerText.includes("Игра окончена")) return clearInterval(brain);

        const grid = getGrid();
        if (!grid) return;

        // Принимаем решение
        const empty = grid.flat().filter(v => v === 0).length;

        // 1. Пытаемся всегда жать ВНИЗ или ВПРАВО
        // 2. ВЛЕВО — только если поле забито и хода нет
        // 3. ВВЕРХ — запрещено
        
        if (empty > 2) {
            // Если место есть, просто чередуем главные направления
            Math.random() > 0.4 ? sendKey('D') : sendKey('R');
        } else {
            // Если тесно, выбираем по оценке
            const scoreD = evaluate(grid);
            const scoreR = evaluate(grid) * 0.9;
            
            if (scoreD >= scoreR) sendKey('D');
            else sendKey('R');

            // Микро-шанс на спасительный сдвиг влево
            if (Math.random() > 0.95) sendKey('L');
        }

    }, DELAY);
})();