Flash To Silverlight : Guess The Number Game: Part 2 – Silverlight

Flash To Silverlight : Guess The Number Game: Part 2 – Silverlight

For my first foray into Flash->Silverlight Game development, I will create a very simple “Guess The Number” game in Flash and then discuss how to do nearly the exact same thing with Silverlight. 

In Part 2 we cover the Silverlight version of the game.

(Read Part 1)

SilverLight Source

So, now we get to the real subject of this tutorial. How do you do create the exact same application above in Silverlight? Well, we start with the page design.

Page Design

Instead of using a fancy GUI app to create the user interface for the Silverlight version of “Guess The Number”, we will use the Visual Studio 2008 XAML editor. Of course, you could use Microsoft Expression Blend 2.0 to design this screen, but it is not necessary for this project as everything we need to do can be accomplished with one tool.

To start, launch Visual Studio 2008, select to create a new Silverlight Project in C#, and wait for the project to be created. When everything is done, you should see the following files listed in the solution explorer:

  • app.xaml
    • app.xaml.cs
  • page.xaml
    • page.xaml.cs

Click on page.xaml, and the Visual Studio XAML editor will open.

Now, we will design a page in XAML that looks remarkably similar to the Flash MovieClip we created.

 

XAML : Page.xaml

XAML is an XML like representation for the page. Here is the XAML necessary to replicate the design of our Flash MovieClip.:

<UserControl x:Class=”SilverlightHelloWorld.Page”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&rdquo;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&rdquo;
Width=”500″ Height=”400″>
<Canvas x:Name=”LayoutRoot” Background=”White”>
<TextBlock x:Name=”t_messageText” Text=”Message” Width=”500″ Canvas.Left=”0″ TextAlignment=”Center” Canvas.Top=”10″></TextBlock>
<TextBlock x:Name=”t_instructionText” Text=”Instructions” Width=”500″ Canvas.Left=”0″ TextAlignment=”Center” Canvas.Top=”30″></TextBlock>
<TextBlock x:Name=”t_guessText” Text=”Guesses” Width=”500″ Canvas.Left=”0″ TextAlignment=”Center” Canvas.Top=”50″></TextBlock>
<TextBox x:Name=”t_userGuess” Text=”” Width=”200″ Canvas.Left=”150″ TextAlignment=”Center” Canvas.Top=”130″></TextBox>
<Button x:Name=”b_SubmitGuess” Content=”Submit Guess” Width=”150″ Height=”50″ Click=”EventClickSubmitGuess” Canvas.Left=”175″ Canvas.Top=”240″ ></Button>
<Button x:Name=”b_PlayAgain” Content=”Start Over” Width=”150″ Height=”50″ Click=”EventClickStartOver” Canvas.Left=”175″ Canvas.Top=”300″ ></Button> </Canvas>
</UserControl>

By the way, you do not have to type all of this code. You can drag the 4 TextBlocks and 2 Buttons from the “Silverlight XAML Controls” box on the left side of the screen, into the XAML code editor. Unfortunately, you cannot drag them into the XAML display window. However, after you have dragged them in, you need to code the rest by hand or by using the properties window in Visual Studio 2008.

XAML Source Breakdown

<UserControl x:Class=”SilverlightHelloWorld.Page”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&rdquo;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&rdquo;
Width=”500″ Height=”400″>

  • Most of the above XAML was created by default. However, I updated the Width and Height to match our Flash Movie.

<Canvas x:Name=”LayoutRoot” Background=”White”>

  • This line defines the type of XAML page we are creating. For this application we will use a “Canvas”. This will allow us to position our object using “x,y” style coordinates.

<TextBlock x:Name=”t_messageText” Text=”Message” Width=”500″ Canvas.Left=”0″ TextAlignment=”Center” Canvas.Top=”10″></TextBlock>

  • The four TextBlock lines are the equivalents for the four text fields we created in Flash.
  • x:Name=”t_messageText” : This is object name we will reference in our C# code.
  • Canvas.Top=”10″ : This is the way to set the “y” position of the object. It means “from the top”.

<Button x:Name=”b_SubmitGuess” Content=”Submit Guess” Width=”150″ Height=”50″ Click=”EventClickSubmitGuess” Canvas.Left=”175″ Canvas.Top=”240″ ></Button>

  • The two Button definitions are the equivalents of the “b_SubmitGuess” and “b_PlayAgain” buttons that we created in our Flash MovieClip.
  • x:Name=”b_SubmitGuess” : The name of our button object.
  • Click=”EventClickSubmitGuess” : The event to call when the button is clicked. This is the equivalent of setting onRelease in Flash ActionScript
  • Canvas.Left=”175″ Canvas.Top=”240″ : Again, XAML funky way of setting “X,Y” coordinates.

That’s it! The basics of XAML are quite easy to understand. However, the intricacies of the mark-up are very complicated. It can be used to create very sophisticated vector graphics and animations. We have only scratched the surface here. For anything more intricate, we would need a XAML GUI editor like Expression Blend 2.

C# : Page.xaml.cs

So now we have made it to the tasty meat of our discussion. Actual C# Silverlight code. This is where the fun begins, as we will see shortly that coding for Silverlight in C# and Flash AS2 are very similar.

To start, click on page.xaml.cs in the solution explorer to bring-up the C# code editor.

First, here is the complete source for you to peruse.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightHelloWorld
{
    public partial class Page : UserControl
    {
        int guesses = 0;
        int numbertoguess = 0;
        int userGuess = 0;

        public Page()
        {
            InitializeComponent();
            InitGame();
        }

        void InitGame()
        {
            guesses = 0;
            Random random = new Random();

            numbertoguess = random.Next(1, 100);
            t_messageText.Text = "Guess The Number From 1-100";
            t_instructionText.Text = "";
            t_guessText.Text = "You have guessed " + guesses.ToString() + " times";
            t_userGuess.Text = "";
            b_PlayAgain.Opacity = 0;
            b_PlayAgain.IsHitTestVisible = false;
            b_SubmitGuess.Opacity = 100;
            b_SubmitGuess.IsHitTestVisible = true;


        }


        void EventClickSubmitGuess(object sender, RoutedEventArgs e)

        {

            if (!Int32.TryParse(t_userGuess.Text, out userGuess)) {


                t_instructionText.Text = "You Must Type A Number Between 1 and 100";

            } else {

                guesses++;

                if (userGuess > numbertoguess)
                {
                    t_instructionText.Text = "Lower";
                }
                else if (userGuess < numbertoguess)
                {
                    t_instructionText.Text = "Higher";
                }
                else
                {
                    t_instructionText.Text = "You Got It!";
                    b_PlayAgain.Opacity = 100;
                    b_PlayAgain.IsHitTestVisible = true;
                    b_SubmitGuess.Opacity = 0;
                    b_SubmitGuess.IsHitTestVisible = false;

                }
            }
            t_guessText.Text = "You have guessed " + guesses.ToString() + " times";


        }

        void EventClickStartOver(object sender, RoutedEventArgs e)

        {
            InitGame();

        }
    }
}


  

Now we will break down this source, but this time we will try to keep the discussion to a comparison of the AS2 and C# Code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightHelloWorld
{
    public partial class Page : UserControl
    {
        int guesses = 0;
        int numbertoguess = 0;
        int userGuess = 0;

What is going on here?

  • This is the class definition for the Silverlight Page class.
  • using System; (etc.) These are all the default classes that are needed to create a default Silverlight application. using in C# is the equivalent to import in ActionScript.
  • namespace SilverlightHelloWorld : namespaces in C# are sort of like packages in AS3.
  • public partial class Page : UserControl : This is the actual class definition for Page.
    • partial classes are a way for C# to compose a single class from multiple sources.
    • Right now, you don’t need to know any more about this.
    • : UserControl is the way you inherit from another class in C#. It is the equivalent to “extends MovieClip” in AS2.
  • int guesses = 0; (etc) Here we initialize the class variables we need for the game. What is interesting here is what IS NOT listed. We do not have to define any of the text fields or buttons in the page.XAML in our code. They are automatically available. If we had coded our Flash version in AS#, this would have also been the case.
public Page()
        {
            InitializeComponent();
            InitGame();
        }

What is going on here?

  • This is the constructor. Unlike the Flash version, we don’;t have to do much here except make a couple function calls.
  • InitializeComponent(); This is the default behavior for the class. Don’t mess with it (right now any way).
  • InitGame(): The behavior here matches the Flash version exactly.
 void InitGame()
        {
            guesses = 0;
            Random random = new Random();

            numbertoguess = random.Next(1, 100);
            t_messageText.Text = "Guess The Number From 1-100";
            t_instructionText.Text = "";
            t_guessText.Text = "You have guessed " + guesses.ToString() + " times";
            t_userGuess.Text = "";
            b_PlayAgain.Opacity = 0;
            b_PlayAgain.IsHitTestVisible = false;
            b_SubmitGuess.Opacity = 100;
            b_SubmitGuess.IsHitTestVisible = true;


        }

What is going on here?

  • The InitGame() : function in C# is essentially the same as the AS2 version functionality, but some there are some differences in the code.
  • numbertoguess = random.Next(1, 100); This is (one of) C#’s nifty ways to get a random number.
  • b_PlayAgain.Opacity = 0; b_PlayAgain.IsHitTestVisible = false; This is the code to make the PlayAgain button invisible. The “visibility” property in XAML was not working for me, but making the Opacity = 0 did work. Opacity works like “_alpha” on Flash. However, you also need to make sure that the button cannot be pressed, even if you cannot see it. That is what the PlayAgain.IsHitTestVisible = false; code does.
void EventClickSubmitGuess(object sender, RoutedEventArgs e)

        {

            if (!Int32.TryParse(t_userGuess.Text, out userGuess)) {


                t_instructionText.Text = "You Must Type A Number Between 1 and 100";

            } else {

                guesses++;

                if (userGuess > numbertoguess)
                {
                    t_instructionText.Text = "Lower";
                }
                else if (userGuess < numbertoguess)
                {
                    t_instructionText.Text = "Higher";
                }
                else
                {
                    t_instructionText.Text = "You Got It!";
                    b_PlayAgain.Opacity = 100;
                    b_PlayAgain.IsHitTestVisible = true;
                    b_SubmitGuess.Opacity = 0;
                    b_SubmitGuess.IsHitTestVisible = false;

                }
            }
            t_guessText.Text = "You have guessed " + guesses.ToString() + " times";


        }

What is going on here?

  • This is the Event Handler for the b_SubmitGuess button.
  • Just like the AS2 version, this is the meat of the program. You will also notice that there are not many differences between this version and the AS2 version.
  • if (!Int32.TryParse(t_userGuess.Text, out userGuess) : While the loosely typed Flash AS2 has the very simple function isNaN(userGuess) to test to see if a variable is number or not, the strongly typed C# does not. (although VB.NET does have something similar…but don’t go there). Instead, you use the INT32.TryParse() static function call. This call does two things: checks if the value is an integer, and if so, places that integer in the variable you provide as the second parameter. This allows us to get rid of (the equivalent to) this line of code required in the Flash AS2 version: userGuess = Number(t_userGuess.text);
void EventClickStartOver(object sender, RoutedEventArgs e)

        {
            InitGame();

        }

What is going on here?

  • This is the Event Handler for the b_PlayAgain button. It works just like the Flash version.

 

And that is it!!!

To finish up, click the “build SilverlightHelloWorld” option in the Build menu to compile the project.

Then, right-click on the SilverLightHelloWorld title of the Solution Explorer and select “View In Browser”. You will see a temporary .HTML page housing your brand-new Silverlight game!!!

See the SilverLight version of Guess The Number Game

So now we have a complete “game” written in both Flash and Silverlight. It doesn’t do much, but it is the basis from which we can made all kind of new and interesting games in the future.

Leave a Reply