Minesweeper with HTML5 & JQuery

One from the drafts I created in Jan 2014

What would you do if you have a lot of time but no IDE? Create a Javascript game 🙂

I recently had an obsession with Minesweeper and I was amazed by how simple the game can actually be. So I opened a notepad and started out writing my own code for minesweeper.

Here is a link to the working game. View source to see what’s happening. All the logic is in the linked game.js file.

I will go about explaining how the logic behind the game was generated (More for my pleasure of explaining than anybody’s interest in reading).

The HTML

This is so simple I don’t even need to put it here. But I’ll do it anyway…


    <div id="gameContainerOuter">
      <div id="gameContainer">
        <table id="mineField" cellspacing="0" cellpadding="0" border="0">
          <!-- Auto generated cells -->
        </table>
      </div>
      <div id="instructionsContainer">
        <div id="instructionsContent">
			Play the game like the regular minesweeper <br />
			Settings/New Game options are to the right <br />
			Access by clicking the [+] area <br />
		</div>
      </div>
      <div id="settingsContainer">
        <div id="settingsHandle">
          <span>[+]</span>
        </div>
        <div id="settingsContent">
          <a id="newGame" href="#" style="margin:15px; padding:5px; border:1px solid #000000; background-color:666666">Start new game</a><br />
          <br />
          <input type="radio" name="gameLevel" id="levelEasy" /> <label>Easy (10x10 with 10 mines)</label><br />
          <input type="radio" name="gameLevel" id="levelMedium" /> <label>Medium (15x15 with 25 mines)</label><br />
          <input type="radio" name="gameLevel" id="levelHard" /> <label>Hard (25x25 with 50 mines)</label> 
        </div>
      </div>
      <div style="display: block; clear: both;"></div>
    </div>

Populating the cells

Populating the cells is more of a JQuery game. Brushed up a bit on traversals and got the following code working:


function placeMines(row, col)
{
  var minesPlaced = 0;

  for (var i=0; i<size; i++)
  {
    field[i] = new Array();
    for (var j=0; j<size; j++)
    {
      field[i][j] = false;
    }
  }

  while (minesPlaced < mines)
  {
    var randomRow = Math.floor(Math.random() * (size));
    var randomCol = Math.floor(Math.random() * (size));

    // alert("Mine " + minesPlaced + " @ " + randomRow + ", " + randomCol);

    if (randomRow != row && randomCol != col && field[randomRow][randomCol] == false)
    {
      field[randomRow][randomCol] = true;
      minesPlaced ++;
    }
  }
}

Finally it’s just about adding a few handlers and getting the whole code working. This turned out to be rather simple in the end

Death of silverlight

Silverlight as a plugin is long gone. With Chrome disabling NPAPI by default, the era of plugins, as we knew it, is gone. Now, what do I do with all the skills I’ve developed as a Silverlight developer?

Hmmm… That’s a tough one. Here’s my take on this:

Working as a front-end developer is a continuous process of learning new technologies. Silverlight came out of nowhere and there was a big rush to learn it. Before that there was a bug rush to learn ActionScript (remember those days?). Of course with the introduction of ActionScript 3.0 things changed dramatically as it nearly coincided with the loud bang of Apple releasing its first iPad followed by iPhone which gave Flash a big juicy finger. Whatever happened to the Flash developers anyway?

All that’s way behind in the past. Lets look at the present. Javascript frameworks have become such a big thing in the market now. The capabilities of the first Silverlight app are far surpassed by an AngularJS app. Add NodeJS and the million NPM plugins with funky names to army and that overpowers other front-end technologies in a big way. How did this come to be? Why did Javascript become such a big thing?

I think we need to go back to late 2000s when new phones were being released every other day. First it was iPhone and a tonne of developers started learning Objective C. Then came Android. Then android just went ‘whoooooshh’ and took over the biggest chunk of the mobile market. Windows phone in its ever-losing smartphone race released a few really good phones. Thanks to Nokia! (we still love you). So many platforms.. How would one keep up with everything?

CSS3 to the rescue. With better support for responsive apps and a bunch of really smart people inspired by JQuery started developing re-usable frameworks. Unlike before these were smaller bite-sized frameworks that could be cherry-picked to create an application of your choice.

Unity – per thread lifetime manager

While working with multi-threaded applications build over a DI framework it would be extremely useful to have objects that are specific to the context of a thread. My most favorite IoC framework, Unity, provides awesome lifetime managers that can be used to handle situations like these.

Scenarios

The most common scenario where I came across this is to group application logs by a specific thread. Each thread does a specific job and I wanted to prefix specific attribute to the log. A smart lazy person would probably just start logging the thread ID. I know that is quite simple for you to understand the logs. But when a somewhat non-technical person (project managers) wish to see the logs, you might want to make the logs more meaningful.

I once worked on this application that performed a lot of calculations on separate threads. A complex calculation was forked into multiple threads. I wanted to store the output for reuse within a thread. (Lets skip the nitty-gritties of
the app). In that situation a ‘PerThreadStore’ came in extremely handy.

ThreadStatic attribute

There is a very simple way to create thread specific properties. Just use the [ThreadStatic] attribute. Quite common among the multi-threaded developers. But using this as an extension of your IoC framework makes the application quite cool to develop.

PerThreadLifetimeManager with Unity

    /// <summary>
    /// Extends the LifetimeManager to define a class that provides a lifetime per thread
    /// </summary>
    public class PerThreadLifetimeManager : LifetimeManager
    {
        /// <summary>
        /// Overridden method that returns the value of the stored object
        /// </summary>
        /// <returns>The value of the object</returns>
        public override object GetValue()
        {
            return PerThreadStore.Item;
        }

        /// <summary>
        /// Overridden method that removes the value for the stored object
        /// </summary>
        public override void RemoveValue()
        {
            PerThreadStore.Item = null;
        }

        /// <summary>
        /// Overridden method that adds a value to the stored object
        /// </summary>
        /// <param name="newValue">The value to be stored</param>
        public override void SetValue(object newValue)
        {
            PerThreadStore.Item = newValue;
        }
    }

    /// <summary>
    /// A store that stores a static object that has a single value per thread
    /// </summary>
    public class PerThreadStore
    {
        [ThreadStatic]
        private static object _Item;

        /// <summary>
        /// Gets or sets any value to be stored per thread
        /// </summary>
        public static object Item
        {
            get
            {
                return _Item;
            }
            set
            {
                _Item = value;
            }
        }
    }

Peace

Problematic sign up process with WP7 dev

I recently purchansed a Nokia Lumia 800 and was very excited with the prospects of developing apps on it. I probably did a dumb thing by not doing some information gathering before I actually purchased the mobile. When I first got the cell, I installed WP7 development tools on my machine. Created my first ‘Hello world’ app and was all excited to run it and things went far far down south from there.

First thing – The WP7 emulator needs the developer key. The error message is quite cryptic. It does not say something like ‘Please enter your developer key as retrieved from AppHub’ but instead gives an error code. Alright, I googled the error and figured out that I need to get the key from AppHub. I set off to sign up on it…

Second thing goes wrong. I realized I need to pay to become a developer. WTF!!! Alright! Im ready to pay. Lets get it done with. I go to the payment details and my country is selected as US which is not my country now, but it was an year ago. I don’t have any more money in my US credit cards so I wanted to change the country, but whatdyaknow…. You can’t. Now how am I supposed to pay?

I go update my windows live account and try again. This time I get an error:

Unable to complete your request
We cannot complete your request now, please try again later.
Message 40001
Hmmm… Alright. Very helpful indeed! Exactly what I was looking for!!! Idiots.
So I googled this error and it looks like I need to email Microsoft and ‘hope’ for an answer. So I did it. I sent a very detailed email.
I reply I got was to update the payment information on Xbox.com! Alright. Microsoft has definitely not thought about a proper distributed DB for their accounts. Ok… Im still going to try to get this thing working… I deal more with broken stuff than proper functional stuff in my line of work. I open my XBox account (which by the way gets created automatically, I guess, when you register your WP7 phone) and look for the country. Hmm… The messed up thing is you can’t bloody change it!!!
Now the solution is to create a new WindowsLive account that is registered in India, then reset my phone to its factory settings and log in using the new credentials… And lose all my previous settings… What bull!
I like WP7 and things… But – “Microsoft… You need to get your act together!! X( “

Error 1001: Service has been marked for deletion

Another of those stupid windows errors!

I was working on this windows service recently. While developing this I code the changes, build the app and run the service installer. (The service installer project is quite cool. I admit). But every now and then when I uninstall the service and try to reinstall it I get this error:

Error 1001: Service has been marked for deletion

I know its marked for deletion. But why is it not deleted yet? I used to restart the system as a solution to this problem. But soon enough I began to see the stupidity behind some of the windows apps. I had the Service Control Manager running to start/stop the service. After uninstalling the service if you happen to open the SCM window, it gets a lock on the service entity and marks it as ‘Disabled’. Now when you try to install the service again Error 1001 pops up.

The solution to this was to just close the SCM and install the service. SCM is one of the core windows utilities. You expect it to behave right?

Mobile emulators

Lately, I’ve been taking a lot of interest into mobile development. I have started developing some Silverlight apps for Windows Phone 7. I plan to upgrade my mobile development skills to include Java, for Android apps, and iOS, for iPhone apps, at some point in the future. (Hopefully that is. For the lazy bum that I am, I am very optimistic in my planning). While I wait to update my skill sets, I need to do something to make my apps available on mobile platforms other than Windows Phone. So creating a mobile version of the web app is the current solution.

I recently developed some test HTML pages and I wanted to test out how it looks on my mobile. To do this test here are my options:

1. Host the site content on some publicly available server (like this… ShishirRao.com 🙂 )

But this is a boring process. I feel sleepy when I open FileZilla. Besides, I’ve messed around with hosted content in all wrong ways before. So I would do my best to prevent doing this with anything other than code ready for production.

2. Host it locally, connect to a LAN connection with WiFi and open the IP:Port of my machine’s Apache/IIS.

This works very well actually. This is my favorite mode of development actually. However I often end up in situations without a WiFi connection. (Like my office where I’m not supposed to be developing mobile apps for my amusement… Or writing this post… {Evil grin})

3. Use a Mobile Emulator on the machine I’m developing stuff on.

This is another good solution. There are several standalone apps and virtual boxes available that emulate mobile browsers for various phones. This is a great way to test my locally hosted app as well as try out the looks of my app on other browsers. (It is very important to see how browsers interpret your HTML. With the advent of HTML 5 and CSS 3.0 and the millions of mobile browsers… ok hundreds… the amount of mismatch in the way a sites are rendered have started to vary greatly) Most importantly, I test out the way it shows up on Safari, Opera and IE. That is for iPhone, Blackberry/Android and Windows Phone.

Here is a link for the windows phone emulator. Nice app it is.

But here’s the best link I’ve found – MOBILE EMULATORS. A neat collection of the emulators available right now.

I almost started making a list of mobile emulators myself, but after seeing the neat job this author has done, I just want to share a link to his page. Hopefully he updates it with new emulators whenever they come around.

System.Xml.XmlSerialization – Assembly bind failure (MDA Error)

When Im debugging my application I ask Visual Studio to throw all exceptions in my code. (I do this by checking everything in Debug > Exceptions) It seems like a good thing to have while debugging applications – to know the exceptions you’re getting even if you’re catching them and handling them. This setting in combination with the use of System.Xml.Serializers seems to constantly throw this error in my application:

System.Xml.Serialization assembly binding failure

This gets annoying after a while as my code seems to be perfectly alright, no errors, but this window keeps popping up at this line:

XmlSerializer xmlSerializer = new XmlSerializer(type);

I looked at the error in detail and it seems to be looking for an assembly named My.Namespace.XmlSerializers. Of course there’s no such assembly and the compiler will get a System.IO.FileNotFoundException. The best solution I could Google out was to uncheck the BindingFailure and prevent the exception from showing up every time.

This worked only in stopping me from getting annoyed, whenever that error showed up, but I knew there still was some error and it was being handled somewhere! I had to figure out what was going on…

Enter Reflector (Now a RedGate product. An addition a cool line up of .NET tools)

I have a trial version of Reflector on my machine and this is an excellent opportunity to figure out what in the world is happening in System.Xml.Serialization. I disassembled the entire System.Xml assembly and searched for the keywork ‘XmlSerializers’.

Looks like there is code to generate a custom assembly to handle type passed to the current serializer. Every call to this creates this assembly in a temp location and runs the deserialization through this assembly. There seems to be multiple options for the ‘temp location’ to generate this assembly. Once the assembly is generated, it is delay loaded at runtime. During this the assembly loader searches for all the possible temp locations and each time it fails to find the assembly in one of the temp locations, it throws a FileNotFoundException. This exception is rethrown as a bind failure.

So… I don’t know why the serialization/deserialization logic needs to be this complicated. But, in case of the core .NET library, it just is. I also have noticed that the memory footprint of System.Xml.Serialization classes to be quite big. This whole process of creating a temp assembly probably adds to it. I know there are better solutions for XML deserialization out there. I will soon get onto searching for one and evaluating it against System.Xml.Serialization methods. I’ll add an update to this post when I do find one (eventually…)

In conclusion, System.Xml.Serialization classes and methods are an expensive way to serialize objects to XML or to deserialize XML to objects. This throws a BindingFailure exception as the library internally uses a try catch to handle delay loading a temp assembly. Though this code is internal to the assembly, this error shows up if we enable throwing all exceptions as the delay load is happening in the context of our application.

So, the best solution to avoid (seeing) this error is what’s been suggested by many – in Visual Studio uncheck BindingFailure in Debug > Exceptions under ManagedDebuggingAssistants

Get current application directory

Often when I write apps, I come across a situation where in I need to store some temporary files. Say, I need to run a command through System.Diagnostics.Process. This command requires a path to store the output as a file though an /o: parameter. For ages I used to use Assembly.GetExecutingAssembly().Location to get the directory of the current app.

This often gets very hairy as the current executing assembly will change if you are invoking your application through an external service. Running unit test cases on this app gets trickier as testing frameworks like NUnit create temporary DLLs at temporary locations. I saw this post that uses Assembly.GetExecutingAssembly().CodeBase to make the application behave better.

Simple code but very effective:

static public string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        UriBuilder uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}

XLite Expression Evaluator

Often, we run into a situation where we might have to work with expressions that come in as strings. If you wish to evaluate the string “1+2” to give 3 and “1+2*2” to give 5 and “(1+2)*2” to give 6 then XLite Eval is one of the easiest solutions. XLite Eval also provides you with a way to add your own functions to perform additional logic.

I developed XLite Eval to work in a way that is very similar to the way you write formulae in Microsoft Excel’s formula bar. View/Download this project on CodePlex at http://xliteeval.codeplex.com/

Idea behind the design

Excel’s formula bar is probably one of the most commonly used controls to enter mathematical formulate in today’s corporate world. Most of the people are already familiar with this or have people around them that can get them upto speed in a short time. Some of the advanced excel users are familiar with complex excel functions like STDVX(…), HLOOKUP(…), SUMIFS(…), etc., But most excel users have an idea of functions like SUM(…), AVG(…), MIN(…), MAX(…) etc., So creating an expression evaluator that uses the syntactic similarity to Excel greatly reduces the learning curve in using XL Lite Expression Evaluator.

Adding new functions

Let me use a lame example of a function called TIMES3 which always returns 3 times the input value. This lame function would take one input value and return a number. This can be easily added to XL Lite Expression Evaluator by adding the following class file:

ExpressionEvaluator.Lib/Core/Functions/Times3.cs

 

using System;
using System.Collections.Generic;

namespace SR.ExpressionEvaluator.Lib.Core.Functions
{
    public class Times3 : IFunction
    {
        List<object> _Args = new List<object>();

        public System.Collections.Generic.List<object> Args
        {
            get
            {
                return _Args;
            }
            set
            {
                _Args = value;
            }
        }

        public object Evaluate()
        {
            if (!Validate())
            {
                throw new Exception("TIMES3: Validation failed");
            }

            return 3 * Convert.ToDouble(Args.First());
        }

        public bool Validate()
        {
            if (Args.Count != 1)
            {
                return false;
            }
            return true;
        }

        public string GetDefinition()
        {
            return @"TIMES3(<value>)";
        }
    }
}

Using variables

In my view, being able to use variables makes the expressions completely dynamic and changing the values of the variables can give different values for the expression. Let’s assume we have the following expression “MY_VAR+10” where MY_VAR is a variable in the expression. We can create this and assign values using the following code:

IEvaluator eval;
string expression = "MY_VAR+10";
object result;

this.eval = Factory.GetEvaluator();
this.eval.Variables.Add("MY_VAR", 35);
result = eval.Evaluate(expression); 
// Yields result = 45

this.eval.Variables["MY_VAR"] = 22;
result = eval.Evaluate(expression); 
// Yields result = 32

Give XLite Eval a shot. Comment all you want on it.