Create a Jigsaw Puzzle Using jQuery and PHP

Posted in Coding, JS & AJAX, PHP2 years ago • Written by 16 Comments

Almost everyone, at one point during childhood, has played jigsaw puzzles. Today I am going to show you how to create a jigsaw puzzle using jQuery and PHP.

Lets start creating puzzles. I know that you must be waiting to see the puzzle in action. I am not going to keep you guessing. Here is the sample demo of the puzzle and download of tutorial files.

Now you got your wish. So lets move onto creating the puzzle.

Splitting an Image into Smaller Parts

First thing we have to do is choose an image for the puzzle. Only jpg images can be used in this example. I am going to use the 1stwebdesigner header image for the puzzle. Once you choose the image it has to be split into smaller images to create the puzzle components.

There are a lot of online tools available for splitting images. But I am going to use my own php code to split the image. The purpose of this tutorial is to make the puzzle. So I am not going to explain the whole PHP code for splitting images. I’ll just explain the necessary configurations.

<?php

    $image_file = 'puzzle.jpg';

    $src = imagecreatefromjpeg($image_file);
    list($width, $height, $type, $attr) = getimagesize($image_file);

    $split_size = '150';

    $cal_width  = $width % $split_size;
    $cal_height = $height % $split_size;

    if ($cal_width > 0) {
        $new_width = intval($width / $split_size) * $split_size + 100;
    } else {
        $new_width = $width;
    }
    if ($cal_height > 0) {
        $new_height = intval($height / $split_size) * $split_size + 100;
    } else {
        $new_height = $height;
    }

    if ($width > 1200) {
        $width = 1200;
        $new_width = 1200;
    }

    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($image_file);

    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    imagejpeg($image_p, $image_file, 100);

    $x_comp = intval($new_width / $split_size);
    $y_comp = intval($new_height / $split_size);

    $winning_string = '';
    $image_names = '';

    $src = imagecreatefromjpeg($image_file);
    $dest = imagecreatetruecolor($split_size, $split_size);

    for ($y = 0; $y < $y_comp; $y++) {
        for ($i = 0; $i < $x_comp; $i++) {
            $characters = 'abcdefghijklmnopqrstuvwxyz';
            $ran_string = '';
            for ($p = 0; $p < 4; $p++) {
                $ran_string .= $characters[mt_rand(0, strlen($characters) - 1)];
            }

            imagecopy($dest, $src, 0, 0, $i * $split_size, $y * $split_size, $split_size, $split_size);
            imagejpeg($dest, "images/$ran_string.jpg");

            $winning_string .= $ran_string;
            $image_names .= $ran_string . ",";
        }
    }

    $image_names = substr($image_names, 0, -1);
    $images = explode(',', $image_names);
    shuffle($images);
?>

Code Explanation

  • First you have to provide the name of your image in the $image_file variable. I have used puzzle.jpg as the name and it should be on the same path as the file which contains the above php code.
  • In line 8 you see the variable $split_size. It is defined in pixels and you can change the value if you want. I have used 150. So the image will be split into parts of 150px * 150px images.
  • Also make sure total width and height of your image is a multiple of 150. If it is not a multiple of 150 some parts of the original image will be removed when split.
  • Then in line 54 you should specify a folder for the split images to be stored. I have used the folder name as images.

Now what you have to do is download the tutorial files first. Then copy it to your web server and give necessary permissions to folders. Then open the split.php file and make the changes mentioned above or keep the default values.

Once you execute it in the browser you will get a output like the following.

Puzzle Winning and Load Strings

You should keep both Winning String and Load String as shown in the above screen. Now we are done with the image split. So lets move onto the next section.

Creating the Puzzle Using Jquery

I have already created images for our puzzle in the images folder. Now we have to create the puzzle by loading the puzzle images. Before that we need to enable Drag and Drop support using Jquery UI library. So I’ll show you the necessary files to be included.

I have downloaded and included the necessary files of jQuery UI Library in the tutorial files. You can use the following code to include the files related to our tutorial.

<html lang='en'>
<head>
	<title>Jquery Drag and Drop Puzzle</title>
	<script src="jquery-1.7.2.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.core.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.widget.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.mouse.js" type="text/javascript"></script>
	<script src="ui/jquery.ui.sortable.js" type="text/javascript"></script>
	<link rel="stylesheet" href="demos.css">
</head>
<body>

</body>
</html>

In the code you can see the file called jquery.ui.sortable.js. It is used to handle the drag and drop and then sort the items inside the given container. This is called Sortable in Jquery UI library. Once you make an element sortable, you will be able to both drag and drop items inside that element. You can make item sortable using the following code.

Jquery Code for Making Unordered List Sortable

$("#sortable").sortable();

Unordered List with Items

<ul id='sortable'>
      <li>Item 1</li>
      <li>Item 2</li>
</ul>

Above codes will enable sortable event on all the li items inside the ul container with the id sortable

Basic CSS Styles for Sortable Element

<style type='text/css'>
	#sortable { list-style-type: none; margin: 0; padding: 0; }
	#sortable li { float: left;}
   .msg_text{
            text-align: center;
            padding: 20px;
            font-size: 30px;
            text-shadow: 1px 1px 1px rgb(21, 23, 28);
        }
</style>

Loading Images for the Drag and Drop Puzzle

Puzzle Before Starting

Now I am going to display the image parts as puzzle. We can use the following PHP code with small configurations to load the images. This code is located in puzzle.php file on the project folder. You can run the puzzle.php file in your web server to directly execute the demo. Now get ready with the Winning String we created earlier.

<?php
            $image_names = "ilsc,scmz,lsea,derv,logi,eyen,vkxl,ihrx,mwgc,bwdk,rfwb,oezh";
            $images = explode(',', $image_names);
            shuffle($images);

            $new_width = "900";
            $new_height= "300";
	    $split_size= "150";

            echo "<ul id='sortable' style='width:" . $new_width . "px;height:" . $new_height . "px;'>";

            foreach ($images as $key => $image_name) {
                echo "<li class='ui-state-default' id='recordArr_$image_name' style='width:" . $split_size . "px;height:" . $split_size . "px;'>
                            <img src='images/$image_name.jpg' /></li>";
            }

            echo "</ul>";
        ?>

Code Explanation

  • First enter the Load String we generated earlier into the variable called $image_names. Keep it as it is if you are going to use the default demo.
  • Each time you change the image of your puzzle and split it with the split.php file, you have to assign the Load String here.
  • Then we have variables called $new_width and $new_height. These values should be defined according to the number of parts in your puzzle.
  • We created 150px * 150px images and we have 6 images horizontally since original image I used was 900*300px. So $new_width should be 150*6 = 900. Also we have 2 images vertically. So $new_height should be 150*2 = 300. Configure those values according to size of your image. Also $split_size is set to 150 since we are using 150*150 images.
  • Then we load all the images for the puzzle inside unordered list. You don’t have to do anything there.
  • Now we have completed displaying the puzzle images.


You can see the puzzle on your screen and try to drag and drop images. You must be wondering why the puzzle is not working. That’s because we haven’t made the puzzle sortable yet. That’s where the magic happens. So lets make it sortable.

Making the Puzzle Sortable

Puzzle After Starting

Include the following code snippet on the head section of your document after the js and css files.

         <script type="text/javascript">
            $(function() {
                $("#sortable").sortable({
                    opacity: 0.6,
                    cursor: 'move',
                    update: function() {

                    }
                });

            });
        </script>

Now you can drag and drop the images and you will be able to see that images are changing in the puzzle. But there is no way you can check whether puzzle is solved or not unless its a very simple one. So now I am going to tell you how to check whether puzzle is solved using a very simple method.

Identify the Winning Moment

Winning Moment of Puzzle

Here is the code that will notify you when the puzzle is solved. Include it inside the update function of the code we created in the previous section

         <script type="text/javascript">
            $(function() {
                $("#sortable").sortable({
                    opacity: 0.6,
                    cursor: 'move',
                    update: function() {
                        var winningString = "oezh,rfwb,lsea,vkxl,ihrx,ilsc,eyen,mwgc,derv,logi,bwdk,scmz";
                        var currentString = '';

                        $('#sortable li').each(function(){
                            var imageId = $(this).attr("id");
                            currentString += imageId.replace("recordArr_", "")+",";
                        });

                        currentString = currentString.substr(0,(currentString.length) -1);

                        if(currentString == winningString){
                            alert("You  Won");
                        }
                    }
                });

            });
        </script>

Code Explanation

  • Each time you move an item in the puzzle the update function will be executed.
  • First insert the Winning String we got earlier when creating images, into winningString variable.
  • Then the code will get the current positions of the images in the puzzle and creates a string with current item order.
  • Next we check whether current string matches the winning string and displays the winning message.


We have completed our tutorial on creating puzzles and now you can enjoy creating and solving puzzles.

Bonus Tip

Have you tried fixing the puzzle yet ?

You might have done it pretty easily since only 12 parts are available in the demo. But when the number of parts increases it will be very difficult unless you find out the correct method.

If you are a designer or developer who has knowledge in working with HTML DOM, you will be able to find the correct method. Drag and drop images a few times and see how the images are positioning. Then try to match that with how the HTML DOM works when you add and remove elements dynamically. I am sure that you will be able to figure it out.

So you can learn about the DOM while having fun with fixing puzzles. Let me know if you figure it out using the comments section.

Whats Next?

Now we have completed creating a basic puzzle using jQuery drag and drop features. What we did was manually create image parts using some php code and including those parts of the puzzle. You can extend this by allowing users to upload images and create the image parts dynamically. Then allow the users to select the puzzle from a dropdown and fix it. So you will be able to create puzzles out of any image.

Sounds good right ? Here is some more functionality you can include in your puzzle.

1. Assign a time to fix the puzzle in a given time period using javascript setTimeout function.

Puzzle with Time

2.Save image names in a database table with correct order and provide a score on how many parts have been completed inside the given time.

Display Puzzle Score

You can extend these features and create a puzzle site for users very easily. Let me know if you have any questions regarding using these puzzles or extending features. Use the instructions in the project files to execute the demo properly. Hope to hear from you.

22 Written ArticlesWebsiteGoogle+

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on WordPress Web Application Development. He is a regular contributor to 1stWebDesigner, Tuts+ network and Sitepoint network. Make sure to contact him at www.innovativephp.com or follow him on Twitter and Google+

16 Comments Best Comments First
  • Jason Webb

    Wednesday, June 6th, 2012 10:01

    4

    Very cool tutorial, thanks. Shared it and gave a link to here.

    +2
    • Dainis Graveris

      Wednesday, June 6th, 2012 12:00

      6

      Jason, do you know it’s illegal to republish other blog content? You can use excerpt and featured image max, but not copy whole article on your own blog post. Please remove it or I will report that post.

      If you didn’t know that, just letting you know, but it is the same as stealing.

      -5
  • Adina

    Tuesday, June 12th, 2012 05:49

    8

    you did excellent work and useful for me as newbie in jquery tutorial.

    +1
    • Dainis Graveris

      Tuesday, June 12th, 2012 07:48

      9

      Thanks! :) I hope you’ll find where to implement it :) Oh and one request, please use your real name in comments otherwise I won’t be able to accept your comment. Now I changed it to one of your team names since I couldn’t find any name in your site about me section.

      +1
  • Rochester Oliveira

    Tuesday, June 5th, 2012 13:57

    1

    Great tutorial!

    Loved the idea since I saw the very first pitch of yours, but the final result is much better than I could imagine.

    []‘s

    0
    • Rakhitha Nimesh

      Wednesday, June 6th, 2012 00:40

      2

      Thanks Rochester for your comment.

      0
  • Manuel Garcia

    Wednesday, June 6th, 2012 08:47

    3

    This is fantastic. I tried to complete the puzzle of 1WD, and I have won :)

    0
    • Dainis Graveris

      Wednesday, June 6th, 2012 11:57

      5

      Hehe, congratulations Manuel! :) I feel like it still can be improved to avoid some little bugs, but awesome for some kind of marketing promotion!

      -1
  • Andrej Badin

    Saturday, June 9th, 2012 08:01

    7

    Realy nice tutorial! But I find PHP part redundant. This could be done purely in JS/jQuery.

    0
  • John

    Wednesday, August 1st, 2012 06:36

    15

    Very nice puzzle idea! How would i set up so the puzzle has a timer til you complete it and then it allows you to post results on facebook?

    0
  • Pamela

    Thursday, July 19th, 2012 16:26

    13

    Hello there it is really an amazing puzzle I need to redo it for children class as competition how can I make the swith the piece that you are holding, with the one in the place you drop, would you help me with this code. i need something very very easy for them. Thank you so much

    0
    • Rakhitha Nimesh

      Saturday, July 21st, 2012 02:40

      14

      Hi Pamela

      I would love to make this puzzle for children. But I have to change everything inorder to make 2 images switch its places instead of current behavior. so it will take some time.

      By the way what is the age group children that you planning this puzzle to be given ?

      -1
      • John

        Thursday, August 2nd, 2012 22:43

        16

        Im interested in this as well could you email me on how to do it cheers

        0
  • Gabriel

    Friday, June 29th, 2012 12:21

    11

    Its really cool.
    The only thing that is annoying, is when you place a piece in the up row, it moves all the content.
    Maybe you should swith the piece that you are holding, with the one in the place you drop to avoid this.

    -1
    • Rakhitha Nimesh

      Monday, July 2nd, 2012 23:13

      12

      Thanks for the Comment

      I agree with you about moving all the pieces when you move one. I did it purposely since otherwise it would be very easy. Now we have to find why its moving such a way, in order solve the puzzle. When you find the method it would be very easy. Think about HTML DOM.

      -2
  • Annie

    Thursday, June 21st, 2012 14:15

    10

    Very cool puzzle. It’s a new take on the jigsaw puzzle. As a webmaster, I would pay for a completed puzzle script like this.

    -1
  • John

    Wednesday, August 1st, 2012 06:36

    15

    Very nice puzzle idea! How would i set up so the puzzle has a timer til you complete it and then it allows you to post results on facebook?

    0
  • Pamela

    Thursday, July 19th, 2012 16:26

    13

    Hello there it is really an amazing puzzle I need to redo it for children class as competition how can I make the swith the piece that you are holding, with the one in the place you drop, would you help me with this code. i need something very very easy for them. Thank you so much

    0
    • Rakhitha Nimesh

      Saturday, July 21st, 2012 02:40

      14

      Hi Pamela

      I would love to make this puzzle for children. But I have to change everything inorder to make 2 images switch its places instead of current behavior. so it will take some time.

      By the way what is the age group children that you planning this puzzle to be given ?

      -1
      • John

        Thursday, August 2nd, 2012 22:43

        16

        Im interested in this as well could you email me on how to do it cheers

        0
  • Gabriel

    Friday, June 29th, 2012 12:21

    11

    Its really cool.
    The only thing that is annoying, is when you place a piece in the up row, it moves all the content.
    Maybe you should swith the piece that you are holding, with the one in the place you drop to avoid this.

    -1
    • Rakhitha Nimesh

      Monday, July 2nd, 2012 23:13

      12

      Thanks for the Comment

      I agree with you about moving all the pieces when you move one. I did it purposely since otherwise it would be very easy. Now we have to find why its moving such a way, in order solve the puzzle. When you find the method it would be very easy. Think about HTML DOM.

      -2
  • Annie

    Thursday, June 21st, 2012 14:15

    10

    Very cool puzzle. It’s a new take on the jigsaw puzzle. As a webmaster, I would pay for a completed puzzle script like this.

    -1
  • Adina

    Tuesday, June 12th, 2012 05:49

    8

    you did excellent work and useful for me as newbie in jquery tutorial.

    +1
    • Dainis Graveris

      Tuesday, June 12th, 2012 07:48

      9

      Thanks! :) I hope you’ll find where to implement it :) Oh and one request, please use your real name in comments otherwise I won’t be able to accept your comment. Now I changed it to one of your team names since I couldn’t find any name in your site about me section.

      +1
  • Andrej Badin

    Saturday, June 9th, 2012 08:01

    7

    Realy nice tutorial! But I find PHP part redundant. This could be done purely in JS/jQuery.

    0
  • Jason Webb

    Wednesday, June 6th, 2012 10:01

    4

    Very cool tutorial, thanks. Shared it and gave a link to here.

    +2
    • Dainis Graveris

      Wednesday, June 6th, 2012 12:00

      6

      Jason, do you know it’s illegal to republish other blog content? You can use excerpt and featured image max, but not copy whole article on your own blog post. Please remove it or I will report that post.

      If you didn’t know that, just letting you know, but it is the same as stealing.

      -5
  • Manuel Garcia

    Wednesday, June 6th, 2012 08:47

    3

    This is fantastic. I tried to complete the puzzle of 1WD, and I have won :)

    0
    • Dainis Graveris

      Wednesday, June 6th, 2012 11:57

      5

      Hehe, congratulations Manuel! :) I feel like it still can be improved to avoid some little bugs, but awesome for some kind of marketing promotion!

      -1
  • Rochester Oliveira

    Tuesday, June 5th, 2012 13:57

    1

    Great tutorial!

    Loved the idea since I saw the very first pitch of yours, but the final result is much better than I could imagine.

    []‘s

    0
    • Rakhitha Nimesh

      Wednesday, June 6th, 2012 00:40

      2

      Thanks Rochester for your comment.

      0

Comments are closed.

54.197.94.141 - unknown - unknown - US