Silverlight Snake (Nibbler Clone) 2009
Here’s a game I wrote in Silverlight 2.0 that is a clone of the old-school classic Nibbler. If you never played or heard of Nibbler, you’re either too young; as it was released in 1982, or you never hanged out in many arcades as a child.
Nibbler was originally the first game to feature a billion point scoring system, which at the time I guess was even more important than graphics. In fact, I believe someone did manage to reach the billion point after playing the game straight for more than 48 hours!
For a long time, I pondered on the game design and mechanics of Nibbler; you know it isn’t the best game out there (in the eyes of most) it’s rather dull. However, it is certainly the fastest game you’ll ever experience. I can’t think of any other game that allows you to complete a level in 2 or 3 seconds! Yes, it gets that fast! There’s only a handful of levels that repeat over and over yet all of us (me and my friends) just wanted to play the game more and more, as if we suffered from an OCD to play this game until we dropped. And sometimes we would, after a dozen hours or so. ![]()
But the interesting thing about Nibbler is it allowed the dedicated soul to play the game for endless hours. Once you figured out the patterns for each maze, you could clear the maze with your eyes closed, literally. But be a split millisecond too slow and you would crash hard!
My attempt to recreate the game is not so much an attempt to deliver a faithful representation of the game, but to allow you to play it (if you should so decide to do so) for hours upon hours, or days even, and make it as fast as the original. That’s easier said then done, considering the browser containment, performance, memory leaks and constrained only to keyboard input as opposed to an arcade style joystick. So at least, that’s my goal.
My first impression is that I think it might be finally possible with Silverlight, but it’s going to be tricky. Note, the entire game is XAML based and designed to play in a 1000×1000 pixel canvas! So the fidelity of the game is quite… HD and therefore performance issues lurking. There’s also some crazy cool control template stuff going on in regards to the levels. I might however start looking into a raster based version in Silverlight 3 when it’s released.
Well anyway, you can checkout and play the game over at SilverArcade.com.
Thanks,
–Bill Sithiro
Frog Puzzle
Have you ever found yourself with no Internet connection, no computer, no TV, or anything to entertain yourself with after a hard day’s work? I caught myself at such a time once (luckily, only for just a week) and my only amusement was a little puzzle game I managed to pickup for just a dollar or two in a remote oddities store. The game was simple; it had no instructions and consisted of just 9 pieces. Your goal was to place the pieces as such so as the frogs depicted were all lined up. Seems simple right? Boy, I tell you, did I had a hard time solving it! Anyway, I took a picture with my mobile phone once I solved it (see bellow) so I could remember the solution next time I would play it. Unfortunately, I lost the puzzle and all I had to remind me of it was this picture. Fortunately, I had some spare time in hands recently, so I decided to recreate the puzzle game in Silverlight 2. And this time, it was just as fun making it as it was playing it.

Odd, isn’t it?
The original game took me a couple of hours to solve. In my version, I’ve included a little hint to help you solve it quicker. See if you can pick up on it.
Thank you,
–Bill Sithiro
CalcLight – The under 10kB Silverlight spreadsheet
Every year Microsoft organises a great conference named MIX that is about web design and development. It’s probably better you visit the official site for a better description, as what I want to blog about is the little competition the MIX09 organisers launched last month (December 2008). The idea behind the competition is to create ”something for the web” in Silverlight, WPF browser application or WPF Click Once application in under 10kB of code. As the competition is now over, I thought I would post a blog on my competition entry, CalcLight.
But before I begin, let’s travel back in time to the days of the console and DOS and look at the source code for a spreadsheet written for Turbo Pascal 3. Borland used to release little samples like MicroCalc in their Pascal and C++ development IDE’s. Now, the point of this is to look at the amount of code required to handle a formula. Keep in mind, that there’s is no UI in the MicroCalc sample and you could write a better expression parser now days, but the things that could go wrong in terms of data entry still remain numerous. In fact, to do it properly just a decent parser itself would exceed the 10kB limit. So, how on Earth do you then create a fully functional spreadsheet application with a UI plus all the spreadsheet plumbing in under 10Kb? And the answer is… by taking shortcuts. Enter JavaScript!
When I decided to make CalcLight, my software estimation skills told me that no way I could make it handle formulas plus the UI under the contest’s size limit (although perhaps with just a few more kilobytes it might have been possible). However, I did notice that nothing was stopping me from using JavaScript to handle the expressions. In that case, all I needed to do was simply parse the formula for direct cell values and then simply pass the parsed formula to JavaScript to evaluate. Here’s some sample code to setup usage with JavaScript within Silverlight:
1: HtmlElement scriptHost=HtmlPage.Document.CreateElement("script");
2: scriptHost.SetAttribute("type","text/javascript");
3: scriptHost.SetProperty("text","function Evaluate(exp){try{return eval(exp);}catch(e){return "#VALUE!";}}");
4: HtmlPage.Document.DocumentElement.AppendChild(scriptHost);
Our Silverlight application is now ready to execute the Evaluate function. But we’re not quite done yet, although this would work nicely for something like this:
1: HtmlPage.Window.Invoke("Evaluate", "((10 * 3.5) / (234 + 123 + 232.23)) * 2");
However, what we’re hoping to do is also pass cell names instead of just direct values. And these cells may just as well contain other formulas pointing to other cells and so on. Things are getting a little more complicated, but nothing out of hand. The way CalcLight works, every cell is a class. The Cell class contains three methods to help us solve the above problem. Additionally, we have an instance (named Cells) of a static Dictionary<String,Cell> with all our cell instances to assist us:
1: string[] symb = { "=", "+", "-", "/", "*", "(", ")", ",", "?", ":", "<", ">" };
2:
3: string Parse(string x)
4: {
5: x = x.Replace(" ", "");
6: var arr = x.Split(symb, StringSplitOptions.RemoveEmptyEntries);
7: var d = from i in arr orderby i descending select i;
8: foreach(var item in d)
9: {
10: var v = Regex.Replace(item, "^[A-Z]{1,2}[0-9]{1,3}$", Cell.GetValue(item, this), RegexOptions.None);
11: x = x.Replace(item, v);
12: }
13: return x;
14: }
15:
16: static string GetValue(string cid, Cell cell)
17: {
18: if (Cells.ContainsKey(cid))
19: {
20: var c = Cells[cid];
21: if (c != null)
22: {
23: if (c != cell)
24: return c.Evaluate(c.Text);
25: else
26: return "!CIRCULAR!";
27: }
28: else
29: return cid;
30: }
31: else
32: return cid;
33: }
34:
35: string Evaluate(string x)
36: {
37: if (x.StartsWith("="))
38: {
39: try
40: {
41: return HtmlPage.Window.Invoke("Evaluate", Parse(x).Replace("=", "")).ToString();
42: }
43: catch (Exception)
44: {
45: return "#VALUE!";
46: }
47: }
48: else
49: return x;
50: }
The entry point of the above snippet is the Evaluate function. We pass a formula to the Evaluate function (e.g. =A1+B1) which in turn calls Parse with the formula and will enter a state of recursion for each cell in the formula until the entire formula(s) are evaluated. Notice, we also check for situations where a cell references itself . This is known as a circular reference. However, there is also the case of one cell reference another that in turn references the first. This is also a circular reference. To make a long story short it results in a stack overflow, something not handled very gracefully in Silverlight and when I first tested for that, it crashed every single browser I checked it with! Luckily, we can fix this easily, and you can use this technique elsewhere as well. But we need to make some slight modifications:
First, we need a static variable to keep count of how many iterations the GetValue method is being called. We’ll just call it ITR for iteration:
1: static int ITR = 0;
Next, we need to re-initialise it in the exit point (finally clause) of the Evaluate method:
1: string Evaluate(string x)
2: {
3: if (x.StartsWith("="))
4: {
5: try
6: {
7: return HtmlPage.Window.Invoke("Evaluate", Parse(x).Replace("=", "")).ToString();
8: }
9: catch (Exception)
10: {
11: return "#VALUE!";
12: }
13: finally
14: {
15: ITR = 0;
16: }
17: }
18: else
19: return x;
20: }
Secondly, we’re incrementing the counter every time GetValue is called.
1: static string GetValue(string cid, Cell cell)
2: {
3: ITR++;
4:
5: if (Cells.ContainsKey(cid))
6: {
7: var c = Cells[cid];
8: if (c != null)
9: {
10: if (c != cell)
11: return c.Evaluate(c.Text);
12: else
13: return "!CIRCULAR!";
14: }
15: else
16: return cid;
17: }
18: else
19: return cid;
20: }
Now, all we need is a switch that will make sense as an indication that we’re ‘cruising for a bruising’ (stack overflow). We do this in the Parse function and we simply add the following line:
1: string Parse(string x)
2: {
3: if (ITR > 3000)
4: {
5: ITR=0;
6: return "!OVERFLOW!";
7: }
8:
9: x = x.Replace(" ", "");
10: var arr = x.Split(symb, StringSplitOptions.RemoveEmptyEntries);
11: var d = from i in arr orderby i descending select i;
12: foreach(var item in d)
13: {
14: var v = Regex.Replace(item,"^[A-Z]{1,2}[0-9]{1,3}$", Cell.GetValue(item, this), RegexOptions.None);
15: x = x.Replace(item, v);
16: }
17: return x;
18: }
Basically, if our counter has exceeded 3000 iterations it’s time to call it quits and return an error. Now, 3000 is just a guess, it could work just as well with 5 or maybe 10 thousand iterations. I’m not sure, I haven’t really tested it to that detail, but do note however that the larger this number is the larger the amount of formulas you can resolve i.e. recursion deep resolving (e.g. cell 1 points to cell 2, cell 2 points to cell 3 and so on). We want to keep at something practical and remember our primary goal is trying to catch circular references with the less amount of code as possible.
The Parse method is very interesting as this is where we do the actual formula parsing. This is how it works, we give it an expression and we strip out all the whitespace. Secondly, we split the formula from symbols and are left with an array of strings. Now these strings, maybe cell names, maybe number values, maybe function names, or simply text, but all we care about is cell names. We apply a regular expression pattern to test for exactly that, and call GetValue to evaluate the cell’s value. But what’s that LINQ statement you might ask? Why is it important to sort the array in descending order? This catches formulas where we have something like this: =B1+B11. This helps our Regex pattern matching distinguish from B1 and B11 by first evaluating the later cell first.
And that’s about it regarding CalcLight’s formula parsing shortcut. Use JavaScript in your SilverLight projects whenever you can; it’s easier to add functionality and avoid caching problems in browsers with .xap’s. However, also note Silverlight features like Regular Expressions and LINQ that made the formula parsing not only a breeze but in a fraction of code! Compare it with the old-school Pascal source code shown above to appreciate today’s modern coding features.
Finally, one feature I didn’t manage to get in the size limit, sadly, is range cells (e.g. A1:C10) but hey, it’s time to worry about the UI now. And no JavaScript is going to help us pull off the next stunt of visualising 10 thousand cells!
Thank You,
-Bill Sithiro
ASP.NET – A Dynamic Image Server Control – Part 1
As you already know if you’re an ASP.NET developer, a server control renders pure HTML that is embedded into the page the server control is hosted. But what if you wanted to display a dynamic image on the page. Since the server control renders only HTML it would have to render some <img> tag pointing to some location on your web server or other. You could argue that instead of placing a custom made server control on the page just place an ASP.NET Image server control and target it appropriately. It could let’s say target an .aspx page that renders a dynamic image. But that just doesn’t feels right for a dynamic image. It’s not something some one can simply get out of the toolbox and drop it on the page in a nice componentized manner. Furthermore, customize it using the property editor and see how it looks even in design mode. That’s much better, but how?
Unfortunately, the answer is not so straightforward but for some things it can be. If you wanted to display let’s say a small image, for example a CAPTCHA, you could use the HTML URL scheme data:[<mediatype>][;base64],<data> that embeds the raw image data inside the page as Base64 characters:
1: protected override void RenderContents(HtmlTextWriter output)
2: {
3: using (Bitmap bitmap = new System.Drawing.Bitmap(40, 20))
4: {
5: using (Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
6: {
7: graphics.Clear(Color.Red);
8: graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
9: Font font = new Font("Arial", 8, FontStyle.Bold);
10: graphics.DrawString("HeLlo", font, Brushes.White, 3, 3);
11: output.Write(string.Format("<img src="data:image/png;base64,{0}">",
12: ImageToBase64(bitmap, ImageFormat.Png)));
13: }
14: }
15: }
16:
17: protected string ImageToBase64(System.Drawing.Image image, ImageFormat format)
18: {
19: using (MemoryStream ms = new MemoryStream())
20: {
21: // Convert Image to byte[]
22: image.Save(ms, format);
23: byte[] imageBytes = ms.ToArray();
24:
25: // Convert byte[] to Base64 String
26: return Convert.ToBase64String(imageBytes);
27: }
28: }
To be continued…
Art of Solitaire – Silverlight 2 Card Game
This a Hi-Lo Solitaire game I wrote way back in Silverlight 1.1 Alpha and that I recently updated to Silverlight 2. At the time of writing, Silvelright 1.1 Alpha didn’t have a way of updating the screen programmatically, and the only way to do it, was by defining an event handler of a StoryBoard.Completed event. I recall there was also an HtmlTimer but it just wasn’t fast enough. Of course, having concurrent animations all over the place starting at different intervals with only one StoryBoard was challenging enough, and I didn’t want a StoryBoard for every single object on the screen that would probably kill performance too. So, I distributed all the animations between four StoryBoards.
Now there’s Timers, Threads and CompositionTarget event rendering along with StoryBoard so you can take your pick on what method to use which I find quite nice. Click the image bellow to play!
Thank you,
–Bill Sithiro

