HomeASP.NET Developing a Dice Game Using ASP.NET Futur...
Developing a Dice Game Using ASP.NET Futures Drag and Drop Techniques
Nowadays, with Ajax being used by more and more web applications, drag & drop support to some degree becomes the magic weapon for various heavyweight Ajax frameworks. As one of the famous Ajax solutions, Microsoft ASP.NET AJAX has not declined to shoulder responsibility and put forward its own server-side and client-side drag & drop solutions. However, in this article, we’ll focus on ASP.NET AJAX client-side drag & drop programming with the development of a simple dice game.
Contributed by Xianzhong Zhu Rating: / 13 April 09, 2008
Drag & drop is the tremendous improvement within the desktop applications area that has vastly increased software application efficiency. However, it is a pity that JavaScript itself does not provide built-in support for the mouse drag & drop operation. Later, with the introduction of DHTML techniques various, browsers started to bring forward their own drag & drop solutions. To eliminate the differences between the solutions provided by various browsers, multifarious JavaScript libraries turned out, whose goals are nearly all the same: providing a cross-browser compatible solution and simplifying drag & drop programming.
Author's Note: To follow along with the dice game development in this article, you're assumed to have installed Visual Studio 2005 and at least the two components of ASP.NET AJAX, which are ASP.NET 2.0 AJAX Extensions and ASP.NET Futures July 2007. In addition, it is highly advisable that you download the source files accompanying this article.
Drag & drop support by ASP.NET Futures
In this section, we’ll first explore the inner workings of cross-browser drag & drop client-side support byASP.NET Futures. To achieve a drag & drop operation, we should take into consideration three factors:
—Draggable items - DOM elements that can be moved around the page, while drop targets are elements that act as "containers" for draggable items. The MS AJAX framework allows us to define draggable elements by implementing theIDragSource interface.
—Drop targets - a class that implements theIDropTargetinterface. In fact, we can also create a class that implements both theIDragSourceandIDropTargetinterfaces.
—DragDropManager - a global object that is instantiated at runtime and is generally used to launch dragging operations and to register drop targets. As you may have doped out, the DragDropManager serves as the headquarters for the whole drag & drop operation by invoking the corresponding methods of the interfaces IDragSource and IDropTarget.
Thus, we can take the following steps to create a drag & drop UI:
—Create draggable items by implementing the IDragSource interface. The class that implements this interface is also responsible for calling the Web.UI.DragDropManager.startDragDrop() method in order to start the dragging operation (typically, this is done via an event handler for the mousedown event of the control's element). Each draggable item has its owndataType, which is an identifier that allows you to group draggable items (the predefined dataType isHTML).
—Create drop targets by implementing the IDropTarget interface. A class that implements this interface is responsible for registering the drop target by invoking the Web.UI.DragDropManager.registerDropTarget() method. Each drop target has a list of accepted DataTypes that specify what "types" of draggable items can be dropped on that target.
Author's Note: Within the file PreviewDragDrop.js, which is shipped with ASP.NET Futures, there are only a pair of built-in behaviors (i.e. DragDropList and DraggableListItem) that support the drag & drop operation. Therefore, to gain a more intensive comprehension of the IdragSource, IdropTarget, and DragDropManager interfaces, as well as the relations between them, the recommended approach is to further study the source code of the DragDropList and DraggableListItem behaviors in the PreviewDragDrop.js file. Once you have grasped the main ideas of the two behaviors, you are sure to reach the summit of ASP.NET AJAX-related drag & drop programming.
Now, let’s concentrate on the main idea of this article, which is developing a dice game with drag & drop support.
Let’s first take a quick look at the final result we hope to achieve.
Visualizing the finish line
In the dice game, we are to create two custom behaviors that are inherited from the IDragSource and IDropTarget interfaces respectively, and perform drag & drop operations at the proper times with the help of the DragDropManager object.Figure1shows theinitialrun-time snapshot of thedice game (CustDragDropDemo.aspx). Here theplayercandrag one of the six dice at the top onto the lower-bottom box with a question mark in it. The question mark will then be replaced with the number of dots the player picks. Of course, as a rule, the six die at the top should be positioned at random with the dot number ranging from one to six.
Figure 1—the initial run-time snapshot of the dice game
Figure2showsone of therun-time snapshots of thedice game, where the player has selected a die with five dots.When the player clicks ‘Restart the game,’ the box at the lower bottom again displays a question mark and the six numbers (1~6) have also been repositioned randomly under the six small boxes with the back covers being the same pattern.
This kind of game is pretty simple in desktop application scenarios. However, in web areas, it is still difficult to tackle, mainly because of the incompatibility between browsers. Next let's dig into the how-to solutions.
Create an ASP.NET AJAX CTP-Enabled Web Site
Launch Visual Studio 2005 and then select the "File | New Website…" menu item to create a new website using the template named "ASP.NET AJAX CTP-Enabled Web Site." Name the projectClientDragDropTest (select Visual C# as the built-in language). After that, the system should automatically add references to the necessary assemblies—Microsoft.Web.Preview.dll and System.Web.Extensions.dll (you cannot see it, since it’s put into .NET GAC). And also, you can see aScriptManagerserver control automatically added to the Default.aspx page. Simply put, this server control acts as the control center for the entire ASP.NET AJAX framework. Finally, rename the Default.aspx file to CustDragDropDemo.aspx.
Next, let’s delve into how to construct the two client-side behaviors that we will utilize in this game.
Obviously, the six dice represent the drag sources. Therefore, we can define a custom behavior named MagicDragSourceBehavior. By attaching this behavior to the six client-side controls that are associated with the six dice, we can make the six die-related DOM elements draggable.
For analysis, we list the source code of MagicDragSourceBehavior, which is shown below:
As for MagicDragSourceBehavior, the following points deserve to be mentioned:
1. This behavior is defined within the Custom.UI namespace.
2. The private variable _visual serves the same role as the private variable _dragVisual and is defined within the DragDropList behavior. These are all used to create a semitransparent element that indicates the drag & drop process.
3. The dragDropMagic propertyis very important. It corresponds to thedata propertyused inside the DragDropList behavior. In this sample, this property is used to store our custom object—Custom.UI.DragDropMagic (for brevity, we have not listed its source code; you can refer to the downloadable source code of the article), which defines two properties:backgroundColorandnumber. These represent the background color of the drop area and the dot number that is shown. Please note the relationship between this property and the data within MagicDropTargetBehavior. It will be defined later.
4. As for the methods declared in IDragSource, here we have defined them with those unused in this empty sample.
5. At the end of the event handler, mouseDownHandler, the following method is invoked:
This method is responsible for notifying DragDropManager that the drag & drop operation has already started.
6. To use MagicDragSourceBehavior inside the declarative XML-Script blocks, we have also defined its descriptor with only adragDropMagic propertyexposed (as is explained above).
Next, let’s take a look at the second behavior—MagicDropTargetBehavior, which will be attached to the droppable area in the dice game. The following is the total source code for MagicDropTargetBehavior:
//only the two conditions are met, can the draggable object be droppable
return (dataType == 'DragDropMagic' && data);
},
//do the factual dropping. Here, we use the data in the draggble object to alter the background color of the droppable area and show the dot number of the dice
Since we have made enough comments between the lines, we don't need to waste space chattering. However, the last point readers should take notice of is that both in the initializeanddispose methods,the corresponding methods of DragDropManager are invoked.
Last but not least, please remember to call the notifyScriptLoaded() methodof Sys.Application at the end of thecustDragDrop.js fileto notify theASP.NET AJAXclient-side framework that this script has been loaded successfully:
Open the CustDragDropDemo.aspx page. As with other typical ASP.NET AJAX web pages, at the nearest position neighboring <form> element, we can see the definition of the ASP.NET AJAX server control ScriptManager; within which, we should add all necessary references to the related script files. Here’s the corresponding code:
As was shown before, in the custDragDrop.js file we defined two custom behaviors, MagicDragSourceBehavior and MagicDropTargetBehavior, and an important class, Custom.UI.DragDropMagic, which represents the factual data the draggable object carries.
Next, follow the relatedHTMLelement definitions and use someCSSstyles for a beautiful look. That’s all.
<fieldset style="width: 607px" >
<legend><span style="font-size: 12pt">Please select a dice</span></legend>
Since the two custom behaviors we are to use are defined in the Custom.UI custom namespace, we have to add a reference to this namespace.
xmlns:cns="javascript:Custom.UI">
Next, we defined six ASP.NET AJAX client-side controls, which are bound to the six <div/> DOM elements that represent the six dice respectively. And, as is discussed above, we should apply the custom MagicDragSourceBehavior to all six controls.
Inside the descriptor block of MagicDragSourceBehavior, we’ve merely exposed one property—dragDropMagic. This property is a rather complex object. Therefore, we decide to use the JavaScript mode, rather than the xml-script mode, to specify this property for the six behaviors (which should be discussed later).
Next, the DOM element <div/> that represents the drop area is also attached to a client-side control (DropTarget), which is also decorated with another MagicDropTargetBehavior.
In the next section we'll see how we use the JavaScript mode to specify the dragDropMagic property for the above six behaviors and how we can attach a click event handler to the ‘Restart the game’ button.
As a general rule, we’d better specify the properties of the behaviors within the defaultloadevent handler—pageLoad of the client object Sys.Application. As was explained before, we specifically build a DragDropMagic to describe the possible complex data that the draggable object carries. In this game, we have to specify the dragDropMagic property for each of the six custom behaviors. The related code is shown below:
Note that the $find method is the shortcut for the Sys.Application.findComponent global method. This is very important in client-side programming and is used to find the reference to the client-side component.
The effect of the createRandomArray helper function is to create six numbers ranging from 1 to 6 that should be assigned to the six dice at random with equal chance. For simplicity, we’ve directly specified the background color of the drop area. Now, you can see that when the game is launched, the six dice will be assigned six different dot numbers at random. The following gives the source code associated with the createRandomArray function.
//return an integer ranging from iFirstValue to iLastValue
It's all so simple, isn’t it? When the player clicks the ‘Restart the game’ button, we again invoke createRandomArray to generate random numbers and assign them to the six dice. And also, we set up the necessary properties for the six dice. Finally, we restore the content of drop target to the beginner question mark.
So much for this game—you can now press F5 and give it a test! I bet you will be attracted to the friendly interface.
In this article, we developed a simple dice game using the ASP.NET AJAX client-side drag & drop technique. As was emphasized again and again, the two client-side interfaces (IDragSouce and IDropTarget) and the DragDropManager object play crucial roles in nearly all ASP.NET AJAX client-side drag & drop based applications. Therefore, to gain a more intensive comprehension of the IdragSource and IdropTarget interfaces, DragDropManager, as well as the relations between them, you are highly advised to earnestly study the source code of the two important behaviors—DragDropList and DraggableListItem in the PreviewDragDrop.js file. Once you have seized the main ideas of how to implement the two behaviors, you may have the ability to do any kind of ASP.NET AJAX-related drag & drop programming.
Apparently, the little game in this article is pretty simple. Maybe the biggest deficiency is that we have not employed the typical Web service means to provide data to the client side. But by using the many samples related to consumer Web service in ASP.NET AJAX on the Internet, it won't be difficult for you to supplement this functionality. And you may even use this small program to develop your own more complex and Ajax-based online games.