December 2010

Volume 25 Number 12

Windows Phone 7 Development: Sudoku for Windows Phone 7

By Adam Miller | December 2010

Sudoku has become a popular game over the last 10 years, finding a home in most newspapers right next to the crossword puzzle. Game shows based on Sudoku have even been created. If you’re unfamiliar with it, Sudoku is a number placement game. The game board is a 9x9 grid and the goal is to place the numbers 1-9 in the grid such that each row, column and sub 3x3 grid contains each number once. The nature of the game lends itself nicely to play on a portable device, and Windows Phone 7 should be no exception. You can soon expect a handful of Sudoku applications in the marketplace after the recent release of Windows Phone 7, and you can even add your own to that list by following this article.

MVVM Introduction

My application will roughly follow the Model-View-ViewModel (MVVM) design pattern. Although there won’t be any actual Models (because this app doesn’t require database storage), it will still be a good learning tool because the ViewModel is really the core of the pattern.

There can be a bit of a learning curve to understand the MVVM pattern, but once it clicks, you’ll find you can get a really nice separation between the UI and business logic. Furthermore, it reveals the power of data binding in Silverlight while freeing you from the majority of the tedious code of updating a UI (FirstNameTextBox.Text = MyPerson.FirstName will be a thing of the past!). For more information about data binding in Silverlight, take a look at the MSDN Library article “Data Binding” at tinyurl.com/SLdatabind.

Because of the size and simplicity of this app, and the focus of this article, a third-party MVVM framework won’t be used. However, it’s likely that your application will grow to be more complex than this one, and you’d be wise to start with a third-party framework such as the MVVM Light Toolkit (mvvmlight.codeplex.com). It will provide you with free, tested code that you’ll end up writing anyway (noted from experience).

Creating the Application

Start by creating your new Windows Phone 7 project by opening Visual Studio and selecting File | New | Project, then in the new project dialog, Visual C# | Silverlight for Windows Phone | Windows Phone Application. Start by creating two new folders, Views and ViewModels, following a common MVVM pattern. At this point, you can also start debugging if you want to take a peek at the emulator provided as part of the SDK.

The Sudoku game can be broken down into three conceptual types: each of the individual squares (81 total in the typical 9x9 board); the overall game board that houses the squares; and a grid for the numbers 1-9 for input. To create the views for these items, right-click on the Views folder and select Add | New Item. Select Windows Phone User Control from the dialog and name the first file GameBoardView.xaml. Repeat for SquareView.xaml and InputView.xaml. Now, in the ViewModel folder, add the following classes: GameBoardViewModel and SquareViewModel. The Input View won’t require a ViewModel. You’ll also want to create a base class for your ViewModels to avoid code duplication. Add a ViewModelBase class to your ViewModels folder. At this point, your solution should look similar to Figure 1.

image: Sudoku Windows Phone 7 Solution with Views and ViewModels

Figure 1 Sudoku Windows Phone 7 Solution with Views and ViewModels

ViewModel Base Class

The ViewModelBase class will need to implement the INotifyPropertyChanged interface found in System.ComponentModel. This interface is what allows the public properties in ViewModels to bind to controls in the views. The implementation of the INotifyPropertyChanged interface is pretty simple—only the PropertyChanged event must be implemented. Your ViewModelBase.cs class should look similar to the following (don’t forget the using statement for System.ComponentModel):

Most of the third-party MVVM frameworks will include a ViewModel base class that contains this boilerplate code. All of your ViewModels will inherit from ViewModelBase. The properties in a ViewModel that the UI will bind to need to call NotifyPropertyChanged in the setter. This is what allows the UI to automatically update when the value of a property changes. It does get a bit tedious implementing all of your properties in this way, so it’s a bit of a tradeoff for the code that you don’t have to write to update the UI.

Implementing the Individual Squares

Start by implementing the SquareViewModel class. Add public properties for Value, Row and Column as integers; and IsSelected, IsValid and IsEditable as Booleans. Although the UI can bind to the Value property directly, this will cause issues because “0” will be displayed for unassigned squares. To resolve this, you can either implement a binding converter or create a read-only “StringValue” property that will return an empty string when the Value property is zero.

The SquareViewModel will also be responsible for notifying the UI of its current state. The four states for an individual square in this app are Default, Invalid, Selected and UnEditable. Normally this would be implemented as an enum; however, enums in the Silverlight framework don’t have a couple of the methods that enums in the full Microsoft .NET Framework have. This causes an exception to be thrown during serialization, so the states have been implemented as constants:

Now, open SquareView.xaml. You’ll notice some styles have been applied at the control level for the font size and color. The preset style resources are usually found in a separate resources file, but in this case, Windows Phone 7 provides them to your application by default. The resources are described on the MSDN Library page, “Theme Resources for Windows Phone,” at msdn.microsoft.com/library/windows/apps/ff769552(v=vs.105).aspx. Some of these styles will be used in this application so the application colors will match the user-selected theme. The theme can be selected in the emulator by going to the home screen and clicking the more arrow | Settings | theme. From here you can change the background and accent colors (Figure 2).

image: Windows Phone 7 Theme Settings Screen

Figure 2 Windows Phone 7 Theme Settings Screen

Inside the grid in SquareView.xaml, place a Border and a TextBlock:

The code-behind for SquareView.xaml.cs can be seen in the accompanying code download. The constructor requires an instance of the SquareViewModel. This will be provided when the game board is bound. Also, there’s a custom event raised when the user clicks inside the grid. Using custom events is one way to allow ViewModels to communicate with each other; however, for larger applications, this approach can get messy. Another option is to implement a Messenger class that will facilitate the communication. Most MVVM frameworks provide a Messenger (sometimes referred to as Mediator) class.

It may seem messy from an MVVM purist’s standpoint to update the UI using the code-behind, but these items don’t lend themselves nicely to a BindingConverter. The BoxGridBorder’s BorderThickness is based on two properties, and the Foreground and Background brushes come from the application resources, which aren’t readily accessible in a BindingConverter.

Implementing the Game Board

The GameBoard view and ViewModel can now be implemented. The view is simple, just a 9x9 grid. The code-behind, available in the code download, is almost as simple—just a public property to expose the ViewModel and a couple private methods to handle the child box click and binding the game array.

 The ViewModel contains the bulk of the code. It contains methods to validate the board after user input, to solve the puzzle and to save and load the board from storage. The board is serialized to XML when saving, and IsolatedStorage is used to save the file. For full implementation, please see the source code download; the storage code is of most interest and is shown in Figure 3 (note that you’ll need a reference to System.Xml.Serialization).

Figure 3 The Board Storage Code

Implementing the Input Grid

The input view is simple as well, just some buttons nested in stackpanels. The code-behind, shown in Figure 4, exposes a custom event to send the clicked button’s value to the application, as well as two methods that will assist in making this game playable in portrait or landscape mode.

Figure 4 The Code-Behind for the Input View

Bringing Views Together on MainPage.xaml

Finally, the application is brought together with the implementation of MainPage.xaml. The Input and GameBoard views are placed in a grid. This application will require all of the screen real estate available, so the PageTitle TextBlock that was automatically inserted when the project was created has to be removed. The ApplicationTitle TextBlock will only be visible in portrait mode. The Windows Phone 7 Application Bar will also be taken advantage of. Using the Application Bar will make the application feel more integrated with the phone and will provide the Sudoku application a nice interface to allow the user to solve, reset and start a new puzzle:

The images are taken from a set of icons provided by Microsoft specifically for Windows Phone 7 that are installed with the tools at C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.0\Icons. After images are imported into the project, select the image properties and change Build Action from “Resource” to “Content” and Copy to Output Directory from “Do Not Copy” to “Copy If Newer.”

The final piece of this application puzzle is to implement the MainPage code-behind. In the constructor, the SupportedOrientations property is set to allow the application to rotate when the user rotates the phone. Also, the InputView’s SendInput event is handled and the input value is forwarded to the GameBoard:

The Navigation methods also need to be implemented to handle loading and saving the game board:

When the phone is rotated, the application will receive a notification. This is where the InputView moves from below the game board to the right of it and is rotated (see Figure 5).

Figure 5 Code to Handle Phone Rotation

This is also where the menu item clicks are handled:

At this point, the game is complete and playable (see Figures 6 and 7).

image: Sudoku Game in Portrait Mode

Figure 6 Sudoku Game in Portrait Mode

image: Solved Game in Landscape Mode

Figure 7 Solved Game in Landscape Mode

So there you have it, a nice game waiting for you the next time you’re waiting in line. This article has demonstrated how to get started creating Silverlight-based Windows Phone 7 applications. Also, it has shown how to use serialization and user storage to persist an application and how to allow your application to support multiple orientations. In addition, you should now be familiar with the MVVM pattern and how to use data binding with it.


Adam Miller is a software engineer for Nebraska Global in Lincoln, Neb. You can follow him at blog.milrr.com.

Thanks to the following technical experts for reviewing this article: Larry Lieberman and Nick Sherrill