Changed around line 1
+ class SlidingPuzzle {
+ constructor() {
+ this.size = 9;
+ this.tiles = [];
+ this.moves = 0;
+ this.timer = 0;
+ this.timerInterval = null;
+ this.init();
+ }
+
+ init() {
+ this.puzzle = document.getElementById('puzzle');
+ this.moveCounter = document.getElementById('moveCount');
+ this.timerDisplay = document.getElementById('timer');
+ document.getElementById('startGame').addEventListener('click', () => this.startNewGame());
+ this.createTiles();
+ }
+
+ createTiles() {
+ this.puzzle.innerHTML = '';
+ this.tiles = Array.from({length: this.size * this.size - 1}, (_, i) => i + 1);
+ this.tiles.push(null);
+
+ this.tiles.forEach((num, index) => {
+ const tile = document.createElement('div');
+ tile.className = num ? 'tile' : 'tile empty';
+ if (num) tile.textContent = num;
+ tile.addEventListener('click', () => this.moveTile(index));
+ this.puzzle.appendChild(tile);
+ });
+ }
+
+ startNewGame() {
+ this.moves = 0;
+ this.moveCounter.textContent = '0';
+ this.shuffleTiles();
+ this.startTimer();
+ }
+
+ shuffleTiles() {
+ for (let i = this.tiles.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [this.tiles[i], this.tiles[j]] = [this.tiles[j], this.tiles[i]];
+ }
+ this.updateDisplay();
+ }
+
+ moveTile(index) {
+ const emptyIndex = this.tiles.indexOf(null);
+ if (!this.isValidMove(index, emptyIndex)) return;
+
+ [this.tiles[index], this.tiles[emptyIndex]] = [this.tiles[emptyIndex], this.tiles[index]];
+ this.moves++;
+ this.moveCounter.textContent = this.moves;
+ this.updateDisplay();
+
+ if (this.checkWin()) {
+ clearInterval(this.timerInterval);
+ setTimeout(() => alert('Congratulations! You won!'), 100);
+ }
+ }
+
+ isValidMove(index, emptyIndex) {
+ const row = Math.floor(index / this.size);
+ const emptyRow = Math.floor(emptyIndex / this.size);
+ const col = index % this.size;
+ const emptyCol = emptyIndex % this.size;
+
+ return (
+ (Math.abs(row - emptyRow) === 1 && col === emptyCol) ||
+ (Math.abs(col - emptyCol) === 1 && row === emptyRow)
+ );
+ }
+
+ updateDisplay() {
+ const tiles = this.puzzle.children;
+ this.tiles.forEach((num, index) => {
+ tiles[index].className = num ? 'tile' : 'tile empty';
+ tiles[index].textContent = num || '';
+ });
+ }
+
+ startTimer() {
+ clearInterval(this.timerInterval);
+ this.timer = 0;
+ this.updateTimerDisplay();
+
+ this.timerInterval = setInterval(() => {
+ this.timer++;
+ this.updateTimerDisplay();
+ }, 1000);
+ }
+
+ updateTimerDisplay() {
+ const minutes = Math.floor(this.timer / 60);
+ const seconds = this.timer % 60;
+ this.timerDisplay.textContent =
+ `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
+ }
+
+ checkWin() {
+ return this.tiles.every((tile, index) =>
+ (index === this.tiles.length - 1 && tile === null) ||
+ tile === index + 1
+ );
+ }
+ }
+
+ document.addEventListener('DOMContentLoaded', () => {
+ new SlidingPuzzle();
+ });