Introduction

This article is a bit of an excursion for me, and it will be somewhat lighter than my usual articles. The tech that you are reading about in this article was only published last week, so I hope I can be forgiven for not going into depth for each and every feature. We will be taking a first look at Windows Phone 7, and creating a puzzle game using Silverlight and features of the XNA framework audio API.

Background

Last week at MIX10, Microsoft announced the release of the developer tools for the new Windows Phone 7. Like many developers, I was pretty happy about this. The MIX10 Developer conference 2010, which began at Las Vegas Monday last week, saw Microsoft focus specifically on its Microsoft Windows 7 phone and developer tools for the same. I spent all of last weekend putting this game together, and playing around with the new WP7 goodness. The verdict? I really like it. It's a familiar environment, Silverlight and XNA, and I believe it will have a big impact on the mobile phone landscape. Like many developers, I have felt a little jealous of the iPhone devs, making their fun little apps. Seemingly making wads of cash from apps as absurd as the iFart. It's mostly hype I believe, with the market place being highly competitive these days. But still, I would have liked to have gotten a taste of that scene, but alas had neither the time nor inclination to jump into the Apple world with Objective-c. Yes, Novell has its iPhone Touch, and I had contemplated taking it for a ride. But still, I believe I would end up feeling like I was trying to push a square block through a round hole.

Enter WP7. Now Microsoft has hit the ball out of the park, seriously. Yes yes, I know I sound like a bit of a fanboy, but I'm pleased that this stuff has hit the scene. In 2008, with version 1.1 of Silverlight (the first version that used .NET), I predicted that Silverlight would be huge. Ok, that was an easy call, but it's clear now that Windows Phone is set to make a massive impact. We have the familiar development environment of Visual Studio, a technology that is terrific for building flexible and dynamic interfaces, Silverlight, and finally the market place. All the ingredients for a perfect storm!

So in order to try out WP7, I've brought back my Mike Wazowski lookalike character for another incarnation of Alien Sokoban! I wrote much of the game logic for this game a couple of years ago for another article in Silverlight. Back then Silverlight for .NET had yet to have a proper release, it was version 1.1 and we didn't even have a baked in textbox; we had to roll our own. My, how times have changed. Now with the latest version of Silverlight, we have a cavalcade of new features. Web Cam, VSM, Com Interop, Multicast streaming, the list goes on and on. (but alas, still no baked in menu control yet!).

Windows Phone 7 uses Silverlight 3. The developer tools include an emulator, which is in fact a virtual machine. This is great, because it's like having the phone, without having the phone, which is helpful because I don't have the phone. There is full developer integration in Visual Studio; we have a debugger, and we can hover over variables in the code editor, etc., just like in Silverlight.

Getting Started

Installation of the WP7 Tools

Install the Windows Phone developer tools CTP, and don't forget to read the release notes. Note that if you have Visual Studio 2010 RC, (note that you need the RC or later, and you can't have a beta installed on the same machine), then the tools will be integrated into the existing Visual Studio installation, otherwise Visual Studio 2010 Express will be installed.

Figure: Installing the Windows Phone 7 Developer Tools CTP

The setup program will automatically download and install the required components.

Developers will feel completely at home within Visual Studio 2010, when working with Windows Phones apps. Here, we see that we are able to work directly with the designer, with a visual representation of the workable phone area to guide us.

PageOrientation

One of the most obvious implications of hosting an application in a Windows Phone application is how to contend with layout orientation, and in particular detecting when orientation changes, and whether we deem our UI compatible with particular orientations. The PhoneApplicationPage has a settable property named SupportedOrientations. This enum value may be either Landscape, Portrait, or PortraitOrLandscape. By assigning it a value, either in XAML or in code, we are able to restrict how an application can be viewed. For Alien Sokoban, I went with PortraitOrLandscape, because I wished to provide the user with the ability to rotate the game grid depending on its dimensions. One thing of note is that setting the orientation from user code is not possible, as it is marked as SecurityCritical. We can see this in Reflector when we browse to the Page.Orientation property.

Figure: Page.Orientation property is SecurityCritical

SecurityCritical is a familiar attribute to most Silverlight developers. It means that an exception will ensue if we attempt to call it, and thus it's off limits. You can find more about Silverlight's code security model here.

Please note that this is Silverlight security, and is not specific to Windows Phone. It just goes to show that Windows Phone uses the full version of Silverlight, and not Silverlight Light.

From reflector, we can observe that Page.Orientation is not a dependency property, (nor does it raise a PropertyChanged event), and nor are any of its other properties for that matter. Therefore, binding to a PhoneApplicationPage property won't get us anywhere.

OrientationToVisibilityConverter

The way to detect and update page elements is not immediately possible without some extra work in the code beside. I wanted to hide the 'Alien Sokoban' title depending on the orientation, because it's too wide to present when the orientation is portrait. I could have simply set the Visibility in the OrientationChanged event handler, but I instead created a new dependency property on the MainPage which is updated when the OrientationChanged event handler is called. In order to convert the orientation value, I created an IValueConverter, and consume it from XAML. When the Page.Orientation property changes, the binding for the Visibility of the title TextBlock changes.

A ConverterParameter "Landscape" is used to specify that we wish to show the TextBlock only when the Page.Orientation property is of a landscape kind, which includes the values Landscape, LandscapeLeft, or LandscapeRight. The following is an excerpt from the OrientationToVisibilityConverter, which shows how the converter changes a PageOrientation value to a Visibility value:

Using the XNA Framework Audio API

I was pleasantly surprised just how easy it is easy to use the XNA framework to play sound effects. It is good for short samples, where instant playback is required. Be warned however that it is fussy about the format. I found that only PCM format wav files were supported. I used GoldWave to save all audio to a PCM format. For longer clips, it makes more sense to use a more space efficient format, such as mp3, but for this you'll need to use the MediaElement control.

All sound effects are defined in the MainPage.xaml.cs code beside as the following excerpt demonstrates:

Be aware that the Build Action of all audio files, which are intended to be played by the XNA framework, needs to be set as Content.

Figure: Audio file Build Action must be set to Content.

When using the MediaPlayer element in Silverlight in the past, I've noticed there can be a short delay when queuing media. Using the XNA framework, playback is instantaneous; a critical requirement for sound effects.

MainPage Bindings

During instantiation, the MainPage has a Game instance assigned as its DataContext. Mostly all of its activities are controlled by data binding and Game property changes. The MainPage is provided here in its entirety:

Ordinarily, I wouldn't recommend placing this kind of UI logic code in the code beside, as I prefer using a MVVM approach. However, in the interests of expediency, I went with this approach.

The CellControl is assigned a Game cell, and changes its visual depending on the cell's state. If it is deemed a wall, it shows a grey square, etc.

Game Play

Please see the video of the game for an overview of how to play the game. The game logic has also been documented here and here.

Phone On-Screen Keyboard

Windows Phone 7 allow the developer to specify the type of data that a user is able to enter via the on-screen keyboard. It is also context sensitive, and will zoom into a TextBox when the TextBox gains focus. To change the keyboard to something that is more applicable to the data that is being entered, an InputScope is used.

Figure: Enter level code using On Screen Display

For example, to specify a variation to the default on-screen keyboard (as shown above), apply an InputScope element to the TextBox.

Conclusion

In this article, we have seen how to create a Windows Phone puzzle game using Silverlight 3. We have looked at PageOrientation and how it applies to control layout. We examined the on-screen keyboard, and how different keyboards can be selected based on context, and we also briefly looked at the XNA Framework audio API, and how it can be used to play sound effects.

I'm very excited about the future of this platform. After spending only a brief amount of time with it, I feel at home already. I hope you find this project useful. If so, then I'd appreciate it if you would rate it and/or leave feedback below. This will help me to make my next article better.

Share

About the Author

Daniel Vaughan is a Microsoft MVP and co-founder of Outcoder, a Swiss software and consulting company dedicated to creating best-of-breed user experiences and leading-edge back-end solutions, using the Microsoft stack of technologies--in particular WPF, WinRT, Windows Phone, and also Xamarin.Forms.

Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.

Daniel is the developer behind several acclaimed Windows Phone apps including Surfy, Intellicam, and Splashbox; and is the creator of a number of popular open-source projects including Calcium SDK, and Clog.

Would you like Daniel to bring value to your organisation? Please contact

Thanks for the article - it's very informative. This is the first Windows Phone 7 app
that I've run on VS2010, so I'm not sure if my VS2010 behavior is normal or not...
I am getting runtime error messages when I run the app in VS2010 Pro, although
they seem to have no effect on the app (it seems to work despite these messages):

(1) when I select "Start Debugging" the WP7 emulator starts, Sokoban is deployed to it,
and the app seems to work, but I get an error dialog box with "Object reference not
set to an instance of an object"

(2) when I instead select "Start Without Debugging", the game also loads and runs in the
emulator, but I get the following error message "Application 00000000-0000-0000-0000-000000000000
is not installed on the device" (although I don't get the Object reference error message).

Do you experience the same behaviors when you run the app in the emulator? Do you have
any ideas about how to fix this?

Yes - I've run the four simple Windows Phone sample apps that I think came with the
Windows Phone Tools - ApplicationBarSample, AccelerometerSample, MiniBrowser,
and LocationServiceSample (and none of them generate these errors), but this
is the only one that uses Silverlight. I'll check with Microsoft Support about
these errors.

OK - Microsoft 1st said this is a known bug in the case where the user selects the Solution instead of a Project (but selecting the Solution didn't help). Then Microsoft said this is a known bug where if you don't open at least one file these error messages occur (and that didn't help either). Then I realized that Sokoban.Phone was set as the StartUp project instead of Sokoban.Phone.UI - making Sokoban.Phone.UI the StartUp project makes these error messages go away. I re-downloaded your zip and noticed that Sokoban.Phone is set as the StartUp project. So it seems that my problem was really due to my unfamiliarity with VS (it's been some years since I last used it) and the Project references. I'll let Microsoft know what their error messages mean...

Wow, this is an excellent article! I am new to Silverlight and slowly trying to comprehend and make sense of things. I've been reading about silverlight in blogs and other tutorials and your article is the perfect way for me to step up a level (pun intended ) in Silverlight. I am going to dig into your code and recommend it to others too. Thanks for sharing the code and taking the time to explain.