Published Thursday, May 03, 2007 5:10 PM by mtaulty

Porting some old C# code to Silverlight

For me, the big thing about Silverlight is .NET and it may even get me to the point where I'm happier to try manipulating the HTML DOM from time to time Silverlight lets me do that in a nice way from .NET (I haven't tried yet but I did spy some classes in there).

I wanted to take a bit of old code (and this is very old code) and see how hard it would be to "Silverlight" it.

I took my old game of Tetris (which doesn't quite work properly) and ripped off the Windows Forms front end and added a Silverlight front end.

Because it's Silverlight it didn't seem right not to have a video in there so I put the Tetris pieces on top of the Silverlight video from the main site (http://www.microsoft.com/silverlight) after transcoding it a bit with Expression Media Encoder to try and reduce the size (I lost a bit of quality too I'm afraid but then that video was originally 720p and 25MB! :-))

I found moving this code over to Silverlight to be pretty easy with the hard bit trying to understand the Tetris code that I had in the past because I lost the source for it once and rebuilt it from ILDASM so it's messy.

Interestingly, for me, the hardest bit about this was that I was moving it from Windows Forms to Silverlight. In Windows Forms there's no retained graphics and so you have to remember where you put everything on the screen which means you need perhaps to maintain different data structures than in Silverlight where the graphics system remembers things for you.

Additionally, there's a lot I could to in Silverlight to make the performance a lot smoother and perhaps apply some nice animations. For instance, I rotate the game pieces manually (because that's how the code already was) whereas Silverlight could do that for me. Not sure what it could do for me in terms of detecting collisions but I bet there's something there as well.

The game ticks on a 150ms timer. I'm using the HtmlTimer class which is deprecated in the framework already so it perhaps indicates something else to come in the timer space. I tried System.Threading.Timer but that leaves you with the age old problem of thread affinity and I didn't see an obvious way to solve it so HtmlTimer worked fine.

( if you actually want to play the game, it's the 'q' key for left, 'w' for right and 'a' and 's' for rotate left and right - I couldn't find a set of Keys properties anywhere so I hard-coded character codes in there :-)).

I'm not willing to share the source for this - it's abysmal but I had a bit of fun trying it out (there's definitely also some funnies in the game engine as well).

# Custom animation using timers in WPF and Silverlight 1.1 @ Friday, May 04, 2007 6:01 AM

WPF comes with great support for animation using XAML without needing to code this in for example C#.

Erwyn van der Meer