(function() {
console.log("Запуск Бота-Навигатора...");
const DELAY = 200;
const weights = [
[2, 4, 8, 16],
[32, 64, 128, 256],
[512, 1024, 2048, 4096],
[8192, 16384, 32768, 65536]
];
function getGrid() {
let grid = Array(4).fill(0).map(() => Array(4).fill(0));
const tiles = Array.from(document.querySelectorAll('div')).filter(el => {
return el.innerText.replace(/[^0-9]/g, '').length > 0 && el.children.length === 0;
});
if (tiles.length === 0) return grid;
// Определяем размеры контейнера, чтобы понять шаг сетки
const firstTile = tiles[0].getBoundingClientRect();
const container = tiles[0].parentElement.getBoundingClientRect();
const cellW = container.width / 4;
const cellH = container.height / 4;
tiles.forEach(tile => {
const rect = tile.getBoundingClientRect();
const val = parseInt(tile.innerText.replace(/[^0-9]/g, '')) || 0;
// Вычисляем колонку и ряд на основе координат (относительно контейнера)
const col = Math.floor((rect.left - container.left + cellW / 2) / cellW);
const row = Math.floor((rect.top - container.top + cellH / 2) / cellH);
if (row >= 0 && row < 4 && col >= 0 && col < 4) {
grid[row][col] = val;
}
});
return grid;
}
function evaluate(grid) {
let score = 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];
}
}
}
return score;
}
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("Game Over")) return clearInterval(brain);
const grid = getGrid();
// Симулируем "вес" направлений
const scoreD = evaluate(grid) * 1.5; // Приоритет вниз
const scoreR = evaluate(grid) * 1.4; // Приоритет вправо
// Если поле забито (мало нулей)
const empty = grid.flat().filter(v => v === 0).length;
if (empty > 1) {
if (scoreD >= scoreR) sendKey('D');
else sendKey('R');
} else {
// В панике пробуем влево, но никогда вверх
const panic = Math.random();
if (panic > 0.5) sendKey('D');
else if (panic > 0.1) sendKey('R');
else sendKey('L');
}
}, DELAY);
})();