Introduction
This is a simple puzzle game developed using pure HTML and jQuery. This puzzle consists of an image which is divided into fifteen small parts or we could call them segments. These parts are randomly arranged on the puzzle board. Your task isthat you have to rearrange the image segments in proper order. There are 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 divs on puzzle board, Puzzle board consist s of a total of 16 small divs, 15 image divs 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.
Code
To swap clicked square and the current empty square, I have written the below function which will swap the position of these divs or segments using left and top co-ordinates.
-
- function Move(clicked_square, square_size) {
- var ismovable = false;
-
-
- 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');
-
-
- if (oldx == newx && newy == (parseInt(oldy) - square_size) + 'px')
- ismovable = true;
-
-
- if (oldx == newx && newy == (parseInt(oldy) + square_size) + 'px')
- ismovable = true;
-
-
- if ((parseInt(oldx) - square_size) + 'px' == newx && newy == oldy)
- ismovable = true;
-
-
- if ((parseInt(oldx) + square_size) + 'px' == newx && newy == oldy)
- ismovable = true;
-
- if (ismovable) {
-
- $(clicked_square).css('z-index', zi++);
-
-
- $(clicked_square).animate({ left: oldx, top: oldy }, 200, function() {
-
- $('#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="board"></div>
- </div> <input id="button" type="button" value="Start Again"></input>
- <script>
- $('#button').click(function ()
- {
- $("#board").randomize();
- });
- </script>
- </body>
-
- </html>
CSS used for this puzzle:
- #game_object {
- background-color: #ffffff;
- }
- #PuzzleDiv {
- position:fixed;
- top: 15%;
- left: 35%;
- height: 403px;
- width: 403px;
- padding:2px;
- }
I hope you enjoyed reading this article. So keep reading and don’t forget to post your valuable feedback.