A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the ‘Having fun with jQuery UI’ blog post.
In this post we will go through how to create the game using ASP.NET MVC, jQuery and jQuery UI.
The screenshot below shows the game running.

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.
$.getJSON("/Game/GetAnimals",
{ numberOfAnimals: numberOfItemsToGet, previousAnimal: correctAnswer.text() },
function(data) {
addItems(data);
$("#droppable").droppable(droppableOptions);
assignDraggables();
hideItemsForLevel();
setUpSlider();
setTimeout(function() {
instructions.text(instructionsText);
items.show();
}, 1000);
});
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.
The images for the animals used in the game are from http://www.openclipart.org.



