Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Create a Drag and Drop Game

DZone's Guide to

How to Create a Drag and Drop Game

Want to create a drag and drop game? Here's a neat tutorial.

· Performance Zone
Free Resource

Discover 50 of the latest mobile performance statistics with the Ultimate Guide to Digital Experience Monitoring, brought to you in partnership with Catchpoint.

Hi! Today we will create a drag and drop game which uses jQuery drag drop functions. We will create two boxes, from one box we need to drag the content box and drop the same to another box. We will be using sortable function and its events. I hope you will like this game.

Background

For the last Independence day for India, I though to create a game related to the word “INDIA”. I created and hosted it in my website.

Play the Game

You can play the game here: http://sibeeshpassion.com/FindINDIA/

Using the Code

First we will create an html5 page as follows.


<!DOCTYPE html>
<html>
<head>
    <title>Find INDIA Game - Sibeesh Passion</title>   
</head>
<body id="body">
</body>
</html>


And now we will set style to the body. To set the background image fit to the screen we will use the following styles.


 #body {
            background: url("http://sibeeshpassion.com/content/images/indian%20flag%20banner.jpg") no-repeat center center fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
        }


Now we can see page as follows.

Image title


Make Image Fit To The Screen

Since we are going to create a client side game, it is necessary to load the jquery and jquery ui reference.


 <script src="jquery-2.0.2.min.js"></script>
    <script src="jquery-ui.js"></script>


Next we will create the drag able contents as follows.


<div class="dragDiv">
            <div id="dragDivInner">
                <div myid="1" class="droppable" myval="I"></div>
                <div myid="2" class="droppable"></div>
                <div myid="3" class="Notdroppable"></div>
                <div myid="6" class="droppable"></div>
                <div myid="7" class="droppable"></div>
                <div myid="8" class="Notdroppable"></div>
                <div myid="9" class="droppable" myval="N"></div>
                <div myid="10" class="Notdroppable"></div>
                <div myid="11" class="droppable"></div>
                <div myid="12" class="droppable"></div>
                <div myid="17" class="droppable"></div>
                <div myid="18" class="Notdroppable"></div>
                <div myid="19" class="droppable"></div>
                <div myid="20" class="Notdroppable" myval="A"></div>
                <div myid="21" class="droppable"></div>
                <div myid="22" class="droppable"></div>
                <div myid="23" class="Notdroppable"></div>
                <div myid="24" class="droppable"></div>
                <div myid="25" class="Notdroppable" myval="I"></div>
                <div myid="26" class="droppable"></div>
                <div myid="27" class="droppable"></div>
                <div myid="28" class="Notdroppable"></div>
                <div myid="29" class="droppable"></div>
                <div myid="30" class="Notdroppable"></div>
                <div myid="31" class="Notdroppable" myval="D"></div>
                <div myid="32" class="droppable"></div>
                <div myid="33" class="droppable"></div>
                <div myid="34" class="Notdroppable"></div>
                <div myid="35" class="droppable"></div>
                <div myid="40" class="Notdroppable"></div>
            </div>
        </div>


Now we need to set a div where we can drag contents to it.


<div class="dropDiv">
            <div id="draggedContent" style="display: none;"></div>
        </div>


As it is a game, we must set the game rules also right?


<div id="gamerules">
            <ul>
                <li class="caption">Find "INDIA" Game Rules </li>
                <li>You can drag and drop any boxes. </li>
                <li>We have set each letters from "INDIA" in the boxes. It is hidden</li>
                <li>The game is, you need to find out the letters of "INDIA" by drag and drop the boxes to nearest box</li>
                <li>Let us play the game now...</li>
            </ul>
        </div>


And we will set some styles to those elements.


.dropDiv {
            border: 1px solid #ccc;
            width: 25%;
            height: auto;
            padding: 10px;
            display: inline;
            position: absolute;
            margin-left: 5px;
            min-height: 265px;
        }

        .dragDiv {
            border: 1px solid #ccc;
            width: 27%;
            height: auto;
            padding: 10px;
            float: left;
            margin-left: 5px;
            min-height: 265px;
        }

        #parent {
            /*border: 1px solid #ccc;*/
            height: 307px;
            width: 70%;
            padding: 20px;
        }

        .droppable {
            width: 25px;
            height: 28px;
            padding: 5px;
            background-color: green;
            margin: 3px;
            float: left;
            cursor: move;
        }

        .Notdroppable {
            width: 25px;
            height: 28px;
            padding: 5px;
            background-color: red;
            margin: 3px;
            float: left;
        }

        #countdiv {
            margin-top: 10px;
            float: left;
        }

        #gamerules {
            border: 1px solid #ccc;
            width: 250px;
            height: 280px;
            padding: 5px;
            float: right;
            margin-left: 5px;
        }

        .caption {
            list-style: none;
            color: green;
            padding: 5px;
            font-weight: bold;
        }


So our page will look as follows.

Image title

The next thing what we need to do is adding sortable functionality using jquery sortable to the div which has class as dropDiv.


$(".dropDiv").sortable({
                connectWith: '.dropDiv',
                forcePlaceholderSize: true,
                forceHelperSize: true,
                opacity: 0.60,
                placeholder: 'placeholder',
                tolerance: 'touch',
                scroll: false,
                cancel: '.dropDiv',
                start: function (event, ui) {
                },
                stop: function (event, ui) {
                },
                update: function (event, ui) {
                },
                receive: function (event, ui) {
                }
            });


Please be noted that we have given connectWith property as follows to make the drag able div to be dropped only in the div which has class as dropDiv.


connectWith: '.dropDiv'

We have also set the property cancel as follows to make the dropped div not drag able from dropDiv.


cancel: '.dropDiv',

Next we will set draggable for our inner divs.


$('.Notdroppable,.droppable').draggable({
                connectToSortable: '.dropDiv',
                containment: "#dropDiv",
                helper: 'clone',
                revert: 'invalid'
            });


Game Insights

As you can see in the html of the our dragDiv, we have set an attribute myval for some of the div. So what we are going to do is when a user drags a div we will check whether that particular div has that attribute and if it has, user got one letter. In this way user needs to collect 5 letters from the dragDiv.

So in the stop function of sortable we will write some scripts as follows.


stop: function (event, ui) {
                    ++count;
                    if (ui.item.attr('myval')) {
                        $('#draggedContent').show().append(ui.item.attr('myval'));
                    }
                    $(".dragDiv div[myid=" + ui.item.attr('myid') + "]").remove();
                    var res = maxTrial - count;
                    if (res == 0) {
                        $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');
                        $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();
                    } else {
                        $('#countdiv').show().html('You still have ' + res + ' tries');
                    }
                    $('.dropDiv .droppable, .dropDiv .Notdroppable').remove();
                    if ($('#draggedContent').html().length == 5) {
                        alert('You have won the game!!!. Please collect the prize from somewhere ;)');
                        $('#countdiv').show().html('You have won the game!!!. Please collect the prize from somewhere ;)!. Please refresh to start the game again');
                        $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();
                    }


                }

We are checking whether the inner div has a particular attribute as follows and once we find it, we are removing that from dragDiv.


if (ui.item.attr('myval')) {
                        $('#draggedContent').show().append(ui.item.attr('myval'));
                    }
                    $(".dragDiv div[myid=" + ui.item.attr('myid') + "]").remove();

If a user has already got those five letters, we must alert the user right? We will do this validation in stop function.


start: function (event, ui) {
                    if (count > maxTrial) {
                        $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');
                    } else {

                    }
                }

Image title

Image title

If there is no chances left, user will get a message as follows:

Image title

Now what we need to do next? Yes we need to shuffle div contents or elese user may find it easy when the tiles are in same order and in same place.

To shuffle the divs dynamically we will add some scripts as follows.


 var parent = $("#dragDivInner");
            var divs = parent.children();
            while (divs.length) {
                parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
            }

Next we will disable the right click and mouse events as follows.


document.onmousedown = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                return false;
            }
        }
        document.onkeydown = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                return false;
            }
        }
$(document).on("contextmenu", function (e) {
                return false;
            });


We will also disable the F12 key of keyboard.


document.onkeypress = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                return false;
            }
        }


As every game has some settings, we will also give some settings.


 <div id="gameSettings">
        <br />
        Select Game Level : 
        <select id="selectGameLevel">
            <option value="Easy">Easy</option>
            <option value="Medium">Medium</option>
            <option value="Hard">Hard</option>
        </select>
    </div>


And in the drop down option change we will decrease the maximum trials allowed.


 $("#selectGameLevel").change(function (e) {
                var selected = $("#selectGameLevel option:selected").val();
                if (selected == "Easy") {
                    maxTrial = 25;
                } else if (selected == "Medium") {
                    maxTrial = 15;
                } else if (selected == "Hard") {
                    maxTrial = 10;
                }
            });

So our complete page will look like this.

Image title

Our complete code is as follows:

Complete Code


<!DOCTYPE html>
<html>
<head>
    <title>Find INDIA Game - Sibeesh Passion</title>
    <script src="jquery-2.0.2.min.js"></script>
    <script src="jquery-ui.js"></script>
    <style>
        #body {
            background: url("http://sibeeshpassion.com/content/images/indian%20flag%20banner.jpg") no-repeat center center fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
        }

        .dropDiv {
            border: 1px solid #ccc;
            width: 25%;
            height: auto;
            padding: 10px;
            display: inline;
            position: absolute;
            margin-left: 5px;
            min-height: 265px;
        }

        .dragDiv {
            border: 1px solid #ccc;
            width: 27%;
            height: auto;
            padding: 10px;
            float: left;
            margin-left: 5px;
            min-height: 265px;
        }

        #parent {
            /*border: 1px solid #ccc;*/
            height: 307px;
            width: 70%;
            padding: 20px;
        }

        .droppable {
            width: 25px;
            height: 28px;
            padding: 5px;
            background-color: green;
            margin: 3px;
            float: left;
            cursor: move;
        }

        .Notdroppable {
            width: 25px;
            height: 28px;
            padding: 5px;
            background-color: red;
            margin: 3px;
            float: left;
        }

        #countdiv {
            margin-top: 10px;
            float: left;
        }

        #gamerules {
            border: 1px solid #ccc;
            width: 250px;
            height: 280px;
            padding: 5px;
            float: right;
            margin-left: 5px;
        }

        .caption {
            list-style: none;
            color: green;
            padding: 5px;
            font-weight: bold;
        }

        #gameSettings {
            width: auto;
        }
    </style>
    <script>
        var count = 0;
        var maxTrial = 25;
        document.onkeypress = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                return false;
            }
        }
        document.onmousedown = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                return false;
            }
        }
        document.onkeydown = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                return false;
            }
        }
        $(function () {
            $(document).on("contextmenu", function (e) {
                return false;
            });
            var parent = $("#dragDivInner");
            var divs = parent.children();
            while (divs.length) {
                parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
            }
            $("#selectGameLevel").change(function (e) {
                var selected = $("#selectGameLevel option:selected").val();
                if (selected == "Easy") {
                    maxTrial = 25;
                } else if (selected == "Medium") {
                    maxTrial = 15;
                } else if (selected == "Hard") {
                    maxTrial = 10;
                }
            });
            $('.Notdroppable,.droppable').draggable({
                connectToSortable: '.dropDiv',
                containment: "#dropDiv",
                helper: 'clone',
                revert: 'invalid'
            });
            $(".dropDiv").sortable({
                connectWith: '.dropDiv',
                forcePlaceholderSize: true,
                forceHelperSize: true,
                opacity: 0.60,
                placeholder: 'placeholder',
                tolerance: 'touch',
                scroll: false,
                cancel: '.dropDiv',
                start: function (event, ui) {
                    if (count > maxTrial) {
                        $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');
                    } else {

                    }
                },
                stop: function (event, ui) {
                    ++count;
                    if (ui.item.attr('myval')) {
                        $('#draggedContent').show().append(ui.item.attr('myval'));
                    }
                    $(".dragDiv div[myid=" + ui.item.attr('myid') + "]").remove();
                    var res = maxTrial - count;
                    if (res == 0) {
                        $('#countdiv').show().html('Sorry, you have no more chances left!!!. Please refresh to start the game again');
                        $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();
                    } else {
                        $('#countdiv').show().html('You still have ' + res + ' tries');
                    }
                    $('.dropDiv .droppable, .dropDiv .Notdroppable').remove();
                    if ($('#draggedContent').html().length == 5) {
                        alert('You have won the game!!!. Please collect the prize from somewhere ;)');
                        $('#countdiv').show().html('You have won the game!!!. Please collect the prize from somewhere ;)!. Please refresh to start the game again');
                        $('.dragDiv .droppable, .dragDiv .Notdroppable').remove();
                    }


                },
                update: function (event, ui) {
                },
                receive: function (event, ui) {
                }
            });
        });
    </script>
</head>
<body id="body">
    <div id="gameSettings">
        <br />
        Select Game Level : 
        <select id="selectGameLevel">
            <option value="Easy">Easy</option>
            <option value="Medium">Medium</option>
            <option value="Hard">Hard</option>
        </select>
    </div>
    <div id="parent" style="float: left;">
        <div class="dragDiv">
            <div id="dragDivInner">
                <div myid="1" class="droppable" myval="I"></div>
                <div myid="2" class="droppable"></div>
                <div myid="3" class="Notdroppable"></div>
                <div myid="6" class="droppable"></div>
                <div myid="7" class="droppable"></div>
                <div myid="8" class="Notdroppable"></div>
                <div myid="9" class="droppable" myval="N"></div>
                <div myid="10" class="Notdroppable"></div>
                <div myid="11" class="droppable"></div>
                <div myid="12" class="droppable"></div>
                <div myid="17" class="droppable"></div>
                <div myid="18" class="Notdroppable"></div>
                <div myid="19" class="droppable"></div>
                <div myid="20" class="Notdroppable" myval="A"></div>
                <div myid="21" class="droppable"></div>
                <div myid="22" class="droppable"></div>
                <div myid="23" class="Notdroppable"></div>
                <div myid="24" class="droppable"></div>
                <div myid="25" class="Notdroppable" myval="I"></div>
                <div myid="26" class="droppable"></div>
                <div myid="27" class="droppable"></div>
                <div myid="28" class="Notdroppable"></div>
                <div myid="29" class="droppable"></div>
                <div myid="30" class="Notdroppable"></div>
                <div myid="31" class="Notdroppable" myval="D"></div>
                <div myid="32" class="droppable"></div>
                <div myid="33" class="droppable"></div>
                <div myid="34" class="Notdroppable"></div>
                <div myid="35" class="droppable"></div>
                <div myid="40" class="Notdroppable"></div>
            </div>
            <div id="countdiv" style="display: none;"></div>
        </div>
        <div class="dropDiv">
            <div id="draggedContent" style="display: none;"></div>
        </div>
        <div id="gamerules">
            <ul>
                <li class="caption">Find "INDIA" Game Rules </li>
                <li>You can drag and drop any boxes. </li>
                <li>We have set each letters from "INDIA" in the boxes. It is hidden</li>
                <li>The game is, you need to find out the letters of "INDIA" by drag and drop the boxes to nearest box</li>
                <li>Let us play the game now...</li>
            </ul>
        </div>
    </div>
</body>
</html>

Now let us play the game.

Conclusion

I hope you liked my article. Now please share me your feedback. Thanks in advance.

Is your APM strategy broken? This ebook explores the latest in Gartner research to help you learn how to close the end-user experience gap in APM, brought to you in partnership with Catchpoint.

Topics:
performance ,game dev ,web dev ,html5

Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}