Game of Life in Javascript

Background

A while ago, I discovered Jonh Conway’s Game of Life. Game of Life is a cellular automaton invented by the British mathematician John Horton Conway in 1970.

A cellular automaton is an array (of one or more dimensions) of cells in which each cell has a finite number of conditions. An example of a finite number of conditions is “on” and “off”, or “empty”, “half full” and “full”.

A set rules determines, based on the current condition of the cells and each cell’s neighbours, what the next condition of each cell will be.

By applying these rules repeatedly, certain patterns or movements come to exist. Depending on the rules, these movements can closely resemble what happens spontaneously in nature.

Conway’s Game of Life is an example of such a cellular automaton. The cells can either be dead or alive and within the automaton, the following rules apply:

  1. Every living cell with less than two living neighbours dies as if by underpopulation
  2. Every living cell with more than three living neighbours dies as if by overpopulation
  3. Every living cell with exactly two or three living neighbours continues to live
  4. Every dead cell with exactly three living cells comes back to life

By applying these rules multiple times per second, the cells will switch state and this can, depending on the formations of living cells, lead to interesting movements.

I thought this was so intersting that I decided to build my own implementation of Conway’s Game of Live. Using Javascript.

My implementation

Because Conway’s Game of Life takes place inside a two dimensional grid of cells, it seemed logical to use a <table> for this. In my first version I tried to get everything working without using any extra variables in Javascript by keeping everything inside attributes of the <td>’s. This worked, the performance was so horrible that I had to find another way.

In my second (and current) version, I ended up creating three classes in Javascript:

  • A class Cell that, of course, represents a cell.
  • A class GameOfLifeRenderer that is responsible for creating a <table> with a certain amount of cells. The condition of the cells is saved in a two dimensional array of the type Cell.
  • A class GameOfLifeLogic that implements the rules of the game.

The logics work like this:

  1. Loop over the two dimensional array of Cells and calculate the amount of living neighbours for each cell.
  2. Determine for each cell what its next condition will be.
  3. Loop over the two dimensional array a second time. If the current condition of a cell if different from its next condition, change the current condition and give the <td> the correct color.

Here you can find my version of Conway’s Game of Life I have also provided a browser friendly version of my Javascript code.

Posted in Development | Tagged | 2 Comments

The plans for 2010

There is an update to this post available here: http://www.kristofclaes.be/blog/2010/06/17/the-plans-for-2010-update/.

In the wonderful world of IT there is an such abundancy of things to do and discover that it is often hard to focus on just a few them. Most of the times, that leads to superficially looking into a lot of things while mastering none of them and before you know it, you’ll be the proverbial jack of all trades and master of none.

Because a new year goes hand in hand with New Year’s resolutions, I thought it might be a good idea to make some resolutions in the area of technologies. I’ve taken some time to compile a list of things I believe are quite interesting and want to know more of. It is my intent to check off items on the list during the year and by the beginning of 2011 I should have finished everything. I have tried to keep the list on the small side to have a buffer for one or two extra things I might encounter during the year. If find too many things, they’ll just have to wait for 2011.

This is the list I mean to finish, in no particular order:

The fun part is that certain items can be combined. Let’s say I build a demo application in ASP.NET MVC 2 and use MongoDB for data storage. That’s two items off the list. Why stop there? Why not use dependency injection and integrate all three databases in the application? And why not set up a continuous integration server while developing the application? I must admit maybe that’s a bit too ambitious.

We’ll see where we get!

Posted in Development | Tagged , , , | 1 Comment

Scott Guthrie is coming to Belgium

Scott Guthrie, Corporate Vice President of the Microsoft Developer Division, among other things responsible for ASP.NET, Silverlight and IIS 7, is coming to Belgium on the 4th of December to give a presentation about Visual Studio 2010, .NET 4 and Silverlight 4.

The presentation is free and it will take place in Kinepolis in Brussels. The planning for the day can be found below and registering can done using this link.

13:00 – 13:30 Reception and registration
13:30 – 15:00 Visual Studio 2010 and .NET 4 web development
15:00 – 15:20 Break
15:20 – 16:30 Silverlight
16:30 – 17:00 Q&A
Posted in Development | Tagged , | Leave a comment

ASP.NET MVC with Ninject 2

In his book Pro ASP.NET MVC Framework, author Steven Sanderson takes three chapters to explain how build an e-commerce application in ASP.NET MVC. Because Steven is a big fan of Domain-Driven Development (DDD) he uses the opportunity to explain how to apply the principles of Inversion of Control (IoC) or Dependency Injection (DI) using Castle Windsor, a IoC-framework with which you can quite easily introduce IoC to your application (if your business logic is modelled correctly of course).

Because I find the concept of DDD and IoC very interesting, I have decided to check out how easy it is to replace Castle Windsor in Steven’s example application with another IoC-framework: Ninject.

My first attempts with Ninject 1.0 didn’t lead to much. It quickly became too mmuch of a hassle compared to Castle Windsor. Just when I was about to give up, I noticed that there was beta version of Ninject 2.0 available. With this version it was a breeze to set up IoC.

To allow an ASP.NET MVC application work with Ninject 2.0 for DI, you can follow these easy steps:

Download Ninject and add it to your application

On Github, you can download the latest version of Ninject 2.0 and the Ninject.Web.MVC extension.

The only thing you have to do is download the source code of the two projects, compile them to get the two needed dll’s (Ninject.ddl and Ninject.Web.Mvc.ddl) and add these dll’s to your project.

Configurate Ninject

Now your project contains the references to Ninject, there are a few things to be configured. The bulk of these settings can be done in the code behind of your Global.asax.

The first thing you have to do is include the two Ninject libraries:

using Ninject;
using Ninject.Web.Mvc;

As you may notice, your Global.asax class is called MvcApplication and inherits by default from System.Web.HttpAplication:

public class MvcApplication : System.Web.HttpApplication
{
    ...
}

A big part of Ninject works automagically. This magic can be achieved by letting the MvcApplication class inherit from NinjectHttpApplication:

public class MvcApplication : NinjectHttpApplication
{
    ...
}

The Global.asax has an Application_Start() method. The NinjectHttpApplication class has its own version to serve that purpose and we are going to implement it now. Replace the Application_Start() with the following code:

protected override void OnApplicationStarted()
{
    RegisterAllControllersIn(System.Reflection.Assembly.GetExecutingAssembly());
    RegisterRoutes(RouteTable.Routes);
}

The first line is responsible for registering all controller classes (classes that implement IController somehow). The second line is simply copied from the old Application_Start() methid and takes case of route registration, just like in a default MVC application.

Now we have to initialize the Ninject kernel. This can be done with the following code:

protected override IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Load(System.Reflection.Assembly.GetExecutingAssembly());
    return kernel;
}

It is the kernel that eventually takes care injecting the dependencies. To do this, the kernel uses a list of bindings. But where does it get this list? From all classes in your application that inherit from the NinjectModule class.

Creating a module with bindings

Now add a new class to your application and call it, for example, WebModule and let it inherit from NinjectModule (in the Ninject.Modules namespace) and implement the Load() method:

public class WebModule : NinjectModule
{
    public override void Load()
    {
        Bind<DomainModel.Abstract.IProductsRepository>().To<DomainModel.Concrete.SqlProductsRepository>().WithConstructorArgument("connectionString", @"Server=.\SQLEXPRESS;Database=SportsStore;Trusted_Connection=yes;");
        Bind<DomainModel.Services.IOrderSubmitter>().To<DomainModel.Services.EmailOrderSubmitter>().WithConstructorArgument("smtpServer", "127.0.0.1").WithConstructorArgument("mailFrom", "sportsstore@example.com").WithConstructorArgument("mailTo", "admin@example.com");
    }
}

In this example what the Load() method looks like for the SportsStore application from the Pro ASP.NET MVC Framework book.

Every time the Ninject kernel encounters a controller with a contructor parameter of the type IProductsRepository, it will pass in an instance of SqlProductsRepository. This SqlProductsRepository also has a constructor parameter: the connectionstring. This connectionstring can also be passed in using Ninject bindings.

The same goes for the IOrderSubmitter. In this case the kernel will pass in an instance of lOrderSubmitter meegeven with three constructor parameters.

Conclusion

It was actually quite easy to replace Castle Windsor with Ninject 2.0. They are both easy to configure. What can be an advantage of Castle Windsor is that the bindings are done in the Web.Config. That can come in handy when you have separate environments for development, staging and production. In that case you can just use the same code in all three environments but with different IoC settings in the Web.Config files.

The above bindings look like this for Castle Windsor:


<configuration>
    <configSections>
        <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
    </configSections>

    <castle>
        <components>
            <component id="ProductsRepository"
              service="DomainModel.Abstract.IProductsRepository, DomainModel"
              type="DomainModel.Concrete.SqlProductsRepository, DomainModel"
              lifestyle="PerWebRequest">
                <parameters>
                    <connectionString>Server=.\SQLEXPRESS;Database=SportsStore;Trusted_Connection=yes;</connectionString>
                </parameters>
            </component>
            <component id="OrderSubmitter"
              service="DomainModel.Services.IOrderSubmitter, DomainModel"
              type="DomainModel.Services.EmailOrderSubmitter, DomainModel">
                <parameters>
                    <smtpServer>127.0.0.1
                    <mailFrom>sportsstore@example.com
                    <mailTo>admin@example.com
                </parameters>
            </component>
        </components>
    </castle>
</configuration>
Posted in Development | Tagged , | 3 Comments