<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Собери картинку (Drag & Drop)</title>
<style>
  body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; margin-top: 50px; }
  #puzzle { display: grid; grid-template-columns: repeat(3, 100px); grid-gap: 2px; }
  .piece { width: 100px; height: 100px; background-size: 300px 300px; border: 1px solid #333; }
  .dragging { opacity: 0.5; }
</style>
</head>
<body>

<h2>Собери картинку</h2>
<div id="puzzle"></div>
<p id="message"></p>

<script>
const rows = 3;
const cols = 3;
const puzzle = document.getElementById('puzzle');
const message = document.getElementById('message');

// Картинка 300x300 (можно заменить)
const image = 'https://i.imgur.com/3XjQqfS.jpg';

// Создаём кусочки
let pieces = [];
for (let r = 0; r < rows; r++) {
  for (let c = 0; c < cols; c++) {
    pieces.push({row: r, col: c});
  }
}

// Перемешиваем кусочки
pieces = pieces.sort(() => Math.random() - 0.5);

// Создаём элементы на странице
pieces.forEach((p, index) => {
  const div = document.createElement('div');
  div.className = 'piece';
  div.draggable = true;
  div.style.backgroundImage = `url(${image})`;
  div.style.backgroundPosition = `-${p.col * 100}px -${p.row * 100}px`;
  div.dataset.correctIndex = index;
  puzzle.appendChild(div);
});

// Drag & Drop
let dragSrc = null;

puzzle.addEventListener('dragstart', e => {
  if (e.target.classList.contains('piece')) {
    dragSrc = e.target;
    e.target.classList.add('dragging');
  }
});

puzzle.addEventListener('dragend', e => {
  e.target.classList.remove('dragging');
});

puzzle.addEventListener('dragover', e => {
  e.preventDefault();
});

puzzle.addEventListener('drop', e => {
  e.preventDefault();
  if (e.target.classList.contains('piece') && dragSrc) {
    // Меняем фоновые позиции
    const temp = dragSrc.style.backgroundPosition;
    dragSrc.style.backgroundPosition = e.target.style.backgroundPosition;
    e.target.style.backgroundPosition = temp;

    checkWin();
  }
});

// Проверка победы
function checkWin() {
  let correct = 0;
  const divs = document.querySelectorAll('.piece');
  divs.forEach(div => {
    const index = parseInt(div.dataset.correctIndex);
    if (div.style.backgroundPosition === `-${pieces[index].col * 100}px -${pieces[index].row * 100}px`) {
      correct++;
    }
  });
  if (correct === rows * cols) {
    message.textContent = '🎉 Победа! Ты собрал картинку!';
  }
}
</script>

</body>
</html>