×
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
jaaura (Talk | contribs)
m (Jaaura -)
hamishwillee (Talk | contribs)
m (Text replace - "[[Category:Silverlight" to "[[Category:XAML")
Line 1: Line 1:
[[Category:Windows Phone]][[Category:Games]][[Category:Silverlight]][[Category:Windows Phone 7.5]][[Category:Windows Phone 8]]
+
[[Category:Windows Phone]][[Category:Games]][[Category:XAML]][[Category:Windows Phone 7.5]][[Category:Windows Phone 8]]
 
{{Abstract|This article describes how to create a simple game using Visual C# and XAML in Windows Phone.}}  
 
{{Abstract|This article describes how to create a simple game using Visual C# and XAML in Windows Phone.}}  
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->

Revision as of 04:29, 10 April 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: hamishwillee (10 Apr 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.

344 page views in the last 30 days.
×