Click here to Skip to main content
15,867,568 members
Articles / Web Development / HTML
Article

Silverlights Out - An Introduction into Silverlight by Example

Rate me:
Please Sign up or sign in to vote.
3.19/5 (22 votes)
13 May 20074 min read 86.3K   195   35   14
An Introduction into Silverlight by Example

Silverlights Out 2.0

Live Online Demo

Introduction

Any sufficiently advanced technology is indistinguishable from magic.
—Arthur C. Clarke


"Silverlight is a cross-browser, cross-platform plug-in for delivering the next generation of Microsoft .NET–based media experiences and rich interactive applications for the Web." http://silverlight.net/

The best way to learn a new technology is by using it.
The most fun way to learn a new technology is by using it to make a game.

This is my first application I have written in Silverlight. Silverlight is a subset of .NET, just like the .NET Compact Framework is, and has it's own set of special rules, and ways of doing things.

If you want to learn more about Silverlights Outs, then check out my blog: http://www.cjcraft.com/blog/.

That's why I recommend learning Silverlight by first creating a simple application, something like Silverlights Out, so that new users can focus on what is new and different about creating Silverlight applications until they earn their "wings" so to speak.

Prerequisites

In order to create Silverlight applications you will need a machine, I recommend a virtual PC, and have it set up with the following Silverlight prerequisites:

  • Runtimes

    To get started with Silverlight, download the Silverlight 1.1 Alpha release to use .NET languages.

  • Microsoft Silverlight 1.1 Alpha [download]

    The runtime required to view Silverlight applications created with .NET Microsoft

  • Developer Tools

    Download the Visual Studio developer tools to start developing Silverlight applications.

  • Microsoft Visual Studio codename "Orcas" Beta 1 [download]

    The next generation development tool.

  • Microsoft Silverlight Tools Alpha for Visual Studio codename "Orcas" Beta 1 [download]

    The add-on to create Silverlight applications using .NET

  • Designer Tools

    Download the Expression designer tools to start designing Silverlight application.

  • Expression Blend 2 May Preview [download]

    Professional design tool to create user interaction for Silverlight.

  • Software Development Kit

    For documentation, samples and add-ins, also download the SDK's.

  • Microsoft Silverlight 1.1 Alpha Software Development Kit (SDK) [download]

    Download this SDK to create Silverlight Web experiences that target Silverlight 1.1 Alpha.
    The SDK contains documentation and samples.

Background

Wikipedia.org Article: Lights Out (puzzle) [view]

"Lights out, also known as Fiver, is a one player puzzle that is played on a m by n grid of squares in which every square has two states: on and off. The game usually starts off with all squares off, where the goal is to turn on every square. By selecting a square, itself and all the surrounding squares' (up, down, left, right) state is turned toggled. For example, on a 3 by 3 grid of squares with all squares off, if the center one is selected, it will turn "on" and so will 4 other squares."

Silverlights Out demonstrates the following features:

  • Animated scrolling starfield background
  • Transparency
  • Timer

Using the code

Puzzle games like Silverlights Out are great to learn a new language or technology with since you get a taste of everything without anything too challenging getting in the way of success.

Main Methods

RandomizeBoard()

This method handles randomizing the board before a game start.

This is accomplished by looping through every square, and randomly deciding to call ToggleSquare() on it or not.

C#
private void RandomizeBoard()
{
    // create a randomizer
    Random random = new Random();

    // loop through each squares
    for (int i = 0; i < squares.Count; i++)
    {
        // fifty / fifty toggle square
        if (Convert.ToBoolean(random.Next(2)))
        {
            ToggleSquare(squares[i]);
        }
    }
}

ClickSquare()

This function is responsible for managing which square the user has clicked.

First, we grab the square's name, and then we call ToggleSquare() on all appropriate squares.

C#
private void ClickSquare(object sender, MouseEventArgs e)
{
    Image image = sender as Image; // cast sender object into Image

    int index = squares.IndexOf(image); // get index of clicked square

    if (index > 4) // make sure we are not on topmost row
        ToggleSquare(squares[index - 5]); 
                // toggle square above clicked square

    if (index % 5 != 0)
        ToggleSquare(squares[index - 1]); 
                // toggle square to left of clicked square

    ToggleSquare(squares[index]); // toggle clicked square

    if (index % 5 != 4)
        ToggleSquare(squares[index + 1]); 
                // toggle square to right of clicked square

    if (index < 20) // make sure we are not on bottommost row
        ToggleSquare(squares[index + 5]); 
                // toggle square below clicked square
}

ToggleSquare()

When a square is clicked, this helper method decides the results for the nearby squares.

If the square is on, we turn it off; otherwise we turn it back on. Then we check the board for a win state. We also set and change the image opacity for a nice effect.

C#
private void ToggleSquare(Image image)
{
    // check if square is on
    if (image.Source == vistaLogoOn.Source)
    {
        image.Source = vistaLogoOff.Source;
        image.Opacity = 0.50;
    }
    else
    {
        image.Source = vistaLogoOn.Source;
        image.Opacity = 0.75;
    }

    if (CheckForWin())
        gameStatus.Text = "You Win";
}

CheckForWin()

After a move is made, this helper function determines if the board is in a win state.

We loop through every square, and count how many are on and off. If all are the same, the user has won.

C#
private bool CheckForWin()
{
    int onCount = 0; // assume no square on by default
    bool checkForWin = false; // assume player did not win

    // loop through all squares
    for (int i = 0; i < squares.Count; i++)
    {
        if (squares[i].Source == vistaLogoOn.Source)
            onCount++;
    }

    // if all lights are on or off then player wins
    if (onCount == 0 || onCount == 25)
        checkForWin = true;

    return checkForWin;
}

Tips & Tricks

Browser.HtmlTimer

I found there is an HtmlTimer class in Silverlight 1.1. This class is undocumented and marked obsolete. Visual Studio shows a warning after compilation: 'System.Windows.Browser.HtmlTimer' is obsolete: 'This is not a high resolution timer and is not suitable for short-interval animations. A new timer type will be available in a future release.

C#
...
// use the browser's HtmlTimer to refresh background regularly

System.Windows.Browser.HtmlTimer timer = 
                new System.Windows.Browser.HtmlTimer();
timer.Interval = 1;
timer.Enabled = true;
timer.Tick += new EventHandler(timer_Tick);
...

void timer_Tick(object sender, EventArgs e)
{
   double currentLeft = (double)background.GetValue(Canvas.LeftProperty);
   if (currentLeft <= 0)
   {
      // move background pixels over>
      background.SetValue(Canvas.LeftProperty, currentLeft + 2);
   }
   else
   {
      // reset backgrounds position
      background.SetValue(Canvas.LeftProperty, -340);
   }
}

Points of Interest

Be sure to check out the timer code using System.Windows.Browser.HtmlTimer, for now, it is the easiest way to do raw animations.

Resources

Most everything you'll need to use and learn Silverlight is listed at the sites below:

History

  • 2007.05.13 Uploaded original article
  • 2007.05.14 Converted code to use arrays and loops

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralLink not working Pin
fred800923-Aug-08 9:09
fred800923-Aug-08 9:09 
QuestionUmm...you're live demo's got a bug. Pin
ChristopherHenderson22-May-07 8:24
ChristopherHenderson22-May-07 8:24 
GeneralVery good mindmap Pin
Ward15-May-07 1:08
Ward15-May-07 1:08 
GeneralRe: Very good mindmap Pin
CJCraft.com15-May-07 7:38
CJCraft.com15-May-07 7:38 
QuestionAnyone want a sequel? Pin
CJCraft.com13-May-07 13:53
CJCraft.com13-May-07 13:53 
AnswerRe: Anyone want a sequel? Pin
jonnii13-May-07 22:55
jonnii13-May-07 22:55 
GeneralRe: Anyone want a sequel? Pin
ribawaja14-May-07 3:18
ribawaja14-May-07 3:18 
GeneralRe: Anyone want a sequel? Pin
irrdev14-May-07 5:08
irrdev14-May-07 5:08 
GeneralRe: Anyone want a sequel? Pin
CJCraft.com14-May-07 16:14
CJCraft.com14-May-07 16:14 
GeneralRe: Anyone want a sequel? Pin
CJCraft.com14-May-07 16:06
CJCraft.com14-May-07 16:06 
GeneralRe: Anyone want a sequel? Pin
jonnii14-May-07 23:16
jonnii14-May-07 23:16 
GeneralRe: Anyone want a sequel? Pin
Tim Kohler5-Jul-07 7:46
Tim Kohler5-Jul-07 7:46 
AnswerRe: Anyone want a sequel? Pin
thund3rstruck18-May-07 4:49
thund3rstruck18-May-07 4:49 
AnswerRe: Anyone want a sequel? Pin
simonor4-Jan-08 5:16
simonor4-Jan-08 5:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.