diff --git a/index.html b/index.html new file mode 100644 index 0000000..2dcca92 --- /dev/null +++ b/index.html @@ -0,0 +1,17 @@ + + + + + + Sliding Puzzle + + + + +

Sliding Puzzle Game

+
+
+ + + + \ No newline at end of file diff --git a/original-image.png b/original-image.png new file mode 100644 index 0000000..8e16481 Binary files /dev/null and b/original-image.png differ diff --git a/script.js b/script.js new file mode 100644 index 0000000..a6352c8 --- /dev/null +++ b/script.js @@ -0,0 +1,85 @@ +const imgPos = [ + 'top left', + 'top center', + 'top right', + 'center left', + 'center center', + 'center right', + 'bottom left', + 'bottom center', +] +let grid = [ + 0,1,2, + 3,4,5, + 6,7,8 +] + + + + +const newGame = () => { + let seq = [0,1,2,3,4,5,6,7,8]; + grid = []; + for (let i=0;i<9;i++) { + const cur = seq.splice(Math.random()*seq.length, 1); + grid.push(cur[0]); + } +} + + +const shift = (idx) => { + if (grid[idx-1] == 8) { + grid[idx-1] = grid[idx]; + grid[idx] = 8; + } else if (grid[idx+1] == 8) { + grid[idx+1] = grid[idx]; + grid[idx] = 8; + } else if (grid[idx+3] == 8) { + grid[idx+3]=grid[idx]; + grid[idx] =8; + }else if (grid[idx-3] == 8) { + grid[idx-3]=grid[idx]; + grid[idx] =8; + } + display(); +} + +const checkWin = () => { + for (let i=0;i<9;i++) { + if (grid[i]!=i) { + return false; + } + } + return true; +} + +const display = () => { + let gridDiv = document.querySelector('.grid').cloneNode(false); + for (let i=0;i<9;i++) { + const cell = document.createElement('div') + cell.classList.add('.cell'); + if (grid[i]!=8) { + cell.style.backgroundPosition = imgPos[grid[i]]; + cell.style.backgroundImage = 'url("https://d3dyfaf3iutrxo.cloudfront.net/general/upload/9999541de1b34295a6c3322e95e2fea7.webp")'; + cell.style.cursor = 'pointer'; + cell.addEventListener('click', ()=>shift(i)); + } + gridDiv.appendChild(cell); + } + document.querySelector('.grid').replaceWith(gridDiv); + setTimeout(() => { + if (checkWin()) { + alert("Congratulations! You solved the puzzle! Click on New Game to continue playing !!"); + } + }, 10); +} +newGame(); +display(); + + + + +document.querySelector('button').addEventListener('click', ()=>{ + newGame(); + display(); +}) \ No newline at end of file diff --git a/style.css b/style.css new file mode 100644 index 0000000..f109691 --- /dev/null +++ b/style.css @@ -0,0 +1,34 @@ +body { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + gap: 10px; + background-color: #f3f3f3; +} + +.grid { + display: grid; + grid-template-columns: 200px 200px 200px; + grid-template-rows: 180px 180px 180px; + justify-content: center; + background-color: white; + gap: 2px; +} + + +.cell { + width: 100px; + height: 100px; + cursor: pointer; +} + +button { + padding: 10px; + margin-top: 20px; + outline: none; + border: none; + background-color: #4caf50; + border-radius: 5px; + color: white; +} \ No newline at end of file