Changed around line 1
+ const puzzleContainer = document.getElementById('puzzle-container');
+ const resetBtn = document.getElementById('reset-btn');
+ const message = document.getElementById('message');
+ let tiles = [];
+ let emptyIndex = 8;
+
+ function createTiles() {
+ for (let i = 0; i < 8; i++) {
+ const tile = document.createElement('div');
+ tile.classList.add('tile');
+ tile.textContent = i + 1;
+ tile.dataset.index = i;
+ tile.addEventListener('click', moveTile);
+ tiles.push(tile);
+ }
+ const emptyTile = document.createElement('div');
+ emptyTile.classList.add('tile', 'empty');
+ emptyTile.dataset.index = 8;
+ tiles.push(emptyTile);
+ puzzleContainer.append(...tiles);
+ }
+
+ function shuffleTiles() {
+ do {
+ tiles.sort(() => Math.random() - 0.5);
+ tiles.forEach((tile, index) => {
+ tile.dataset.index = index;
+ puzzleContainer.append(tile);
+ });
+ emptyIndex = tiles.findIndex(tile => tile.classList.contains('empty'));
+ } while (!isSolvable());
+ }
+
+ function isSolvable() {
+ let inversions = 0;
+ const tileNumbers = tiles
+ .filter(tile => !tile.classList.contains('empty'))
+ .map(tile => Number(tile.textContent));
+
+ for (let i = 0; i < tileNumbers.length; i++) {
+ for (let j = i + 1; j < tileNumbers.length; j++) {
+ if (tileNumbers[i] > tileNumbers[j]) inversions++;
+ }
+ }
+
+ return inversions % 2 === 0;
+ }
+
+ function moveTile(e) {
+ const clickedIndex = Number(e.target.dataset.index);
+ if (isAdjacent(clickedIndex, emptyIndex)) {
+ swapTiles(clickedIndex, emptyIndex);
+ emptyIndex = clickedIndex;
+ if (isSolved()) {
+ showMessage();
+ tiles.forEach(tile => tile.removeEventListener('click', moveTile));
+ }
+ }
+ }
+
+ function isAdjacent(index1, index2) {
+ const row1 = Math.floor(index1 / 3);
+ const col1 = index1 % 3;
+ const row2 = Math.floor(index2 / 3);
+ const col2 = index2 % 3;
+ return Math.abs(row1 - row2) + Math.abs(col1 - col2) === 1;
+ }
+
+ function swapTiles(index1, index2) {
+ [tiles[index1].dataset.index, tiles[index2].dataset.index] = [
+ tiles[index2].dataset.index,
+ tiles[index1].dataset.index
+ ];
+ puzzleContainer.insertBefore(tiles[index1], tiles[index2]);
+ }
+
+ function isSolved() {
+ return tiles.every((tile, index) => {
+ if (tile.classList.contains('empty')) return index === 8;
+ return Number(tile.textContent) === index + 1;
+ });
+ }
+
+ function showMessage() {
+ message.classList.add('visible');
+ }
+
+ function resetGame() {
+ tiles.forEach(tile => tile.addEventListener('click', moveTile));
+ message.classList.remove('visible');
+ shuffleTiles();
+ }
+
+ function init() {
+ createTiles();
+ shuffleTiles();
+ resetBtn.addEventListener('click', resetGame);
+ }
+
+ init();