5/19/2014

image puzzle game Using JavaScript, HTML & CSS

image puzzle game Using JavaScript, HTML & CSS
image puzzle game Using JavaScript, HTML & CSS

 

Step 1: HTML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Image Puzzle Game</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Image Puzzle Game</h1>
  <div id="puzzle-container"></div>
  <button id="shuffle-button">Shuffle</button>
  <p id="message"></p>

  <script src="script.js"></script>
</body>
</html>

Step 2: CSS (style.css)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
body {
  font-family: Arial, sans-serif;
  text-align: center;
  background-color: #f0f0f0;
}

#puzzle-container {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(3, 100px);
  gap: 2px;
  margin: 20px auto;
  width: 306px;
  border: 2px solid #444;
}

.tile {
  width: 100px;
  height: 100px;
  background-image: url('https://via.placeholder.com/300'); /* Change to any image URL */
  background-size: 300px 300px;
  cursor: pointer;
  border: 1px solid #ccc;
  box-sizing: border-box;
  transition: transform 0.2s;
}

.tile.correct {
  border-color: green;
}

#shuffle-button {
  padding: 10px 20px;
  font-size: 16px;
  margin-bottom: 10px;
}

#message {
  font-weight: bold;
  color: green;
}

Step 3: JavaScript (script.js)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const container = document.getElementById('puzzle-container');
const shuffleButton = document.getElementById('shuffle-button');
const message = document.getElementById('message');

const size = 3;
let tiles = [];

function createTiles() {
  tiles = [];

  for (let row = 0; row < size; row++) {
    for (let col = 0; col < size; col++) {
      const index = row * size + col;

      const tile = document.createElement('div');
      tile.classList.add('tile');
      tile.style.backgroundPosition = `-${col * 100}px -${row * 100}px`;
      tile.dataset.index = index;

      tile.addEventListener('click', () => selectTile(tile));
      container.appendChild(tile);
      tiles.push(tile);
    }
  }
}

let selectedTile = null;

function selectTile(tile) {
  if (!selectedTile) {
    selectedTile = tile;
    tile.style.transform = 'scale(1.1)';
  } else {
    swapTiles(selectedTile, tile);
    selectedTile.style.transform = 'scale(1)';
    selectedTile = null;
    checkWin();
  }
}

function swapTiles(tile1, tile2) {
  const temp = tile1.dataset.index;
  tile1.dataset.index = tile2.dataset.index;
  tile2.dataset.index = temp;

  updateTilePositions();
}

function updateTilePositions() {
  tiles.forEach(tile => {
    const index = tile.dataset.index;
    const row = Math.floor(index / size);
    const col = index % size;
    tile.style.backgroundPosition = `-${col * 100}px -${row * 100}px`;
  });
}

function shuffleTiles() {
  message.textContent = '';
  const indices = [...Array(tiles.length).keys()];
  indices.sort(() => Math.random() - 0.5);
  tiles.forEach((tile, i) => {
    tile.dataset.index = indices[i];
  });
  updateTilePositions();
}

function checkWin() {
  const isWin = tiles.every((tile, index) => Number(tile.dataset.index) === index);
  if (isWin) {
    message.textContent = '🎉 Puzzle Completed!';
    tiles.forEach(tile => tile.classList.add('correct'));
  } else {
    tiles.forEach(tile => tile.classList.remove('correct'));
  }
}

shuffleButton.addEventListener('click', shuffleTiles);

createTiles();
updateTilePositions();

You can change the image by replacing the URL in the CSS background-image property. To make it harder, increase the grid size (e.g., 4x4). Add a timer or move counter for more challenge.

5/10/2014

Sliding Puzzle Game

 

Sliding Puzzle Game

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Sliding Puzzle Game</title>
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: #222;
      color: white;
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100vh;
      margin: 0;
      justify-content: center;
    }

    h1 {
      margin-bottom: 20px;
    }

    #puzzle {
      display: grid;
      grid-template-columns: repeat(4, 80px);
      grid-template-rows: repeat(4, 80px);
      gap: 5px;
    }

    .tile {
      display: flex;
      justify-content: center;
      align-items: center;
      background: #61dafb;
      color: #222;
      font-weight: bold;
      font-size: 1.5rem;
      border-radius: 8px;
      cursor: pointer;
      user-select: none;
      transition: background 0.3s;
    }

    .tile.empty {
      background: transparent;
      cursor: default;
    }

    .tile:hover:not(.empty) {
      background: #21a1f1;
    }

    #message {
      margin-top: 20px;
      font-size: 1.2rem;
      min-height: 1.5em;
    }

    button {
      margin-top: 20px;
      padding: 10px 20px;
      font-size: 1rem;
      border: none;
      border-radius: 5px;
      background: #61dafb;
      color: #222;
      font-weight: bold;
      cursor: pointer;
      transition: background 0.3s;
    }
    button:hover {
      background: #21a1f1;
    }
  </style>
</head>
<body>
  <h1>Sliding Puzzle Game</h1>
  <div id="puzzle"></div>
  <div id="message"></div>
  <button id="shuffleBtn">Shuffle & Start</button>

  <script>
    const puzzle = document.getElementById('puzzle');
    const message = document.getElementById('message');
    const shuffleBtn = document.getElementById('shuffleBtn');

    let tiles = [];
    const size = 4; // 4x4 grid
    let emptyPos = size * size - 1; // start empty tile at last position
    let isPlaying = false;

    // Initialize tiles in order
    function init() {
      tiles = [];
      puzzle.innerHTML = '';
      for (let i = 0; i < size * size; i++) {
        tiles[i] = i;
        const tile = document.createElement('div');
        tile.classList.add('tile');
        if (i === emptyPos) {
          tile.classList.add('empty');
          tile.textContent = '';
        } else {
          tile.textContent = i + 1;
        }
        tile.setAttribute('data-index', i);
        tile.addEventListener('click', () => {
          if (!isPlaying) return;
          moveTile(i);
        });
        puzzle.appendChild(tile);
      }
      message.textContent = "Click 'Shuffle & Start' to play!";
    }

    // Swap two tiles in the array and update the DOM
    function swapTiles(i, j) {
      [tiles[i], tiles[j]] = [tiles[j], tiles[i]];
      updateTiles();
    }

    // Update tile DOM to reflect current tiles array
    function updateTiles() {
      tiles.forEach((value, i) => {
        const tile = puzzle.children[i];
        if (value === emptyPos) {
          tile.classList.add('empty');
          tile.textContent = '';
          tile.style.cursor = 'default';
        } else {
          tile.classList.remove('empty');
          tile.textContent = value + 1;
          tile.style.cursor = 'pointer';
        }
      });
    }

    // Check if tile at index can move (if adjacent to empty)
    function canMove(index) {
      const row = Math.floor(index / size);
      const col = index % size;
      const emptyRow = Math.floor(tiles.indexOf(emptyPos) / size);
      const emptyCol = tiles.indexOf(emptyPos) % size;

      // Check if tile is next to empty tile (up/down/left/right)
      return (
        (row === emptyRow && Math.abs(col - emptyCol) === 1) ||
        (col === emptyCol && Math.abs(row - emptyRow) === 1)
      );
    }

    // Move tile if possible
    function moveTile(index) {
      if (canMove(index)) {
        const emptyIndex = tiles.indexOf(emptyPos);
        swapTiles(index, emptyIndex);
        if (checkWin()) {
          message.textContent = "🎉 Congratulations! You solved the puzzle!";
          isPlaying = false;
        }
      }
    }

    // Shuffle tiles randomly using Fisher-Yates shuffle and check solvability
    function shuffle() {
      do {
        for (let i = tiles.length - 2; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [tiles[i], tiles[j]] = [tiles[j], tiles[i]];
        }
      } while (!isSolvable(tiles));
      updateTiles();
      message.textContent = "Game started! Arrange the tiles.";
      isPlaying = true;
    }

    // Check if puzzle is solved
    function checkWin() {
      for (let i = 0; i < tiles.length - 1; i++) {
        if (tiles[i] !== i) return false;
      }
      return true;
    }

    // Count inversions for solvability check
    function countInversions(arr) {
      let inversions = 0;
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (arr[i] !== emptyPos && arr[j] !== emptyPos && arr[i] > arr[j]) {
            inversions++;
          }
        }
      }
      return inversions;
    }

    // Check if current puzzle configuration is solvable
    function isSolvable(arr) {
      const inversions = countInversions(arr);
      const emptyRow = Math.floor(arr.indexOf(emptyPos) / size);

      // For even grid width (4), puzzle is solvable if:
      // - empty on even row from bottom and inversions odd
      // - empty on odd row from bottom and inversions even
      if (size % 2 === 0) {
        const emptyRowFromBottom = size - emptyRow;
        if ((emptyRowFromBottom % 2 === 0) === (inversions % 2 === 1)) {
          return true;
        } else {
          return false;
        }
      } else {
        // Odd grid width: inversions must be even
        return inversions % 2 === 0;
      }
    }

    shuffleBtn.addEventListener('click', () => {
      shuffle();
    });

    init();
  </script>
</body>
</html>