Как создать игру-головоломку «15», используя jQuery и JavaScript

Чтобы создать головоломку «15» с использованием JavaScript и библиотеки jQuery, вы можете выполнить следующие действия:

Шаг 1. Разметка HTML
Создайте структуру HTML для доски-головоломки. Вы можете использовать контейнер divдля хранения плиток, и каждая плитка может быть представлена ​​элементом div.

<div id="puzzle-board">
  <div class="tile">1</div>
  <div class="tile">2</div>
  <div class="tile">3</div>
  <!-- ... -->
  <div class="tile">15</div>
</div>

Шаг 2. Оформление CSS
Оформите доску-головоломку и плитки с помощью CSS. Вы можете установить размеры, границы и другие визуальные свойства по своему усмотрению.

центр;
размер шрифта: 24 пикселя;
курсор: указатель;

Шаг 3. Логика JavaScript
Используйте JavaScript и jQuery для реализации логики головоломки. Вот пример, в котором плитки перемешиваются случайным образом при загрузке страницы и позволяют игроку перемещать плитки, нажимая на них.

$(document).ready(function() {
  // Get the puzzle board and tiles
  var $board = $('#puzzle-board');
  var $tiles = $board.children('.tile');
  // Shuffle the tiles randomly
  shuffleTiles();
  // Attach click event handler to tiles
  $tiles.click(function() {
    var $tile = $(this);
    var $emptyTile = $board.children('.empty');
    // Check if the clicked tile can move
    if (canMove($tile, $emptyTile)) {
      // Swap the tile with the empty tile
      swapTiles($tile, $emptyTile);
      // Check if the puzzle is solved
      if (isSolved()) {
        alert('Congratulations! Puzzle solved.');
      }
    }
  });
  // Function to shuffle the tiles randomly
  function shuffleTiles() {
    $tiles.detach().sort(function() {
      return Math.random() - 0.5;
    });
    $board.append($tiles);
    $tiles.slice(-1).addClass('empty');
  }
// Function to check if a tile can move
  function canMove($tile, $emptyTile) {
    var tileIndex = $tiles.index($tile);
    var emptyIndex = $tiles.index($emptyTile);
    // Check if the tile is adjacent to the empty tile
    return (
      (tileIndex === emptyIndex - 1 && tileIndex % 4 !== 3) || // Left
      (tileIndex === emptyIndex + 1 && tileIndex % 4 !== 0) || // Right
      tileIndex === emptyIndex - 4 || // Up
      tileIndex === emptyIndex + 4 // Down
    );
  }
// Function to swap two tiles
  function swapTiles($tile1, $tile2) {
    $tile1.swap($tile2);
    $tile1.toggleClass('empty');
    $tile2.toggleClass('empty');
  }
// Function to check if the puzzle is solved
  function isSolved() {
    var sortedTiles = $tiles
      .toArray()
      .map(function(tile) {
        return parseInt(tile.innerHTML);
      })
      .slice(0, -1)
      .sort(function(a, b) {
        return a - b;
      });
    for (var i = 0; i < sortedTiles.length; i++) {
      if (sortedTiles[i] !== i + 1) {
        return false;
      }
    }
    return true;
  }
// jQuery plugin to swap elements
  $.fn.swap = function($other) {
    var $this = $(this);
    var $children = $this.parent().children();
    var index1 = $children.index($this);
    var index2 = $children.index($other);
    if (index1 > index2) {
      $this.before($other);
    } else {
      $this.after($other);
    }
  };
});