A Drag And Drop Game
[toc]
Introduction
In this post, 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 into 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.
Using the code
First we will create an html5 page as follows.
[html]
<!DOCTYPE html>
<html>
<head>
<title>Find INDIA Game – Sibeesh Passion</title>
</head>
<body id=”body”>
</body>
</html>
[/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.
[css]
#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;
}
[/css]
Now we can see page as follows.
Since we are going to create a client side game, it is necessary to load the jquery and jquery ui reference.
[js]
<script src=”jquery-2.0.2.min.js”></script>
<script src=”jquery-ui.js”></script>
[/js]
Next we will create the drag able contents as follows.
[html]
<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>
[/html]
Now we need to set a div where we can drag contents to it.
[html]
<div class=”dropDiv”>
<div id=”draggedContent” style=”display: none;”></div>
</div>
[/html]
As it is a game, we must set the game rules also right?
[html]
<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>
[/html]
And we will set some styles to those elements.
[css]
.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;
}
[/css]
So our page will look like as follows.
The next thing what we need to do is adding sortable functionality using jquery sortable to the div which has class as dropDiv.
[js]
$(“.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) {
}
});
[/js]
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.
[js]
connectWith: ‘.dropDiv’
[/js]
We have also set the property cancel as follows to make the dropped div not drag able from dropDiv.
[js]
cancel: ‘.dropDiv’,
[/js]
Next we will set draggable for our inner divs.
[js]
$(‘.Notdroppable,.droppable’).draggable({
connectToSortable: ‘.dropDiv’,
containment: “#dropDiv”,
helper: ‘clone’,
revert: ‘invalid’
});
[/js]
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.
[js]
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();
}
}
[/js]
We are checking whether the inner div has a particular attribute as follows and once we find it, we are removing that from dragDiv.
[js]
if (ui.item.attr(‘myval’)) {
$(‘#draggedContent’).show().append(ui.item.attr(‘myval’));
}
$(“.dragDiv div[myid=” + ui.item.attr(‘myid’) + “]”).remove();
[/js]
If a user has already got those five letters, we must alert the user right? We will do this validation in stop function.
[js]
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 {
}
}
[/js]
If there is no chances left, user will get a message as follows.
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.
[js]
var parent = $(“#dragDivInner”);
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
[/js]
Next we will disable the right click and mouse events as follows.
[js]
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;
});
[/js]
We will also disable the F12 key of keyboard.
[js]
document.onkeypress = function (event) {
event = (event || window.event);
if (event.keyCode == 123) {
return false;
}
}
[/js]
As every game has some settings, we will also give some settings.
[html]
<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>
[/html]
And in the drop down option change we will decrease the maximum trials allowed.
[js]
$(“#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;
}
});
[/js]
So our complete page will look like this.
Our complete code is as follows.
Complete Code
[html]
<!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>
[/html]
Conclusion
Thanks a lot for reading. Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.
Your turn. What do you think?
A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.
Kindest Regards
Sibeesh Venu