×
Namespaces

Variants
Actions
Revision as of 10:04, 11 November 2012 by chintandave_er (Talk | contribs)

Creating a simple colour matching game in silverlight for Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article describes how a simple game can be created using Windows Phone 8 SDK using Visual C#

Note.pngNote: This is a community entry in the Windows Phone 8 Wiki Competition 2012Q4.

WP Metro Icon Joystick.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Compatibility
Platform(s): Windows Phone 8
Windows Phone 8
Windows Phone 7.5
Article
Created: kunal_the_one (11 Nov 2012)
Last edited: chintandave_er (11 Nov 2012)

Contents

Introduction

In this article I will share how I achieved things in WP8 as I created my first WP8 game Color Match. I will share some basic things required to create simple game using Windows Phone 8 SDK. 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.

This is how my final game looks like.

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

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.

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 . 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.

<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 rectangle one above another and wanted to draw text over each rectangle.

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.

            <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 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.

<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 lable 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 hot 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 show image to show if user answer was correct or wrong.

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 need to change the image dynamically, according to user's answer. Changing image source dynamically using code is little mode involving then 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, 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.

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. 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 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.

 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 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.

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 lauched 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 highscore to file. We can use IsolatedStorageSettings class to store the game setting and other information persistently. Its quite similar to QSettings.

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 application and just stated to learn WP8 development. I hope this will help others like me to start working on WP8.

Here is source code for this application.

Version Hint

Windows Phone: [[Category:Windows Phone]]
[[Category:Windows Phone 7.5]]
[[Category:Windows Phone 8]]

Nokia Asha: [[Category:Nokia Asha]]
[[Category:Nokia Asha Platform 1.0]]

Series 40: [[Category:Series 40]]
[[Category:Series 40 1st Edition]] [[Category:Series 40 2nd Edition]]
[[Category:Series 40 3rd Edition (initial release)]] [[Category:Series 40 3rd Edition FP1]] [[Category:Series 40 3rd Edition FP2]]
[[Category:Series 40 5th Edition (initial release)]] [[Category:Series 40 5th Edition FP1]]
[[Category:Series 40 6th Edition (initial release)]] [[Category:Series 40 6th Edition FP1]] [[Category:Series 40 Developer Platform 1.0]] [[Category:Series 40 Developer Platform 1.1]] [[Category:Series 40 Developer Platform 2.0]]

Symbian: [[Category:Symbian]]
[[Category:S60 1st Edition]] [[Category:S60 2nd Edition (initial release)]] [[Category:S60 2nd Edition FP1]] [[Category:S60 2nd Edition FP2]] [[Category:S60 2nd Edition FP3]]
[[Category:S60 3rd Edition (initial release)]] [[Category:S60 3rd Edition FP1]] [[Category:S60 3rd Edition FP2]]
[[Category:S60 5th Edition]]
[[Category:Symbian^3]] [[Category:Symbian Anna]] [[Category:Nokia Belle]]

284 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×