Changed around line 1
+ class PuzzleGame {
+ constructor() {
+ this.moves = 0;
+ this.grid = document.getElementById('puzzleGrid');
+ this.pieces = Array.from(document.querySelectorAll('.puzzle-piece'));
+ this.emptyPiece = document.querySelector('.empty');
+ this.moveCounter = document.getElementById('moveCounter');
+ this.winMessage = document.getElementById('winMessage');
+ this.resetButton = document.getElementById('resetGame');
+
+ this.initializeGame();
+ }
+
+ initializeGame() {
+ this.resetButton.addEventListener('click', () => this.resetGame());
+ this.grid.addEventListener('click', (e) => this.handlePieceClick(e));
+ this.randomizeBoard();
+ }
+
+ handlePieceClick(e) {
+ const piece = e.target.closest('.puzzle-piece');
+ if (!piece || piece.classList.contains('empty')) return;
+
+ if (this.isMovable(piece)) {
+ this.movePiece(piece);
+ this.moves++;
+ this.moveCounter.textContent = `Moves: ${this.moves}`;
+
+ if (this.checkWin()) {
+ this.showWinMessage();
+ }
+ }
+ }
+
+ isMovable(piece) {
+ const emptyIndex = Array.from(this.grid.children).indexOf(this.emptyPiece);
+ const pieceIndex = Array.from(this.grid.children).indexOf(piece);
+
+ const row1 = Math.floor(emptyIndex / 3);
+ const col1 = emptyIndex % 3;
+ const row2 = Math.floor(pieceIndex / 3);
+ const col2 = pieceIndex % 3;
+
+ return Math.abs(row1 - row2) + Math.abs(col1 - col2) === 1;
+ }
+
+ movePiece(piece) {
+ const emptyRect = this.emptyPiece.getBoundingClientRect();
+ const pieceRect = piece.getBoundingClientRect();
+
+ const parent = piece.parentNode;
+ const placeholder = document.createElement('div');
+ parent.insertBefore(placeholder, this.emptyPiece);
+ parent.insertBefore(this.emptyPiece, piece);
+ parent.insertBefore(piece, placeholder);
+ parent.removeChild(placeholder);
+ }
+
+ randomizeBoard() {
+ let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
+ numbers = this.shuffle(numbers);
+
+ this.pieces.forEach((piece, index) => {
+ piece.dataset.index = numbers[index];
+ if (numbers[index] === 9) {
+ piece.classList.add('empty');
+ piece.textContent = '';
+ } else {
+ piece.classList.remove('empty');
+ piece.textContent = numbers[index];
+ }
+ });
+
+ this.moves = 0;
+ this.moveCounter.textContent = 'Moves: 0';
+ this.winMessage.classList.add('hidden');
+ }
+
+ shuffle(array) {
+ let currentIndex = array.length;
+ while (currentIndex !== 0) {
+ const randomIndex = Math.floor(Math.random() * currentIndex);
+ currentIndex--;
+ [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
+ }
+ return array;
+ }
+
+ checkWin() {
+ return this.pieces.every((piece, index) => {
+ return piece.dataset.index == index + 1;
+ });
+ }
+
+ showWinMessage() {
+ this.winMessage.classList.remove('hidden');
+ setTimeout(() => {
+ this.resetGame();
+ }, 3000);
+ }
+
+ resetGame() {
+ this.randomizeBoard();
+ }
+ }
+
+ document.addEventListener('DOMContentLoaded', () => {
+ new PuzzleGame();
+ });