Free tools and easy setup make development easy
Windows Phone 7, as you know, is Microsoft’s new Smartphone OS. One of the most exciting things about Windows Phone 7 is that it features a third-party application platform based on existing Microsoft technologies and tools; technologies and tools that are free, easy, and fun to use. You can use these tools to build applications that are relevant not only for the phone, but also for the desktop PC, Xbox 360, and the Web.
In this article, we’ll introduce you to these tools and technologies as we build a relatively basic game using Visual Studio 2010 and Silverlight. We’ll demonstrate how easy it is to install the tools and create compelling phone applications. If you're new to Silverlight, you might want to visit the Silverlight learning site at http://silverlight.net/learn. If you're familiar with Silverlight or its predecessor, Windows Presentation Foundation (WPF), you’ll feel right at home.
Meet the Tools
If you’re anything like us, you hate how complicated it can be to set up your computer to write software for a specific platform. Historically, in Windows Mobile, setup was painful; first you’d have to purchase Visual Studio Professional (more than $800) and go through its lengthy installation. Then you’d have to download an SDK, a follow on DTK, and one or multiple device emulator images to test your application against different languages. Often, this could add up to eight or nine different packages to download and install, in the correct order.
With Windows Phone, all you need to download is a small stub installation bootstrap application. This setup application will detect and determine what you have installed on your machine and download and install only what you need. In the current release, the complete tool chain is free. Included in the installation are the following components:
- Microsoft Visual Studio 2010 Express for Windows Phone (your IDE)
- Microsoft Expression Blend 4 for Windows Phone
- .NET Framework reference assemblies for Windows Phone, both Silverlight and XNA Framework
- The Windows Phone Emulator, which includes a complete version of the Windows Phone OS that you can use to test and debug your applications
- The Windows Phone Registration tool, which allows you to unlock a hardware device for development purposes
To start, visit the App Hub at http://create.msdn.com. App Hub (Figure 1) is a single online destination for the Windows Phone developer. At App Hub, you’ll be able to download the tools and find all the official developer educational materials published by Microsoft. You also can register with the Windows Phone Marketplace so that you can publish your application to the world.
Building a Puzzle Game
In this article, we’ll walk you through a Windows Phone Silverlight application project and show you how to create a simple, yet elegant puzzle game. We'll provide a basic overview of this project; if you're interested in a more in-depth view, visit the developer labs available as part of the Windows Phone 7 Training Kit (http://channel9.msdn.com/Learn/Courses/WP7TrainingKit).
After you’ve installed the Windows Phone Developer Tools, you’ll be able to create a new Silverlight for Windows Phone project based on one of a number of different templates (Figure 2). Each template is designed to start you off with a completely compilable application (albeit content free). The Panorama and Pivot application templates give you a fully working Windows Phone 7 application that leverages the Panorama or Pivot application style from the Windows Phone design system. This means it's easier than ever to create applications that use the same design paradigms introduced with Windows Phone 7.
For this project, we’ll begin with the default Windows Phone Application template. So select this template, provide a name, and click OK. After your new project is successfully created, Visual Studio displays the MainPage.xaml file in the editor by default. The default display for XAML files is a split view: one pane displays the XAML markup (XML text); the other displays a design view showing the generated user interface as described by the XAML (Figure 3). You’ll return to this view later, when you start adding controls to your application. But before we jump in to the code, let’s review the structure of a Silverlight Windows Phone application.
The basic project that you just created using the Silverlight for Windows Phone application template contains a number of files and folders. The following is a partial overview of the application structure. You can find more information in the online Windows Phone documentation (http://msdn.microsoft.com/en-us/library/ff630878(v=VS.92).aspx). The default Windows Phone Silverlight Application auto-generated project includes the following files:
- App.xaml and App.xaml.cs. These files define the application’s entry point and a set of application lifetime event handlers.
- MainPage.xaml and MainPage.xaml.cs. These files define a page (screen) with some UI elements and their associated code-behind components. This is also the default start page of the application as defined in App.xaml.
- ApplicationIcon.jpeg, Background.jpeg, and SplashScreenImage.jpeg. These files are the graphics assists associated with Windows Phone applications.
- The Properties folder includes additional files
- AppManifest.xml. This file is the standard Silverlight application manifest file. It contains details on everything in the packaged Windows Phone Silverlight application, such as the different DLLs that are part of the application.
- AssemblyInfo.cs. This file contains metadata information about the assembly.
- WMAppManifest.xml. This file is a manifest file that includes specific metadata related to a Windows Phone Silverlight application, including specific features available only for Silverlight for Windows Phone.
Although we won't change any of the default metadata information, this is where you'll need to make changes if your application uses the phone functionality, such as GPS, camera, and push notifications.
Let’s start modifying the default template by adding a new file to the project. In the Solution Explorer window, right click on the project name (this should be the second node in the tree view) and select Add - > New Item. In the resulting dialog box, select to create a new Windows Phone Portrait Page, name the page PuzzlePage.xaml, and click Add to execute the command. This file will be your main game page, where all game logic takes place.
Now let’s add a new button to our initial page, MainPage.xaml, which should still be open in the IDE. The purpose of this button is to take a user from an initial launch menu page to the puzzle. You have many ways to create controls in Visual Studio. In this instance, we’ll create the button by entering its description directly into the XAML XML text. Look at the XML for MainPage.xaml, and you'll find the following comment:
<!--ContentPanel - place additional content here--><br> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
To create the new button, place your cursor between the opening and closing Grid tags, and insert the following XML:
<Button Content="START!" BorderBrush="#f8f4df" Foreground="#f8f4df" <br> Name="StartButton" Grid.Row="1" <br> VerticalAlignment="Center" HorizontalAlignment="Center" <br> Click="StartButton_Click" />
Moving From One Page to the Other
Now we need to provide a way to navigate back and forth from the main page to the game page. The PhoneApplicationPage class provides methods and properties that let developers add page navigation to their application. This is accomplished by using the NavigationService property, which is similar—but not identical—to the NavigationService available in desktop Silverlight. Using the Navigation Service, you can call the Navigate method and pass the URI for the page that you want to navigate to. You can also use the GoBack method to navigate backward through the application’s page stack, which represents the page history of the application.
The hardware Back button also provides backward navigation within an application. By default, the hardware Back button automatically navigates back in the application. You can override this default behavior, but it's not recommended because end users will grow accustomed to using the Back button.
Using the NavigationService is simple; call the Navigate method and pass as a parameter the URI of the page you wish to navigate to, as shown in the following code snippet (which is part of the Start button Click event handler). You can quickly access this event handler by simply double clicking the Start Button in the form design window for MainPage.xaml; this will open the code-behind file MainPage.xaml.cs, at the correct location for this event handler. Insert the following method call:
this.NavigationService.Navigate(new Uri("/PuzzlePage.xaml", UriKind.Relative));
If you compile and run your project at its current stage, your application will run in the Windows Phone Emulator. If you click on the Start button, the phone will navigate to the puzzle page (which is empty at this stage). Press the hardware Back button to navigate back to the main page. Press the hardware Back button once more and you'll exit the game.
All Windows Phone devices feature a Back button that takes a user to the previous screen. This button lets the user navigate back in a given application and even between applications. Unlike other phones, users can navigate from your application to other phone applications like the browser, maps, or their contact list and then press the Back button to seamlessly return to your application. This yields a much more consistent user experience across different applications, whether they are third-party applications or part of the phone's built-in application suite.
The primary mechanisms for navigation in Windows Phone 7 are the Back and Start (Windows flag) buttons, which are both required hardware buttons on the front of the phone. The Start button always returns the user to the Start screen; the Back button always traverses the back stack. By pressing Start, users can navigate and launch other applications.
Relaunching your application via the Back button causes an event to fire that you should use to "rehydrate" your application, bringing a user back to the exact state he saw when he left. If a user relaunches your application from its menu icon or Start Tile, after having left your application via Start, the convention is that you provide the user a new, fresh instance of your application at the default starting place.
Adding the Puzzle User Interface and Logic
The PuzzlePage we created is still empty. It's time to add UI elements and game logic to the page. When navigating to the PuzzlePage it displays an image that, when clicked, is broken down into eight different pieces, which are then rearranged on the board in random fashion. The goal of the game is to solve the puzzle by moving the different pieces into position, which Figure 4 shows.
First, we’ll create the layout of the controls on the page and then add the application logic necessary to initialize the board and respond to user interface events. Next, we’ll add multi-touch support that lets users use their fingers to drag the pieces of the puzzle on the board and rearrange them. As a last step, we’ll create an animation storyboard that creates an attractive visual effect when you succeed in solving the puzzle.
Creating the Puzzle User Interface
Look at the PuzzlePage.xaml file and you’ll see that the default Windows Phone Silverlight Page already includes several predefined objects, such as grids and textblocks. We're going to override the default template and write our own XAML describing the puzzle game. The code snippet in Figure 5 is a partial representation of that XAML. For the complete code, please review the frame source code.
In Figure 5, you can see the root XML element of this page, the XAML container object of the PhoneApplicationPage type, which itself is part of the Microsoft.Phone namespace. The different attributes of the root element includes additional namespace definition supporting the different controls shown on the page, the page’s supported orientation—in our case only portrait and some extra design parameters supporting design time.
The following list explains the callouts in Figure 5:
- Callout A: We'll use these three methods later when we talk about the supporting multi-touch. With a Windows Phone Silverlight application you have the option to handle global (to the page) touch events.
- Callout B: The page’s resources definition. This is where all the visual goodies are stored, such as the WinTransition Storyboard, which defines the animation happening when the games ends. We use additional styles for the buttons and text to fit the overall design. We’ll talk about styles and design when we cover Microsoft Expression Blend.
- Callout C: This defines the Grid’s row. The Grid is probably the best layout control that Silverlight has to offer, because it lets you define rows (as in our example), columns, and any combination of the two. It also automatically realigns when the context of controls in the grid changes. In our case, we define four rows and give each a name that we’ll use later from code behind.
- Callout D: This stack panel defines a container for three buttons that let a user save or load a game.
- Callout E: This grid defines a container for two Textbox objects showing help text and score of the game
- Callout F: This border control holds the main game canvas. The interesting aspect is the definition of render transformation. The RenderTransform is required by an animation storyboard that you'll create to provide a visual effect. The storyboard cannot animate the element unless the transformation is present.
- Callout G: This is the main game canvas control, which hosts the game pieces.
- Callout H: Inside the Border element is a single Canvas element. As noted, this is the main game canvas control, which is used to explicitly position other child elements using coordinates relative to its area.
Although this list provides a partial explanation of the entire PuzzlePage XAML, it's easy to see how well structured the page is and how Silverlight streamlined the creation of such pages. Figure 4 shows the end result.
Creating the Puzzle Logic
Before we can dive into the game logic, we need to talk about two more classes:
- PuzzleTile—This is a Silverlight user control that defines a single game piece in the puzzle. It's a straightforward, self-contained class that encapsulates data of a single puzzle piece (e.g., the game piece number, location, label).
- PuzzleGame—This class defines the logic of the game and provides methods that include initializing a new game, moving the puzzle pieces, saving and restoring the game’s state, and solving the game. We won't cover the game logic here, because it's beyond the scope of explaining the Windows Phone environment. But we encourage you to examine the source code for this class.
The puzzle game code behind, found at PuzzlePage.xaml.cs, is where we close the loop and connect all the dots between the UI defined in the XAML and the different game logic. The page’s constructor instantiates the game logic—encapsulated by the PuzzleGame class—and then binds its events. The PuzzleGame class defines the following events:
- GameStarted. This event is raised when a new game begins. The handler for this event shows the panel with the number of pieces moved, hides the legend with instructions on how to start the game, and then resets the number of moved pieces.
- GameOver: This event occurs when the puzzle is solved. The handler for the event shows the legend with instructions on how to start the game and then updates the move count. This also starts the wining animation defined earlier as the WinTransition storyboard.
- PieceUpdated. This event is triggered whenever a piece is moved. The handler for the event animates the moved piece and then updates the move count.
- After subscribing the event handlers, the constructor calls the InitBoard method to initialize the game board logic.
Adding Multi-Touch Support
Now let's add multi-touch support to our application to allow a user to interact with it. Generally speaking, multi-touch input lets users apply multiple finger gestures simultaneously and have them interpreted as a unit to provide complex commands to an application and simulate directly manipulating an element on the page (e.g., to pan and zoom at the same time). For our game, we’ll update the Windows Phone Puzzle game to receive multi-touch input and enable users to move the pieces of the puzzle on the board by tapping and then dragging them to an empty slot.
As shown in Figure 5, we defined three methods that handle multi- touch:
The ManipulationStarted event, similar to a MouseDown event, is raised when a user taps (or clicks with the mouse in the Windows Phone emulator) any UIElement to manipulate it. The handler for the event verifies if a game is currently in progress and that one of the image elements that represents the puzzle pieces raised the event; otherwise it ignores the event. It locates the corresponding Canvas element for this piece and then calls the game’s logic to determine whether it can be moved—for this to happen, an empty slot must be adjacent to the piece. It then stores the selected piece and records the axis/direction where it can move.
The ManipulationDelta event is raised when a user moves a finger (or the mouse cursor while pressing and holding the right button in the Windows Phone emulator) while manipulating a UIElement. The handler for this event checks if there is a piece currently being moved. If so, it captures the delta value from the only possible axis/direction. To do so, the code needs to enforce drag constraints to validate that the movement is within the available boundaries—a piece cannot overlap other pieces. The handler then updates the position for the piece by setting the property for the appropriate axis.
The ManipulationCompleted event, similar to a MouseUp event, is raised when a user lifts a finger from the screen (or releases the mouse button) after manipulating a UIElement. The handler for this event checks if there is a puzzle piece currently being moved. If so, it determines the time when the last ManipulationCompleted was fired and, provided the time interval is lower than the value specified by the DoubleTapSpeed, it interprets this event as a Double Tap event (or double-click) and moves the piece to the adjacent empty slot. Otherwise, it calculates the offset distance of the piece into its target position and, if the piece has shifted at least one-third of its size into the adjacent slot, it completes the move of the piece into that slot; if not, it pulls the piece back to its original position.
The code for these functions is rather long, so we don't show it here; but make sure you check the code yourself.
Adding Animation Effects
Silverlight offers a great animation system that can produce high quality visual effects. For example, in Silverlight a storyboard defines an animation. Each storyboard defines a timeline that contains key frames. Each key frame can independently redefine control properties, such as position, size, rotation, opacity, and even foreground or background color.
Using this approach, users are not required to create animations by defining every single frame; instead, they need only provide selected points on the timeline to mark significant property changes. Silverlight interpolates the value of the animated properties between two consecutive key frames to generate intervening frames and provide a smooth transition. Each storyboard is an object with methods and events that you can use from the page's code-behind. This includes methods to Begin, Stop, or Pause the animation—and a single event, Completed, which occurs when the animation has completed playing. You can define the storyboards as resources to a Silverlight page, as shown Figure 5.
You can write storyboards as XAML code and you can create them easily using Microsoft Expression Blend. When using Expression Blend, the tools generate the XAML, which you can review and modify if needed. Expression Blend lets designers and developers share the same code base while working together on a single project. Expression Blend lets you create visually rich graphics and animation. The important thing about Expression Blend is that it works with Visual Studio projects. You can have both Expression Blend and Visual Studio open for the same project and changes in each tool are automatically reflected in the other.
Opening the game solution with Expression Blend shows a view of the project similar to what you would see in Visual Studio, but with Expression Blend you can easily define animations and styles. After you open the PuzzlePage.xaml for editing, the bottom left corner of Expression Blend shows the different objects and timelines on the page. As you can see, the PhoneApplicationPage is the main root element from which all other children are defined in a tree. One of the children is the CongratsBorder, which has a storyboard as indicated by the red dot on the CongratsBorder element in the tree (Figure 6).
The dropdown menu lists the storyboards in this page. The WinTransition is the storyboard that plays when a user successfully solves the puzzle. Expression Blend lets you easily define a storyboard by simply recording the changes in the animation when you change properties, or by clicking and dragging an element on the screen. You can preview what happens when the puzzle is solved by using the play button in the timeline. Pressing play starts the animation; in this example, a congratulatory banner flies in from the top of the screen (Figure 7).
Start Developing Now
Although this article gives you just a small glimpse into the world of Windows Phone, we hope you found it intriguing enough to start developing an application. You can start right away. The tools are free and the setup is easy. You'll find considerable documentation in the AppHub (http://create.msdn.com/). As noted earlier, the AppHub is the place where you register to unlock your Windows Phone device to enable testing on a device, as well as to deploy your application to market place.