Sibeesh Passion

Top Menu

  • Home
  • Search
  • About
  • Privacy Policy

Main Menu

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Home
  • Search
  • About
  • Privacy Policy

logo

Sibeesh Passion

  • Articles
    • Azure
    • .NET
    • IoT
    • JavaScript
    • Career Advice
    • Interview
    • Angular
    • Node JS
    • JQuery
    • Knockout JS
    • Jasmine Framework
    • SQL
    • MongoDB
    • MySQL
    • WordPress
  • Contributions
    • Medium
    • GitHub
    • Stack Overflow
    • Unsplash
    • ASP.NET Forum
    • C# Corner
    • Code Project
    • DZone
    • MSDN
  • Social Media
    • LinkedIn
    • Facebook
    • Instagram
    • Twitter
  • YouTube
    • Sibeesh Venu
    • Sibeesh Passion
  • Awards
  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment

  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins

  • Post Messages to Microsoft Teams Using Python

  • Get Azure Blob Storage Blob Metadata Using PowerShell

  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines

CodeProjectJavaScriptJQuery
Home›CodeProject›A Drag And Drop Game

A Drag And Drop Game

By SibeeshVenu
August 20, 2015
1282
0
Share:
Make Image Fit To The Screen

[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.

Make Image Fit To The Screen

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.

[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.

Drag And Drop Game

Drag And Drop Game

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]

Drag And Drop Game

Drag And Drop Game

Drag And Drop Game

Drag And Drop Game

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

Drag And Drop Game

Drag And Drop Game

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.

Drag And Drop Game

Drag And Drop Game

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

TagsDrag And Drop GameJQueryJQuery DragJQuery Dropjquery functions
Previous Article

Merge Multiple Arrays To One

Next Article

Using Spire.PDF In Asp.Net

0
Shares
  • 0
  • +
  • 0
  • 0
  • 0

SibeeshVenu

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer.

Related articles More from author

  • HTML5

    Client Side Chart Widget in HTML5: Part 6 (Radar Chart)

    January 29, 2015
    By SibeeshVenu
  • HighChart

    Working With Charts

    April 29, 2015
    By SibeeshVenu
  • Code SnippetsJQuery

    Check whether an array element is undefined or not in jQuery

    May 31, 2015
    By SibeeshVenu
  • Code SnippetsJQuery

    Find and set checked true and call click event dynamically

    May 31, 2015
    By SibeeshVenu
  • Check for any unsaved changes in page
    CodeProjectHTMLHTML5JQuery

    Check for any unsaved changes in page

    September 29, 2015
    By SibeeshVenu
  • Merge Multiple Arrays To One
    CodeProjectJQuery

    Merge Multiple Arrays To One

    August 18, 2015
    By SibeeshVenu
0

My book

Asp Net Core and Azure with Raspberry Pi Sibeesh Venu

YouTube

MICROSOFT MVP (2016-2022)

profile for Sibeesh Venu - Microsoft MVP

Recent Posts

  • Linux Azure Function Isolated Dot Net 9 YAML Template Deployment
  • Build, Deploy, Configure CI &CD Your Static Website in 5 mins
  • Easily move data from one COSMOS DB to another
  • .NET 8 New and Efficient Way to Check IP is in Given IP Range
  • Async Client IP safelist for Dot NET
  • Post Messages to Microsoft Teams Using Python
  • Get Azure Blob Storage Blob Metadata Using PowerShell
  • Deploy .net 6 App to Azure from Azure DevOps using Pipelines
  • Integrate Azure App Insights in 1 Minute to .Net6 Application
  • Azure DevOps Service Connection with Multiple Azure Resource Group

Tags

Achievements (35) Angular (14) Angular 5 (7) Angular JS (15) article (10) Article Of The Day (13) Asp.Net (14) Azure (65) Azure DevOps (10) Azure Function (10) Azure IoT (7) C# (17) c-sharp corner (13) Career Advice (11) chart (11) CSharp (7) CSS (7) CSS3 (6) HighChart (10) How To (9) HTML5 (10) HTML5 Chart (11) Interview (6) IoT (11) Javascript (10) JQuery (82) jquery functions (9) JQWidgets (15) JQX Grid (17) Json (7) Microsoft (8) MVC (20) MVP (9) MXChip (7) News (18) Office 365 (7) Products (10) SQL (20) SQL Server (15) Visual Studio (10) Visual Studio 2017 (7) VS2017 (7) Web API (12) Windows 10 (7) Wordpress (9)
  • .NET
  • Achievements
  • ADO.NET
  • Android
  • Angular
  • Arduino
  • Article Of The Day
  • ASP.NET
  • Asp.Net Core
  • Automobile
  • Awards
  • Azure
  • Azure CDN
  • azure devops
  • Blockchain
  • Blog
  • Browser
  • C-Sharp Corner
  • C#
  • Career Advice
  • Code Snippets
  • CodeProject
  • Cognitive Services
  • Cosmos DB
  • CSS
  • CSS3
  • Data Factory
  • Database
  • Docker
  • Drawings
  • Drill Down Chart
  • English
  • Excel Programming
  • Exporting
  • Facebook
  • Fun
  • Gadgets
  • GitHub
  • GoPro
  • High Map
  • HighChart
  • How to
  • HTML
  • HTML5
  • Ignite UI
  • IIS
  • Interview
  • IoT
  • JavaScript
  • JQuery
  • jQuery UI
  • JQWidgets
  • JQX Grid
  • Json
  • Knockout JS
  • Linux
  • Machine Learning
  • Malayalam
  • Malayalam Poems
  • MDX Query
  • Microsoft
  • Microsoft ADOMD
  • Microsoft MVP
  • Microsoft Office
  • Microsoft Technologies
  • Microsoft Windows
  • Microsoft Windows Server
  • Mobile
  • MongoDB
  • Monthly Winners
  • MVC
  • MVC Grid
  • MySQL
  • News
  • Node JS
  • npm
  • Number Conversions
  • October 2015
  • Office 365
  • Office Development
  • One Plus
  • Outlook
  • Page
  • PHP
  • Poems
  • PowerShell
  • Products
  • Q&A
  • Raspberry PI
  • React
  • SEO
  • SharePoint
  • Skype
  • Social Media
  • Software
  • Spire.Doc
  • Spire.PDF
  • Spire.XLS
  • SQL
  • SQL Server
  • SSAS
  • SSMS
  • Storage In HTML5
  • Stories
  • Third Party Software Apps
  • Tips
  • Tools
  • Translator Text
  • Uncategorized
  • Unit Testing
  • UWP
  • VB.Net
  • Videos
  • Virtual Machine
  • Visual Studio
  • Visual Studio 2017
  • Wamp Server
  • Web API
  • Web Platform Installer
  • Webinars
  • WebMatrix
  • Windows 10
  • Windows 7
  • Windows 8.1
  • Wordpress
  • Writing

ABOUT ME

I am Sibeesh Venu, an engineer by profession and writer by passion. Microsoft MVP, Author, Speaker, Content Creator, Youtuber, Programmer. If you would like to know more about me, you can read my story here.

Contact Me

  • info@sibeeshpassion.com

Pages

  • About
  • Search
  • Privacy Policy
  • About
  • Search
  • Privacy Policy
© Copyright Sibeesh Passion 2014-2025. All Rights Reserved.
Go to mobile version