×
Namespaces

Variants
Actions
(Difference between revisions)

Creating a simple colour matching game in silverlight for Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
kunal_the_one (Talk | contribs)
(Kunal the one -)
jaaura (Talk | contribs)
m (Jaaura -)
(21 intermediate revisions by 5 users not shown)
Line 1: Line 1:
[[Category:Code Examples]][[Category:Code Snippet]][[Category:Windows Phone]][[Category:Porting]]
+
[[Category:Windows Phone]][[Category:Games]][[Category:Silverlight]][[Category:Windows Phone 7.5]][[Category:Windows Phone 8]]
{{Abstract| This article describes how a simple game can be created using Windows Phone 8 SDK using Visual C#}}
+
{{Abstract|This article describes how to create a simple game using Visual C# and XAML in Windows Phone.}}  
 
+
{{Note|This is a community entry in the [[Windows Phone 8 Wiki Competition 2012Q4]].}}  
+
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
|sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] -->
+
|sourcecode= [[Media:PhoneApp1.zip]]
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|devices= <!-- Devices tested against - e.g. ''devices=Nokia 6131 NFC, Nokia C7-00'') -->
 
|devices= <!-- Devices tested against - e.g. ''devices=Nokia 6131 NFC, Nokia C7-00'') -->
|sdk= <!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Qt SDK 1.1.4]) -->
+
|sdk= Windows Phone SDK 8.0
|platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later -->
+
|platform= Windows Phone
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only -->  
+
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
|creationdate= <!-- Format YYYYMMDD -->
+
|creationdate= 20121111
|author= <!-- Display as link [[User:username]] -->
+
|author= [[User:Kunal the one]]
 
}}
 
}}
  
 
== Introduction ==
 
== Introduction ==
  
In this article I will share how I achieved things in WP8 as I created my first WP8 game Color Match.
+
This article describes how I created my first simple Windows Phone game: "Colour match". The article covers:
I will share some basic things required to create simple game using Windows Phone 8 SDK.  
+
* How to create simple menu  
Game play is simple, you will be displayed a text and a color box and you need to tell if color name in text and color in color box matches or not.
+
* How to use Geometry component in XAML
 +
* How to use image
 +
* How to create animation
 +
* Navigation within different game screen
 +
* How to use {{Icode|IsolatedStorage}} to persist game information
  
This is how my final game looks like.
+
 
<gallery caption="Game screen shots">
+
The game play is simple: The user is shown a text and a color box and you need to tell if color name in text and color in color box matches or not. Below are my final screenshots:
 +
<gallery caption="Game screen shots" widths="340px" heights="620px">
 
File:Colorgame.png|Game menu
 
File:Colorgame.png|Game menu
 
File:Game_play.png|Game screen
 
File:Game_play.png|Game screen
File:Game_play_correct_ans.png|Game screen
+
File:game_play_correct_ans.png|Game screen
 
File:Game_over.png|Score screen
 
File:Game_over.png|Score screen
 
</gallery>
 
</gallery>
 
== Summary ==
 
 
In this article I will cover,
 
* How to create simple menu 
 
* How to use Geometry component in xaml
 
* How to use image
 
* How to create animation
 
* Navigation within different game screen
 
* How to use Isolated store to persist game information
 
  
 
== How to create simple menu and navigation within different game screen ==
 
== How to create simple menu and navigation within different game screen ==
When you create WP8 application, it will create MainPage for you. This is the page that will shows up when user launches application. For my game I used main page as my game menu.
+
When you create WP8 application using the Visual Studio templates, it will create MainPage for you. This is the page that will shows up when user launches application. For my game I used main page as my game menu.
  
First thing I wanted is to make my game full screen,, I did not removed Status Bar it was fine for my case, so I just removed StackPanel element named "TitlePanel in MainPage.xaml that contains Application name and page title .  
+
First thing I wanted in my game app is to have Full Screen feature. To do so, I did not removed Status Bar it was fine for my case, so I just removed {{Icode|StackPanel}} element named ''TitlePanel'' in '''MainPage.xaml''' that contains the Application name and page title. This will remove the application title and page name from page.
This will remove the application title and page name from page.
+
  
If you want to hide Status Bar then you can set shell:SystemTray.IsVisible to false in Xaml page.
+
If you want to hide Status Bar then you can set {{Icode|shell:SystemTray.IsVisible}} to {{Icode|false}} in the XMAL page.
<code>
+
<code xml>
 
<phone:PhoneApplicationPage
 
<phone:PhoneApplicationPage
 
     x:Class="PhoneApp1.ScorePage"    ....
 
     x:Class="PhoneApp1.ScorePage"    ....
Line 63: Line 55:
 
</code>
 
</code>
  
After the main page is as per my requirement, I wanted to add Game Title page and buttons in my menu screen. To get feel of xaml element I decided to create game title using xaml only, rather than using image.
+
After the main page is as per my requirement, I wanted to add Game Title page and buttons in my menu screen. To get feel of XAML element I decided to create game title using XAML only, rather than using image.
I wanted to draw Two rectangle one above another and wanted to draw text over each rectangle.  
+
 
 +
I wanted to draw Two rectangles one above another and wanted to draw text over each rectangle.
 +
 
 +
To make text label one above other I used {{Icode|StackPanel}}, which acts like Row,Column element in QML. Then added to grid layout that contain text element.
  
To make text label one above other I used StackPanel, which act like Row,Column element in QML. Then added to grid layout that contain text element.
 
 
Following code achieve the same.
 
Following code achieve the same.
<code>
+
<code xml>
 
             <StackPanel Orientation="Vertical"  
 
             <StackPanel Orientation="Vertical"  
 
                         VerticalAlignment="Center"
 
                         VerticalAlignment="Center"
Line 92: Line 86:
 
</code>
 
</code>
  
And to complete my menu I needed Buttons, I added buttons in xaml and propert place and added event handler. To add event handler add event handler name in click property and add same method in c# code. In following code onStartGame is my event handler.
+
And to complete my menu I needed Buttons. I added buttons in XAML and and added event handler. To add event handler add event handler name in click property and add same method in C# code. In following code {{Icode|onStartGame()}} is my event handler.
  
<code>
+
<code xml>
 
<Button Content="Start Game"  
 
<Button Content="Start Game"  
 
                         Foreground="Black"
 
                         Foreground="Black"
Line 103: Line 97:
 
</code>
 
</code>
 
Following is C# code for onStartGame event handler. In this method I am using Navigation service to launch my GamePage that contains game logic.
 
Following is C# code for onStartGame event handler. In this method I am using Navigation service to launch my GamePage that contains game logic.
<code>
+
<code csharp>
 
         private void onStartGame(object sender, RoutedEventArgs e)
 
         private void onStartGame(object sender, RoutedEventArgs e)
 
         {
 
         {
Line 110: Line 104:
 
</code>
 
</code>
  
You can add Name to this element and refer them in c# code using same name. Like following.
+
You can add Name to this element and refer them in C# code using same name. Like following:
<code>
+
<code xml>
 
<TextBlock Name="colorName"  
 
<TextBlock Name="colorName"  
 
                         Text="Green"
 
                         Text="Green"
Line 122: Line 116:
  
 
</code>
 
</code>
 +
 
== How to use Geometry component in xaml ==
 
== How to use Geometry component in xaml ==
  
My GamePage layout is almost similar to MainPage. There is game score lable at top, two buttons at bottom. But in middle this time I used Path element to add Rectangle geometry in xaml.
+
My {{Icode|GamePage}} layout is almost similar to MainPage. There is game score label at top, two buttons at bottom. But in middle this time I used Path element to add Rectangle geometry in XAML.
 +
 
 
Following code shows, how rectangle geometry can be added and how to layout text and rectangle one over another using grid layout.  
 
Following code shows, how rectangle geometry can be added and how to layout text and rectangle one over another using grid layout.  
  
<code>
+
<code xml>
                <Grid>
+
<Grid>
                    <Path Name="textBlock" Stroke="Black"
+
  <Path Name="textBlock" Stroke="Black" Fill="Gray">
                          Fill="Gray">
+
    <Path.Data>
                        <Path.Data>
+
      <RectangleGeometry Rect="0 0 450 150"></RectangleGeometry>
                            <RectangleGeometry Rect="0 0 450 150"></RectangleGeometry>
+
    </Path.Data>
                        </Path.Data>
+
  </Path>
                    </Path>
+
  <TextBlock Name="colorName"  
                    <TextBlock Name="colorName"  
+
 
                         Text="Green"
 
                         Text="Green"
 
                         HorizontalAlignment="Center"
 
                         HorizontalAlignment="Center"
 
                         VerticalAlignment="Center"
 
                         VerticalAlignment="Center"
 
                         Style="{StaticResource PhoneTextTitle1Style}" >                         
 
                         Style="{StaticResource PhoneTextTitle1Style}" >                         
                    </TextBlock>
+
  </TextBlock>
                </Grid>
+
</Grid>
 
</code>
 
</code>
  
There are also EllipseGeometry, LineGeometry, PathGeometry and other for drawing different geometry. Following code show hot to draw circle.
+
There are also EllipseGeometry, LineGeometry, PathGeometry and other for drawing different geometry. Following code show how to draw circle.
<code>
+
<code xml>
 
<Grid Background="LightCyan">  
 
<Grid Background="LightCyan">  
 
     <Path Stroke="Maroon" StrokeThickness="8" Fill="Green">  
 
     <Path Stroke="Maroon" StrokeThickness="8" Fill="Green">  
Line 156: Line 151:
  
 
== How to use image ==
 
== How to use image ==
By now my game screen is ready. But I wanted to show image to show if user answer was correct or wrong.
+
By now my game screen is ready. But I wanted to display specific image regardless of the correctness of the answer given by user.
  
 
You can use image element in xaml to display image. Following code shows how to display image using xaml.
 
You can use image element in xaml to display image. Following code shows how to display image using xaml.
<code>
+
<code xml>
            <Image Name="answerImage"
+
<Image Name="answerImage"
                  Source="assets\wrong.png"
+
    Source="assets\wrong.png"
                  HorizontalAlignment="Center"
+
    HorizontalAlignment="Center"
                  VerticalAlignment="Center"
+
    VerticalAlignment="Center"
                  Opacity="0">   
+
    Opacity="0">   
            </Image>
+
</Image>
 
</code>
 
</code>
  
I need to change the image dynamically, according to user's answer. Changing image source dynamically using code is little mode involving then xaml.  
+
I was required to change the image dynamically, according to user's answer. Changing image source dynamically using code is little more involving than XAML.  
I could have used to Image element in xaml and show, hide then according to user's answer. But I wanted to do it manually to show how that can be achieved.
+
I could have used to Image element in XAML and show, hide then according to user's answer. But I wanted to do it manually to show how that can be achieved.
  
Following code shows how to change image's source using c#. Code will show correct or wrong image based on user's answer.
+
Following code shows how to change image's source using C#. Code will show correct or wrong image based on user's answer.
<code>
+
<code csharp>
 
             Uri uri = null;
 
             Uri uri = null;
 
             if (isCorrectAnswer)
 
             if (isCorrectAnswer)
Line 192: Line 187:
 
Now that I am showing images for correct and wrong answer, I wanted to show some animation when image is displayed to user. I decided to add opacity animation to image to fade in over the time.
 
Now that I am showing images for correct and wrong answer, I wanted to show some animation when image is displayed to user. I decided to add opacity animation to image to fade in over the time.
  
Windows phone provide Storyboard class for this purpose, just like QAnimation class in Qt SDK. I used DoubleAnimation to animate opacity property of image over the time. I think this class is similar to QPropertAnimation.
+
Windows phone provide Storyboard class for this purpose, I used {{Icode|DoubleAnimation}} to animate opacity property of image over the time.
  
To add opacity animation, I added Storyboard element in PhoneApplicationPage.Resources, by using following code. Here I am changing opacity of answerImage to 1 from 0, over period of 0.5 second and I want this animation to happen only once.
+
To add opacity animation, I added Storyboard element in {{Icode|PhoneApplicationPage.Resources}}, by using following code. Here I am changing opacity of {{Icode|answerImage}} to 1 from 0, over period of 0.5 second and I wanted this animation to happen only once.
If you want to perform this animation 2 or 3 times you can change 1x to 2x or 3x, or you can change it to ForEver to loop animation continuously.
+
 
<code>
+
If you want to perform this animation 2 or 3 times you can change 1x to 2x or 3x, or you can change it to {{Icode|Forever}} to loop animation continuously.
 +
<code xml>
 
     <phone:PhoneApplicationPage.Resources>
 
     <phone:PhoneApplicationPage.Resources>
 
         <Storyboard x:Name="opacityStoryBoard">
 
         <Storyboard x:Name="opacityStoryBoard">
Line 208: Line 204:
 
</code>
 
</code>
  
I also wanted to get notified when animation is complete, for that I added Completed event handler in DoubleAnimation and named it to onAnimationComplete.
+
I also wanted to get notified when animation is complete, for that I added Completed event handler in {{Icode|DoubleAnimation}} and named it to {{Icode|onAnimationComplete()}}.
Following is code for onAnimationComplete in C#. In code I am hiding the image and drawing new puzzle.
+
Following is code for {{Icode|onAnimationComplete()}} in C#. In code I am hiding the image and drawing new puzzle.
<code>
+
<code csharp>
        private void onAnimationComplete(object sender, EventArgs e)
+
private void onAnimationComplete(object sender, EventArgs e)
        {
+
{
            answerImage.Opacity = 0;
+
    answerImage.Opacity = 0;
            newPuzzle();
+
    newPuzzle();
        }
+
}
 
</code>
 
</code>
  
Now animation is code is complete, however you need to enable it to make animation happen. You need to use Storybord's Begin method to start animation.
+
Now animation's code is complete, however you need to enable it to make animation happen. You need to use Storybord's Begin method to start animation.
<code>
+
<code csharp>
opacityStoryBoard.Begin();
+
opacityStoryBoard.Begin();
 
</code>
 
</code>
  
 
== Navigation within different game screen ==
 
== Navigation within different game screen ==
I already showed how to navigate to another page using NavigationService. But what if you need to pass some data to new page. There are several ways to do so, I am using the easiest of them.
+
I already showed how to navigate to another page using {{Icode|NavigationService}}. But what if you need to pass some data to new page. There are several ways to do so, I am using the easiest of them.
  
When we lauch new page, we provide Uri to NavigationService, we can add query string to this Uri that will be passed to newly launched page and the lauched page can retrieve this query string and process it.
+
When we launch new page, we provide Uri to {{Icode|NavigationService}}, we can add query string to this Uri that will be passed to newly launched page and the launched page can retrieve this query string and process it.
  
 
Following code shows the same. This code is used to launch game over screen (ScorePage) when game is over. I am passing score using query string.
 
Following code shows the same. This code is used to launch game over screen (ScorePage) when game is over. I am passing score using query string.
<code>
+
<code csharp>
                String destination = String.Format("/ScorePage.xaml?score={0}", score);
+
    String destination = String.Format("/ScorePage.xaml?score={0}", score);
                this.NavigationService.Navigate(new Uri(destination, UriKind.Relative));
+
    this.NavigationService.Navigate(new Uri(destination, UriKind.Relative));
 
</code>
 
</code>
  
 
Now on second page, we need to add onNavigateTo handler, that is called whenever page is launched. Following is my implementation.
 
Now on second page, we need to add onNavigateTo handler, that is called whenever page is launched. Following is my implementation.
<code>
+
<code csharp>
        protected override void OnNavigatedTo(NavigationEventArgs e)
+
protected override void OnNavigatedTo(NavigationEventArgs e)
        {
+
{
 
             IDictionary<string, string> parameters = this.NavigationContext.QueryString;         
 
             IDictionary<string, string> parameters = this.NavigationContext.QueryString;         
 
             String scoreStr = parameters["score"];
 
             String scoreStr = parameters["score"];
Line 251: Line 247:
 
               ...
 
               ...
 
             }
 
             }
        }
+
}
 
</code>
 
</code>
  
 
To close this page on Button press event, you can use GoBack method of navigation service.
 
To close this page on Button press event, you can use GoBack method of navigation service.
<code>
+
<code csharp>
        private void onGoToMenu(object sender, RoutedEventArgs e)
+
private void onGoToMenu(object sender, RoutedEventArgs e)
        {
+
{
            this.NavigationService.GoBack();
+
    this.NavigationService.GoBack();
        }
+
}
 
</code>
 
</code>
  
However, for my game above code will display GamePage as GamePage lauched the ScorePage, not MainPage which I wanted to display when user press "Go to menu" button on ScorePage.
+
However, for my game above code will display {{Icode|GamePage}} as {{Icode|GamePage}} launched the {{Icode|ScorePage}}, not {{Icode|MainPage}} which I wanted to display when user press "Go to menu" button on ScorePage.
I don't know how to solve it, but I used following logic. On GamePage I added OnNavigatedTo handler and checking if game is over or not. If game is over then I call GoBack once more to go to MainPage.
+
 
<code>
+
I don't know how to solve it, but I used following logic. On {{Icode|GamePage}} I added {{Icode|OnNavigatedTo()}} handler and checking if game is over or not. If game is over then I call {{Icode|GoBack}} once more to go to {{Icode|MainPage}}.
        protected override void OnNavigatedTo(NavigationEventArgs e)
+
<code csharp>
        {
+
protected override void OnNavigatedTo(NavigationEventArgs e)
 +
{
 
           //check if game over
 
           //check if game over
 
             if (puzzleNumber == 20)
 
             if (puzzleNumber == 20)
Line 272: Line 269:
 
                 this.NavigationService.GoBack();
 
                 this.NavigationService.GoBack();
 
             }
 
             }
        }
+
}
 
</code>
 
</code>
  
 
== How to use Isolated store to persist game information ==
 
== How to use Isolated store to persist game information ==
Now my game is almost complete, but I wanted to save highscore to file. We can use IsolatedStorageSettings class to store the game setting and other information persistently. Its quite similar to QSettings.
+
Now my game is almost complete, but I wanted to save high score to file. We can use {{Icode|IsolatedStorageSettings}} class to store the game setting and other information persistently.  
  
Following code shows how to save information to IsolatedStorageSettings.
+
Following code shows how to save information to {{Icode|IsolatedStorageSettings}}.
<code>
+
<code csharp>
        private void savaHighScore(int score)
+
private void savaHighScore(int score)
        {
+
{
 
             IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
 
             IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
 
             settings["highScore"] = score;
 
             settings["highScore"] = score;
 
             settings.Save();
 
             settings.Save();
        }
+
}
 
</code>
 
</code>
  
 
Following code shows how to get information back from IsolatedStorageSettings.
 
Following code shows how to get information back from IsolatedStorageSettings.
<code>
+
<code csharp>
        private int getHighScore()
+
private int getHighScore()
        {
+
{
 
             IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
 
             IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
 
             int score;
 
             int score;
Line 299: Line 296:
 
             }
 
             }
 
             return 0;
 
             return 0;
        }
+
}
 
</code>
 
</code>
  
Line 305: Line 302:
  
 
To generate random numbers, you can use Random class to generate random numbers. Following code shows basic usage.
 
To generate random numbers, you can use Random class to generate random numbers. Following code shows basic usage.
<code>
+
<code csharp>
 
Random random = new Random();
 
Random random = new Random();
 
int random= random.Next(100);
 
int random= random.Next(100);
Line 311: Line 308:
  
 
To format the string, you can use following code.
 
To format the string, you can use following code.
<code>
+
<code csharp>
 
firstLine.Text = String.Format("Your score : {0}", score);
 
firstLine.Text = String.Format("Your score : {0}", score);
 
</code>
 
</code>
  
 
To convert string to integer.
 
To convert string to integer.
<code>
+
<code csharp>
  String scoreStr = parameters["score"];
+
String scoreStr = parameters["score"];
  int score = Convert.ToInt32(scoreStr);
+
int score = Convert.ToInt32(scoreStr);
 
</code>
 
</code>
  
 
To messaure time take for certain activity.
 
To messaure time take for certain activity.
<code>
+
<code csharp>
 
DateTime startTime = DateTime.Now;
 
DateTime startTime = DateTime.Now;
 
TimeSpan elapsedTime = DateTime.Now - startTime ;
 
TimeSpan elapsedTime = DateTime.Now - startTime ;
Line 329: Line 326:
  
 
== Final notes ==
 
== Final notes ==
So this is all, This is my first windows application and just stated to learn WP8 development. I hope this will help others like me to start working on WP8.  
+
So this is all, This is my first windows phone application and just started to learn Windows Phone development. I hope this will help others like me to start working on Windows Phone.  
 
+
[[File:PhoneApp1.zip| Here ]] is source code for this application.
Media:[PhoneApp1.zip] Here is source code for this application.
+
 
+
{{VersionHint|Versions will be visible from this template when viewed in preview. You can delete this or leave it in the page as it is not displayed in final version}}
+

Revision as of 16:53, 9 January 2013

This article describes how to create a simple game using Visual C# and XAML in Windows Phone.

WP Metro Icon Joystick.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code Example
Source file: Media:PhoneApp1.zip
Tested with
SDK: Windows Phone SDK 8.0
Compatibility
Platform(s): Windows Phone
Windows Phone 8
Windows Phone 7.5
Article
Created: kunal_the_one (11 Nov 2012)
Last edited: jaaura (09 Jan 2013)

Contents

Introduction

This article describes how I created my first simple Windows Phone game: "Colour match". The article covers:

  • How to create simple menu
  • How to use Geometry component in XAML
  • How to use image
  • How to create animation
  • Navigation within different game screen
  • How to use IsolatedStorage to persist game information


The game play is simple: The user is shown a text and a color box and you need to tell if color name in text and color in color box matches or not. Below are my final screenshots:

How to create simple menu and navigation within different game screen

When you create WP8 application using the Visual Studio templates, it will create MainPage for you. This is the page that will shows up when user launches application. For my game I used main page as my game menu.

First thing I wanted in my game app is to have Full Screen feature. To do so, I did not removed Status Bar it was fine for my case, so I just removed StackPanel element named TitlePanel in MainPage.xaml that contains the Application name and page title. This will remove the application title and page name from page.

If you want to hide Status Bar then you can set shell:SystemTray.IsVisible to false in the XMAL page.

<phone:PhoneApplicationPage
x:Class="PhoneApp1.ScorePage" ....
shell:SystemTray.IsVisible="True"> <- change this to show/hide Status Bar

After the main page is as per my requirement, I wanted to add Game Title page and buttons in my menu screen. To get feel of XAML element I decided to create game title using XAML only, rather than using image.

I wanted to draw Two rectangles one above another and wanted to draw text over each rectangle.

To make text label one above other I used StackPanel, which acts like Row,Column element in QML. Then added to grid layout that contain text element.

Following code achieve the same.

            <StackPanel Orientation="Vertical" 
VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="71,202,61,302" Width="324">
<Grid Background="#FF9165B9" Height="120">
<TextBlock Text="Color"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Foreground="#FF086C6C"
Style="{StaticResource PhoneTextTitle1Style}">
</TextBlock>
</Grid>
<Grid Background="#FF631919" Height="120">
<TextBlock Text="Match"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Foreground="#FFEEB5A4"
Style="{StaticResource PhoneTextTitle1Style}">
</TextBlock>
</Grid>
</StackPanel>

And to complete my menu I needed Buttons. I added buttons in XAML and and added event handler. To add event handler add event handler name in click property and add same method in C# code. In following code onStartGame() is my event handler.

<Button Content="Start Game" 
Foreground="Black"
BorderBrush="Black"
Height="100"
Width="200"
Click="onStartGame"></Button>

Following is C# code for onStartGame event handler. In this method I am using Navigation service to launch my GamePage that contains game logic.

        private void onStartGame(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri("/GamePage.xaml", UriKind.Relative));
}

You can add Name to this element and refer them in C# code using same name. Like following:

<TextBlock Name="colorName" 
Text="Green"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Style="{StaticResource PhoneTextTitle1Style}" >
</TextBlock>
 
colorName.Text = "test";

How to use Geometry component in xaml

My GamePage layout is almost similar to MainPage. There is game score label at top, two buttons at bottom. But in middle this time I used Path element to add Rectangle geometry in XAML.

Following code shows, how rectangle geometry can be added and how to layout text and rectangle one over another using grid layout.

<Grid>
<Path Name="textBlock" Stroke="Black" Fill="Gray">
<Path.Data>
<RectangleGeometry Rect="0 0 450 150"></RectangleGeometry>
</Path.Data>
</Path>
<TextBlock Name="colorName"
Text="Green"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Style="{StaticResource PhoneTextTitle1Style}" >
</TextBlock>
</Grid>

There are also EllipseGeometry, LineGeometry, PathGeometry and other for drawing different geometry. Following code show how to draw circle.

<Grid Background="LightCyan"> 
<Path Stroke="Maroon" StrokeThickness="8" Fill="Green">
<Path.Data>
<EllipseGeometry Center="250 150" RadiusX="150" RadiusY="100" />
</Path.Data>
</Path>
</Grid>

How to use image

By now my game screen is ready. But I wanted to display specific image regardless of the correctness of the answer given by user.

You can use image element in xaml to display image. Following code shows how to display image using xaml.

<Image Name="answerImage"
Source="assets\wrong.png"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Opacity="0">
</Image>

I was required to change the image dynamically, according to user's answer. Changing image source dynamically using code is little more involving than XAML. I could have used to Image element in XAML and show, hide then according to user's answer. But I wanted to do it manually to show how that can be achieved.

Following code shows how to change image's source using C#. Code will show correct or wrong image based on user's answer.

            Uri uri = null;
if (isCorrectAnswer)
{
uri = new Uri("Assets/correct.png", UriKind.Relative);
}
else
{
uri = new Uri("Assets/wrong.png", UriKind.Relative);
}
 
StreamResourceInfo resourceInfo = Application.GetResourceStream(uri);
BitmapImage bmp = new BitmapImage();
bmp.SetSource(resourceInfo.Stream);
answerImage.Source = bmp;

How to create animation

Now that I am showing images for correct and wrong answer, I wanted to show some animation when image is displayed to user. I decided to add opacity animation to image to fade in over the time.

Windows phone provide Storyboard class for this purpose, I used DoubleAnimation to animate opacity property of image over the time.

To add opacity animation, I added Storyboard element in PhoneApplicationPage.Resources, by using following code. Here I am changing opacity of answerImage to 1 from 0, over period of 0.5 second and I wanted this animation to happen only once.

If you want to perform this animation 2 or 3 times you can change 1x to 2x or 3x, or you can change it to Forever to loop animation continuously.

    <phone:PhoneApplicationPage.Resources>
<Storyboard x:Name="opacityStoryBoard">
<DoubleAnimation Storyboard.TargetName="answerImage"
Storyboard.TargetProperty="Opacity"
From="0" To="1" Duration="0:0:0.5"
RepeatBehavior="1x"
Completed="onAnimationComplete" />
</Storyboard>
</phone:PhoneApplicationPage.Resources>

I also wanted to get notified when animation is complete, for that I added Completed event handler in DoubleAnimation and named it to onAnimationComplete(). Following is code for onAnimationComplete() in C#. In code I am hiding the image and drawing new puzzle.

private void onAnimationComplete(object sender, EventArgs e)
{
answerImage.Opacity = 0;
newPuzzle();
}

Now animation's code is complete, however you need to enable it to make animation happen. You need to use Storybord's Begin method to start animation.

opacityStoryBoard.Begin();

Navigation within different game screen

I already showed how to navigate to another page using NavigationService. But what if you need to pass some data to new page. There are several ways to do so, I am using the easiest of them.

When we launch new page, we provide Uri to NavigationService, we can add query string to this Uri that will be passed to newly launched page and the launched page can retrieve this query string and process it.

Following code shows the same. This code is used to launch game over screen (ScorePage) when game is over. I am passing score using query string.

    String destination = String.Format("/ScorePage.xaml?score={0}", score);
this.NavigationService.Navigate(new Uri(destination, UriKind.Relative));

Now on second page, we need to add onNavigateTo handler, that is called whenever page is launched. Following is my implementation.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
IDictionary<string, string> parameters = this.NavigationContext.QueryString;
String scoreStr = parameters["score"];
int highScore = getHighScore();
int score = Convert.ToInt32(scoreStr);
if (score > highScore)
{
...
savaHighScore(score);
}
else
{
...
}
}

To close this page on Button press event, you can use GoBack method of navigation service.

private void onGoToMenu(object sender, RoutedEventArgs e)
{
this.NavigationService.GoBack();
}

However, for my game above code will display GamePage as GamePage launched the ScorePage, not MainPage which I wanted to display when user press "Go to menu" button on ScorePage.

I don't know how to solve it, but I used following logic. On GamePage I added OnNavigatedTo() handler and checking if game is over or not. If game is over then I call GoBack once more to go to MainPage.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
//check if game over
if (puzzleNumber == 20)
{
this.NavigationService.GoBack();
}
}

How to use Isolated store to persist game information

Now my game is almost complete, but I wanted to save high score to file. We can use IsolatedStorageSettings class to store the game setting and other information persistently.

Following code shows how to save information to IsolatedStorageSettings.

private void savaHighScore(int score)
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings["highScore"] = score;
settings.Save();
}

Following code shows how to get information back from IsolatedStorageSettings.

private int getHighScore()
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
int score;
if (settings.TryGetValue<int>("highScore", out score))
{
return score;
}
return 0;
}

Some general utility functions

To generate random numbers, you can use Random class to generate random numbers. Following code shows basic usage.

Random random = new Random();
int random= random.Next(100);

To format the string, you can use following code.

firstLine.Text = String.Format("Your score : {0}", score);

To convert string to integer.

String scoreStr = parameters["score"];
int score = Convert.ToInt32(scoreStr);

To messaure time take for certain activity.

DateTime startTime = DateTime.Now;
TimeSpan elapsedTime = DateTime.Now - startTime ;
double miliSecs = elapsedTime.TotalMilliseconds;

Final notes

So this is all, This is my first windows phone application and just started to learn Windows Phone development. I hope this will help others like me to start working on Windows Phone. File:PhoneApp1.zip is source code for this application.

212 page views in the last 30 days.
×