Cover Image for Picture Puzzle Game using Jquery
127 views

Picture Puzzle Game using Jquery

Creating a picture puzzle game using jQuery involves breaking an image into pieces and allowing the user to drag and drop those pieces to reassemble the original image. Below is a simple example of a picture puzzle game using jQuery:

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Picture Puzzle Game</title>
  <style>
    .puzzle-container {
      width: 400px;
      height: 400px;
      border: 2px solid #000;
      margin: 20px auto;
      position: relative;
    }

    .puzzle-piece {
      width: 100px;
      height: 100px;
      border: 1px solid #000;
      background-size: 400px 400px;
      position: absolute;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <div class="puzzle-container" id="puzzleContainer">
    <!-- Puzzle pieces will be created here -->
  </div>
</body>
</html>

JavaScript (script.js):

$(document).ready(function() {
  const pieces = 4; // Number of puzzle pieces (rows x columns)

  // Calculate the size of each piece based on the container's dimensions
  const pieceSize = 400 / pieces;

  // Shuffle array elements randomly
  function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }

  // Create puzzle pieces
  for (let i = 0; i < pieces; i++) {
    for (let j = 0; j < pieces; j++) {
      const posX = -j * pieceSize;
      const posY = -i * pieceSize;

      const piece = $('<div>')
        .addClass('puzzle-piece')
        .css({
          left: j * pieceSize + 'px',
          top: i * pieceSize + 'px',
          backgroundPosition: posX + 'px ' + posY + 'px',
          backgroundImage: 'url(your-image.jpg)' // Replace with the URL of your image
        });

      $('#puzzleContainer').append(piece);
    }
  }

  // Shuffle the puzzle pieces randomly
  const puzzlePieces = $('.puzzle-piece');
  shuffleArray(puzzlePieces);

  // Add draggable behavior to the pieces
  puzzlePieces.draggable({
    containment: '#puzzleContainer',
    snap: '.puzzle-piece',
    snapMode: 'inner'
  });
});

Make sure to replace 'your-image.jpg' with the URL of the image you want to use for the puzzle. The code above will break the image into pieces, shuffle them randomly, and make them draggable. Users can then drag and drop the pieces to solve the puzzle and reassemble the original image.

This is a simple example, and you can enhance it by adding features like a timer, scoring, or providing feedback when the puzzle is completed.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS