Having experience with jQuery I thought this would be a good idea to see if George used the same practices as I do, which he did… which means either we’re both doing it wrong or we’re both doing things correctly… and I’m sticking to the latter
Not having heard of George I had no idea what to expect.
George is a defiantly a character, in fact on the DD9 speaker page they could have stopped after just three words
George is nuts
He has a great presentational style and is able to deliver comments about IE with impeccable timing
After satisfying people who need an agenda what has the content?
George
talked about closures and event delegation
showed demos of using the live method when creating new elements
demonstrated the modern way (at the time of writing) of creating Hijax links using the data-remote attribute
showed a workaround for cross domain AJAX calls using the callback? in the request and JSONP
The last thing I’ll say about this talk was how well George managed to still run demos even though the demo gods did their best to ruin his presentation and screw up his solution.
The code used for creating the game in ASP.NET MVC, jQuery and jQuery UI can be downloaded here.
Getting Started
Instead of three animals used in the demo, the game now contains fourteen. I’ve created a repository which returns the animals. To keep things simple there’s no database here, instead the animals are hard coded.
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
namespace GameUsingAspNetMVCandJQueryUI.Core.Repository
{
public class AnimalsRepository : IAnimalsRepository
{
public IQueryable<Animal> GetAll()
{
return new Animal[]
{
new Animal(){Name = "Cow"},
new Animal(){Name = "Cat"},
new Animal(){Name = "Chicken"},
new Animal(){Name = "Dog"},
new Animal(){Name = "Elephant"},
new Animal(){Name = "Giraffe"},
new Animal(){Name = "Hippo"},
new Animal(){Name = "Lion"},
new Animal(){Name = "Monkey"},
new Animal(){Name = "Mouse"},
new Animal(){Name = "Owl"},
new Animal(){Name = "Penguin"},
new Animal(){Name = "Pig"},
new Animal(){Name = "Sheep"},
}
.AsQueryable();
}
}
}
Command Query Separation
One of the features I have added is to ensure a correct answer for the current game could not be the correct answer in the next. As the repository class was responsible for getting animals, having it contain any logic would violate good design principles.
So the logic goes into the service layer which returns a data transfer object for animals and the correct answer.
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.ExtensionMethods;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;
namespace GameUsingAspNetMVCandJQueryUI.Core.Service
{
public class AnimalsService : IAnimalsService
{
private readonly IAnimalsRepository _animalsRepository;
public AnimalsService(IAnimalsRepository animalsRepository)
{
_animalsRepository = animalsRepository;
}
public AnimalsDto GetAnimalsForGameWithCorrectAnswer(int numberOfAnimals, string previousAnimal)
{
AnimalsDto animalsDto = new AnimalsDto();
animalsDto.Animals = _animalsRepository
.GetAll()
.Where(a => a.Name != previousAnimal)
.Shuffle()
.Take(numberOfAnimals);
animalsDto.CorrectAnswer = animalsDto.Animals.Shuffle().First().Name;
return animalsDto;
}
}
}
This also makes testing easier because the tests can focus on making sure the service is doing what it should like this
using System;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;
using GameUsingAspNetMVCandJQueryUI.Core.Service;
using NBehave.Spec.NUnit;
using NUnit.Framework;
using Rhino.Mocks;
namespace GameUsingAspNetMVCandJQueryUI.Tests
{
[TestFixture]
public class AnimalsServiceTests
{
private IAnimalsService _animalsService;
private IAnimalsRepository _animalsRepository;
private readonly IQueryable<Animal> _animalsStub = new Animal[]
{
new Animal(){Name = "Cow"},
new Animal(){Name = "Pig"},
new Animal(){Name = "Sheep"},
}.AsQueryable();
[SetUp]
public void SetUp()
{
_animalsRepository = MockRepository.GenerateStub<IAnimalsRepository>();
_animalsService = new AnimalsService(_animalsRepository);
}
[Test]
public void Should_Exclude_Previous_Animal_When_Previous_Animal_Is_Passed_In()
{
// Arrange
_animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);
var previousAnimal = _animalsStub.First();
// Act
var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal.Name);
// Assert
result.Animals.Count(a => a.Name == previousAnimal.Name).ShouldEqual(0);
}
[Test]
public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Passed_In()
{
// Arrange
_animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);
string previousAnimal = String.Empty;
// Act
var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);
// Assert
result..Animals.Count().ShouldEqual(3);
}
[Test]
public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Null()
{
// Arrange
_animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);
string previousAnimal = null;
// Act
var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);
// Assert
result.Animals.Count().ShouldEqual(3);
}
[Test]
public void Correct_Answer_Should_Not_Be_Empty()
{
// Arrange
_animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);
// Act
var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, null);
// Assert
result.CorrectAnswer.ShouldNotBeEmpty();
}
}
}
The LINQ Shuffle
Even though we have removed the previous answer, if the animals were returned as they are the answer would just be the next one in the list. So to keep the game exciting, a shuffle extension method is used to shuffle the answers.
using System;
using System.Collections.Generic;
using System.Linq;
namespace GameUsingAspNetMVCandJQueryUI
{
public static class GameExtensions
{
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items)
{
var rnd = new Random();
IEnumerable<int> numbers = Enumerable.Range(0, items.Count()).OrderBy(r => rnd.Next());
var randomItems = new List<T>();
foreach (int number in numbers)
{
randomItems.Add(items.Skip(number).First());
}
return randomItems;
}
}
}
This can be unit tested as shown below
using System.Collections.Generic;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using NUnit.Framework;
namespace GameUsingAspNetMVCandJQueryUI.Tests
{
[TestFixture]
public class GameExtensionsTests
{
[Test]
public void Can_Shuffle_Animals()
{
List<Animal> animals = new List<Animal>()
{
new Animal(){Name = "Cow"},
new Animal(){Name = "Pig"},
new Animal(){Name = "Sheep"},
};
IList<Animal> result = animals.Shuffle().ToList();
Assert.IsFalse(
animals[0].Equals(result[0]) &&
animals[1].Equals(result[1]) &&
animals[2].Equals(result[2]),
"Animals should have been shuffled");
}
}
}
What happens when a player opens the game in their browser?
When the page loads an Ajax call is made using jQuery to an Asp.Net MVC action method which returns a JsonResult.
Two parameters are passed to the action method, one for the previous answer and the other for the number of animals required. The reason for this is because we don’t want to transfer more data over the wire than required, why return fourteen animals when only six are required?
The ‘GetAnimals’ Asp.Net MVC action method shown below serializes the view model returned by the service layer into JSON.
using System.Web.Mvc;
using GameUsingAspNetMVCandJQueryUI.Core.Service;
namespace GameUsingAspNetMVCandJQueryUI.Controllers
{
[HandleError]
public class GameController : Controller
{
private readonly IAnimalsService _animalsService;
public GameController(IAnimalsService animalsService)
{
_animalsService = animalsService;
}
public ActionResult Index()
{
return View("Index");
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult GetAnimals(int numberOfAnimals, string previousAnimal)
{
return Json(_animalsService.GetAnimalsForGameWithCorrectAnswer(numberOfAnimals,previousAnimal));
}
}
}
Notice how I have to be explicit about how I do NOT want the JsonResult to be cached. If you don’t add this Internet Explorer will cache the result and you will get the same animals.
Using the jQuery and jQuery UI in the ASP.NET MVC View
The JavaScript used the demo was good enough to perform the dragging and dropping of pictures so the good news is we can use it again here.
An additional feature I have added is to allow the player to change the difficulty of the game by choosing how many animals are shown on the screen.
To do this I used the jQuery UI slider and jQuery fade functionality. The reason I used fade rather show/hide in jQuery was because I didn’t want the animals to move position when a user changed the difficulty as this would have resulted in a poor user experience by confusing the player.
Currently the message which tells the player if they have selected an incorrect answer is shown when the user stops dragging the animal. This is a problem because if the user drags a correct animal but doesn’t drop it on the droppable a message isn’t shown. If I find a fix for this I’ll update the code and this post.
Jag Reehal’s Final Thought on ‘Creating the animals game using Asp.Net MVC, jQuery and jQueryUI’
I’ve been using jQuery for a while now and I still love it.
The jQuery UI library is very good and the jQuery UI team have done a fantastic job creating demos and documentation.
I really like how you can create your own custom javascript file which only contains the features you require from the library.
No doubt some people will question why the service is returning a data transfer object. I could have returned a collection of animals to the ASP.NET MVC controller and have it create an object to pass to the view. The reason I didn’t do this is because I know the data transfer object will be used by another user interface layer (Silverlight) and because this would have bloated the controller and that’s not good. A best practice for ASP.NET MVC is to have skinny controllers.
As my nephew is coming round to visit in a couple of weeks, I want to create a game he could play.
The aim of the game is to match pictures to a word. The demo shown below uses the jQuery UI library which makes the dragging and dropping possible. If you want to know more check out the excellent draggable and droppable demos.
As this is just a demo the animals are hard coded so if you hit play again you will see the same animals.
Can you match the picture to the word?
Drag the picture to the box on the right
Cow
The demo uses the jQuery and jQuery UI libraries (hosted by Google) and the javascript shown below
$(function() {
var result = $('#incorrectResult');
var correctResult = $('#correctResult');
$(".draggable").draggable({
containment: '#gameContainer',
revert: 'invalid',
start: function(event, ui) {
result.fadeOut(1000);
},
stop: function(event, ui) {
if (!$(this).hasClass('correct')) {
result.html("Try again that's a " + $(this).attr("id"));
result.fadeIn(1000);
}
}
});
$("#droppable").droppable({
accept: '.correct',
drop: function(event, ui) {
$(".draggable").draggable('disable');
correctResult.fadeIn(1000);
correctResult.prepend('Well done! You found the ' + ui.draggable.attr('id') + ' ');
}
});
$("#playAgain").click(function() {
location.reload(true);
});
});
The html used to create the game looks like this
<div id="gameContainer">
<div id="gameTitle">Can you match the picture to the word?</div>
<p id="instructions">Drag the picture to the box on the right</p>
<div id="items">
<img class="draggable correct" id="Cow" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/cow.png" /><br />
<img class="draggable" id="Pig" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/pig.png" /><br />
<img class="draggable" id="Sheep" src="http://www.arrangeactassert.com/wp-content/themes/resources/picturewordgame/sheep.png" />
</div>
<div id="droppable">
<p id="itemName">Cow</p>
</div>
<div id="results">
<div id="correctResult">
<input id="playAgain" type="button" value="Click here to play again" />
</div>
<div id="incorrectResult" />
</div>
</div>
Yes the html and javascript won’t win any awards, the fact it works in a blog post is good enough for me
What’s next?
To begin with I will create a version of the game using ASP.NET MVC, jQuery and jQuery UI. This will look like demo shown in this post with additional functionality to randomise the pictures.
Then I will create a version of the game using Silverlight.
Once this is complete I will refactor both solutions to share as much code as possible. I’m assuming RIA services is the tool of choice but we will see.
After that maybe (way in the future) I might attempt to write this game for the Android platform and take advantage of touch screen mobile phones. I have never developed an application before so this should be an interesting challenge.