Introduction

This is a simple puzzle game developed using pure HTML and jQuery. This puzzle consist of an image which is divided into fifteen small parts or we can say it as segments. These parts are randomly arranged on the puzzle board. Your task is you have to rearrange that image segments in proper order. There is no limitations for moves or time you can take your own time to complete this puzzle.

Background

This puzzle game is mainly based on swapping of div’s on puzzle board, Puzzle board consist of total 16 small div’s, 15 are image div’s and one empty div. Div position is set on the puzzle board on random basis. When you click on any div adjacent to the empty div position of selected div and empty div gets changed.

Check Live Demo Here : jQuery Puzzle Game



Code

To swap clicked square and the current empty square, I have wrote below function which will swap position of these divs or segments using left and top co-ordinates.



function Move(clicked_square, square_size) { var ismovable = false; // Swap x/y between the clicked square and the currently empty square var oldx = $('#board').children("div:nth-child(" + EmptySquare + ")").css('left'); var oldy = $('#board').children("div:nth-child(" + EmptySquare + ")").css('top'); var newx = $(clicked_square).css('left'); var newy = $(clicked_square).css('top'); // The clicked square is north of the empty square if (oldx == newx && newy == (parseInt(oldy) - square_size) + 'px') ismovable = true; // The clicked square is south of the empty square if (oldx == newx && newy == (parseInt(oldy) + square_size) + 'px') ismovable = true; // The clicked square is west of the empty square if ((parseInt(oldx) - square_size) + 'px' == newx && newy == oldy) ismovable = true; // The clicked square is east of the empty square if ((parseInt(oldx) + square_size) + 'px' == newx && newy == oldy) ismovable = true; if (ismovable) { // Increment zindex so the new tile is always on top of all others $(clicked_square).css('z-index', zi++); // Swap squares... Animate new square into old square position $(clicked_square).animate({ left: oldx, top: oldy }, 200, function() { //Move old square into new square position $('#board').children("div:nth-child(" + EmptySquare + ")").css('left', newx); $('#board').children("div:nth-child(" + EmptySquare + ")").css('top', newy); }); } }

HTML page code is below.

<html> <head> <title>jQuery Puzzle Game Demo</title> <link href="main.css" rel="stylesheet" type="text/css" /> <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="main.js"></script> </head> <body> <div id="PuzzleDiv" style="border:1px solid black"> <div id="game_object"></div> </div> <input id="button" type="button" value="button"></input> <script> $('#button').click(function () { $("#game_object").randomize(); }); </script> </body> </html>

Download