Click here to Skip to main content
14,355,397 members

Image Puzzle: An HTML Game

Rate this:
4.88 (87 votes)
Please Sign up or sign in to vote.
4.88 (87 votes)
19 Aug 2019CPOL
An HTML 2D game to describe some basic game development tips in HTML/CSS and JavaScript.

Introduction

This is the article for beginners who want to start the game development in web with some simple approach and without using any heavy tools. This article provides simplified steps to start with the 2D game development using HTML/CSS and JavaScript. Here, I am presenting how to create an Image Puzzle game where you can drag and drop image parts to swap and re-arrange the parts to form the complete image. Now, we have plain JavaScript version also for the same game in GitHub.

You can play the game online here.

Rules

The rules of the game are simple. You just need to drag and drop the broken image pieces to swap it. You need to swap them in a way that it forms the correct image. The number of steps taken to drag and drop the image parts will be counted. So, you may wish to think and try to do it in minimum possible steps. The correct image is provided at the right hand side for your reference.

The screen for the game looks like this:

Image Puzzle

Image Puzzle: Solved

About the Code

To understand it, we can divide the code in 3 parts. HTML, CSS and JavaScript. HTML part contains simple tags to form the layout of the game. CSS provides a bit of responsive design and JavaScript part contains the main logic of the game. Few of the important steps of the game are as follows:

Breaking the Images

For images to look like broken into nxn different parts, where n is the number of parts each side, nxn li element has been used in a ul. The display property of each li has been set to inline-block so that it should appear like a grid. The background image of each li has been set to display 1/(nxn)th part of the image only and position of the background image has been set accordingly. data-value attribute has been assigned to each li to identify the index of the piece.

The code for the same looks like this:

setImage: function (images, gridSize) {
    console.log(gridSize);
    gridSize = gridSize || 4; // If gridSize is null or not passed, default it as 4.
    console.log(gridSize);
    var percentage = 100 / (gridSize - 1);
    var image = images[Math.floor(Math.random() * images.length)];
    $('#imgTitle').html(image.title);
    $('#actualImage').attr('src', image.src);
    $('#sortable').empty();
    for (var i = 0; i < gridSize * gridSize; i++) {
        var xpos = (percentage * (i % gridSize)) + '%';
        var ypos = (percentage * Math.floor(i / gridSize)) + '%';
        var li = $('<li class="item" data-value="' + (i) + '"></li>').css({
            'background-image': 'url(' + image.src + ')',
            'background-size': (gridSize * 100) + '%',
            'background-position': xpos + ' ' + ypos,
            'width': 400 / gridSize,
            'height': 400 / gridSize
        });
        $('#sortable').append(li);
    }
    $('#sortable').randomize();
}

Here, you can see that broken effect is achieved using simple background-image and background-position styles. After the broken images have been set, in the right order, randomize method is used to randomize the pieces. In the game, user has to re-arrange the pieces to form the complete image.

The gridSize indicates that how many parts the image needs to be broken each side (horizontally as well as vertically). The hard-coded value 400 is the size of the box. Please note that you might want to get rid of this hard coded value. I will update this with a variable in my next update. Based on gridSize, I have divided the level of puzzle into 3 parts: easy, medium and hard. Easy being 3x3 grid, medium 4x4 and hard 5x5. You may implement the same in a different way just by changing the value of the corresponding radio button.

Randomizing the Broken Parts

After setting up the images' broken parts, as you can see in the last line of the previous code block, randomize method is used to randomize the broken pieces. For this, a small generic randomize function is created to randomize any jquery element collection.

The implementation of randomize method is as follows:

$.fn.randomize = function (selector) {
    var $elems = selector ? $(this).find(selector) : $(this).children(),
        $parents = $elems.parent();

    $parents.each(function () {
        $(this).children(selector).sort(function () {
            return Math.round(Math.random()) - 0.5;
        }).remove().appendTo(this);
    });
    return this;
}; 

Here, we are simply looping through each child element of the given selector and changing its position based on a random number. The random number should be between 0 and the number of elements in collection.

Drag and Drop of Pieces

To make each broken piece draggable, jquery draggable has been used. Please make sure that jquery-ui.js is included in your page to implement draggable/droppable functionality.

enableSwapping: function (elem) {
        $(elem).draggable({
            snap: '#droppable',
            snapMode: 'outer',
            revert: "invalid",
            helper: "clone"
        });
        $(elem).droppable({
            drop: function (event, ui) {
                var $dragElem = $(ui.draggable).clone().replaceAll(this);
                $(this).replaceAll(ui.draggable);

                currentList = $('#sortable > li').map(function (i, el) { 
                    return $(el).attr('data-value'); });
                if (isSorted(currentList))
                    $('#actualImageBox').empty().html($('#gameOver').html());

                imagePuzzle.enableSwapping(this);
                imagePuzzle.enableSwapping($dragElem);
            }
        });
    }   

As you can see in the above code snippet, after each drop, isSorted is being called to check whether the pieces have been sorted or not. Sorting of each piece is being checked based on the data-value attribute of the containing li element. If the pieces are sorted, it means the picture is complete.

Setting Up the Styles

A very minimum CSS has been used to make it simple to understand. The used CSS allows the page to be responsive and you can play the game in your tablet or mobile also. No third party library for CSS has been used so that you can understand the native CSS styling easily.

Counting the Steps

Counting the steps or any user action is the most common part of any game. Here too, it has been implemented with a simple step. After each drop, it checks if the picture is formed. If yes, the game is over and if no, increment the stepCount variable by 1. Then, update the stepCount in UI using jquery.

Timer

Timer is also one of the important parts of most games. Based on the feedback provided by the readers, a basic timer has been implemented to check the number of seconds it takes to complete the puzzle. The timer is being started at the start of the game and will call tick method every second to update the timer. Tick method is once called from the start method and then calls to itself after each second (using JavaScript SetTimeout) recursively and update the time elapsed in the UI using JQuery. When the picture is completed, i.e., the game is over, final time-taken is calculated and shown at the output using JQuery.

Below is the implementation of timer method.
tick: function () {
     var now = new Date().getTime();
     var elapsedTime = parseInt((now - imagePuzzle.startTime) / 1000, 10);
     $('#timerPanel').text(elapsedTime);
     timerFunction = setTimeout(imagePuzzle.tick, 1000);
 }

Please note that the getTime() method gives the number of milli-seconds passed since 01/01/1970. I would welcome if you would suggest the better way to calculate the time between two DateTimes in JavaScript. I would not like to rely on 1000 milli-second gap in setTimeout() to increment to 1 second.

Levels

Based on the feedback given by users, 3 difficulty levels have been added in the game:

  1. Easy
  2. Medium
  3. Hard

In our example, choosing easy sets the puzzle in 3x3 matrix, medium in 4x4 matrix and hard is set to 5x5 matrix.

Browser Compatibility

I have avoided using HTML 5 or CSS 3 for the sake of simplicity so that it can work in most of the browsers. This game may not work for older browsers < IE11 due to the latest JavaScript code used. If you wish to use this game in older browser versions too, you may simply replace the script reference to the older JQuery version (1.9 or earlier). The latest JQuery version doesn't support older browser.

The attached sample code should work in most of the latest browsers. I have tested it in IE 11 and Google Chrome.

Future Consideration

Well, it is an article for beginners who want to start with game development with a simple approach. In future, I will implement and demonstrate the sound effects and a bit of animations too to make it more dynamic. You may also wish to consider to implement the timer and time-taken to complete the picture. For now, enjoy playing the game. Any suggestions to improve the game are welcome.

History

  • Aug 29, 2014: First version release
  • Feb 08, 2015: Update: Added difficulty level based on the number of broken parts. Based on feedback by user.
  • Mar 12, 2017: Added project to github and other minor updates
  • May 13, 2019: Added plain JavaScript version GitHub link

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Anurag Gandhi
Architect
India India
Anurag Gandhi is a Developer, Consultant, Architect, Blogger, Speaker and a Microsoft Employee. He is passionate about programming.
He is extensively involved in Asp.Net Core, MVC/Web API, Microsoft Azure/Cloud, web application hosting/architecture, Angular, AngularJs, design and development. His languages of choice are C#, Node/Express, JavaScript, Asp .NET MVC, Asp, C, C++. He is familiar with many other programming languages as well. He mostly works with MS Sql Server as the preferred database and has worked with Redis, MySQL, Oracle, MS Access, etc. also.
He is active in programming communities and loves to share the knowledge with others whenever he gets the time for it.
He is also a passionate chess player.
Linked in Profile: https://in.linkedin.com/in/anuraggandhi
He can be contacted at: soft.gandhi@gmail.com

Disclaimer: Any posts, article, content present in this website is my personal opinion based on best of my knowledge and experience. None of the content provided by me should be considered as official communication/opinion or my Employer.

Comments and Discussions

 
SuggestionA little bug Pin
tal_segal25-Aug-19 4:58
membertal_segal25-Aug-19 4:58 
AnswerRe: A little bug Pin
Anurag Gandhi4-Nov-19 14:28
professionalAnurag Gandhi4-Nov-19 14:28 
GeneralMy vote of 5 Pin
Hyder1423-Aug-19 0:13
memberHyder1423-Aug-19 0:13 
AnswerRe: My vote of 5 Pin
Anurag Gandhi4-Nov-19 14:27
professionalAnurag Gandhi4-Nov-19 14:27 
BugNice one, thanks a lot Pin
AndreS_7522-Aug-19 0:49
memberAndreS_7522-Aug-19 0:49 
AnswerRe: Nice one, thanks a lot Pin
Anurag Gandhi4-Nov-19 14:26
professionalAnurag Gandhi4-Nov-19 14:26 
PraiseHTML Game Pin
Regina Hawk19-Aug-19 22:11
memberRegina Hawk19-Aug-19 22:11 
AnswerRe: HTML Game Pin
Anurag Gandhi4-Nov-19 14:23
professionalAnurag Gandhi4-Nov-19 14:23 
PraiseThanks for this awesome puzzle Pin
Member 133556552-Jul-19 20:35
memberMember 133556552-Jul-19 20:35 
AnswerRe: Thanks for this awesome puzzle Pin
Anurag Gandhi19-Jul-19 20:28
professionalAnurag Gandhi19-Jul-19 20:28 
GeneralMy vote of 5 Pin
Country Man14-May-19 2:25
memberCountry Man14-May-19 2:25 
AnswerRe: My vote of 5 Pin
Anurag Gandhi16-May-19 3:03
professionalAnurag Gandhi16-May-19 3:03 
Questiongeneral information Pin
Member 1395546520-Aug-18 7:49
memberMember 1395546520-Aug-18 7:49 
AnswerRe: general information Pin
Anurag Gandhi13-May-19 19:36
professionalAnurag Gandhi13-May-19 19:36 
QuestionTo create a Game for offline Pin
Member 135555763-Dec-17 22:30
memberMember 135555763-Dec-17 22:30 
AnswerRe: To create a Game for offline Pin
OriginalGriff3-Dec-17 22:31
protectorOriginalGriff3-Dec-17 22:31 
QuestionNot working on mobile browser Pin
jafaruddeen7-Aug-17 20:15
memberjafaruddeen7-Aug-17 20:15 
AnswerRe: Not working on mobile browser Pin
Anurag Gandhi12-May-19 20:09
professionalAnurag Gandhi12-May-19 20:09 
QuestionThanks for this very nice game, and a wish Pin
Ernst Sauer21-Mar-17 1:56
memberErnst Sauer21-Mar-17 1:56 
Questionuse as a captcha type element Pin
c_becker16-Sep-16 4:37
memberc_becker16-Sep-16 4:37 
AnswerRe: use as a captcha type element Pin
Anurag Gandhi16-Sep-16 8:44
professionalAnurag Gandhi16-Sep-16 8:44 
GeneralMy vote of 5 Pin
Woody D14-Sep-16 1:30
memberWoody D14-Sep-16 1:30 
AnswerRe: My vote of 5 Pin
Anurag Gandhi14-Sep-16 8:00
professionalAnurag Gandhi14-Sep-16 8:00 
QuestionStop image change on level Pin
Woody D14-Sep-16 1:47
memberWoody D14-Sep-16 1:47 
AnswerRe: Stop image change on level Pin
Anurag Gandhi16-Sep-16 8:48
professionalAnurag Gandhi16-Sep-16 8:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 28 Aug 2014

Stats

162.8K views
9.4K downloads
119 bookmarked