SIGN UP MEMBER LOGIN:    
ARTICLE

Creating a Silverlight Game-Part IV

Posted by Mamta M Articles | Silverlight with C# August 25, 2009
In this concluding part of the article series, we will see how to add code in the event handler.
Reader Level:
Download Files:
 


In this concluding part of the article series, we will see how to add code in the event handler.

Note
: The C# code given below may seem cumbersome to you and it's quite possible that you can develop a better version of it. You are welcome to implement the logic in your own way.

The XAML code for the button b1 in MainPage.xaml looks like this:

<
Button x:Name="b1" Content=" " Grid.Column="0" Grid.Row="0" Style="{StaticResource ButtonStyle1}"  />

Similarly it would be seen for all the nine buttons.

Add an event handler to trap the Click event as follows:

<
Button x:Name="b1" Content=" " Grid.Column="0" Grid.Row="0" Click="btnClick" Style="{StaticResource ButtonStyle1}"  />

This will auto-generate a Click event handler in the code-behind:

private
void btnClick(object sender, RoutedEventArgs e)
{
}

Add code in this event handler as follows:

if
(CheckGame())
{
      MessageBox.Show("Game over! you won");
      string newname, str, name;
      Button btn1, bn, btn;
      bn = (Button)e.OriginalSource;
      bn.Background = new SolidColorBrush(Colors.Yellow);
      str = bn.Content.ToString();
      name =  bn.Name; 
      int x = int.Parse(name.Substring(1)); 
      int[] arr = {1,2,4,5,7,8};
      if (arr.Contains(x))
      {
         if (CheckBlank(x+1))
         {
             btn = (Button)GridRoot.FindName(name); 
             btn.Content = " ";
             newname = "b"+(x+1);
             btn1 = (Button)GridRoot.FindName(newname); 
             btn1.Content = str;
         }
       }
      arr =  new int[]{2,3,5,6,9,8};
            if (arr.Contains(x))
            {
                if (CheckBlank(x - 1))
                {
                    btn = (Button)GridRoot.FindName(name);
                    btn.Content = " ";
                    newname = "b" + (x - 1);
                    btn1 = (Button)GridRoot.FindName(newname);
                    btn1.Content = str;
                }
             }
            arr = new int[] {1,2,3,4,5,6};
            if (arr.Contains(x))
            {
                if (CheckBlank(x + 3))
                {
                     btn = (Button)GridRoot.FindName(name);
                     btn.Content = " ";
                     newname = "b" + (x + 3);
                     btn1 = (Button)GridRoot.FindName(newname);
                     btn1.Content = str;
                }
            }
            arr = new int[] {4,5,6,7,8,9 };
            if (arr.Contains(x))
            {
                if (CheckBlank(x - 3))
                {
                     btn = (Button)GridRoot.FindName(name);
                    btn.Content = " ";
                     newname = "b" + (x -3);
                     btn1 = (Button)GridRoot.FindName(newname);
                    btn1.Content = str;
                }
            }
            if (CheckGame())
            {
                MessageBox.Show("Game over! you won");
            }
 }

The above code uses a pattern of numbers to check where the exchange between the blank cell and a filled cell should take place. To check whether the user clicked a particular cell, we make use of an array named arr and populate the numbers in it. Then we check whether the game is over by invoking a method CheckGame(). The code for this method is as follows:

private
bool CheckGame()
{
    string newname;
    Button b=null;
    bool flag = true;
    for(int index=1; index <= 8;index++)
    {
        newname = "b" + index;
        b = (Button)GridRoot.FindName(newname);
        int val = 0;
        if (!b.Content.Equals (" "))
        {
             val = int.Parse(b.Content.ToString());
             if (val != index)
             {
                       flag = false;
             }
        }
        else
             flag = false;
    }
    if (flag)
    {
         return true;
    }
    else
         return false;
 }

Finally, the code for the method CheckBlank() is as follows:

private
bool CheckBlank(int x)
{
     Button b=null;
     int i = 0;
     foreach (Control c in GridRoot.Children)
     {
         i++;
         b = (Button)c;
         if (b.Content.Equals(" "))
         {
            break;
         }
     }
     if (i == x)
         return true;
     else
         return false;
 }

Save, build and test the application.

Thus, you explored how to create a simple game using Silverlight and Blend. This example used very few effects and capabilities of Silverlight and Blend. If possible, try to implement lot more in your version of the code because both Silverlight and Blend have ample potential and powerful features.

Part I | Part II | Part III

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor