Untitled
unknown
plain_text
9 months ago
3.7 kB
1
Indexable
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sliding Puzzle Game</title> <style> body { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #f0f0f0; margin: 0; } .puzzle-container { display: grid; grid-template-columns: repeat(4, 100px); grid-template-rows: repeat(4, 100px); gap: 2px; } .puzzle-piece { display: flex; justify-content: center; align-items: center; width: 100px; height: 100px; background-color: #2196f3; color: white; font-size: 24px; cursor: pointer; user-select: none; } .empty { background-color: #ffffff; cursor: default; } </style> </head> <body> <div class="puzzle-container" id="puzzle-container"></div> <script> const puzzleContainer = document.getElementById('puzzle-container'); const size = 4; let puzzle = []; let emptyRow = size - 1; let emptyCol = size - 1; function initPuzzle() { puzzle = []; for (let i = 0; i < size; i++) { puzzle[i] = []; for (let j = 0; j < size; j++) { if (i === size - 1 && j === size - 1) { puzzle[i][j] = ''; } else { puzzle[i][j] = i * size + j + 1; } } } shufflePuzzle(); drawPuzzle(); } function shufflePuzzle() { for (let i = 0; i < 1000; i++) { const direction = Math.floor(Math.random() * 4); switch (direction) { case 0: move(emptyRow - 1, emptyCol); break; // up case 1: move(emptyRow + 1, emptyCol); break; // down case 2: move(emptyRow, emptyCol - 1); break; // left case 3: move(emptyRow, emptyCol + 1); break; // right } } } function drawPuzzle() { puzzleContainer.innerHTML = ''; for (let i = 0; i < size; i++) { for (let j = 0; j < size; j++) { const piece = document.createElement('div'); piece.className = 'puzzle-piece'; piece.textContent = puzzle[i][j]; if (puzzle[i][j] === '') { piece.classList.add('empty'); } else { piece.addEventListener('click', () => move(i, j)); } puzzleContainer.appendChild(piece); } } } function move(row, col) { if (row >= 0 && row < size && col >= 0 && col < size) { const rowDiff = Math.abs(emptyRow - row); const colDiff = Math.abs(emptyCol - col); if (rowDiff + colDiff === 1) { puzzle[emptyRow][emptyCol] = puzzle[row][col]; puzzle[row][col] = ''; emptyRow = row; emptyCol = col; drawPuzzle(); } } } initPuzzle(); </script> </body> </html>
Editor is loading...
Leave a Comment