Click here to Skip to main content
15,881,618 members
Articles / Programming Languages / C#

Breakout in Silverlight

Rate me:
Please Sign up or sign in to vote.
4.61/5 (19 votes)
15 Apr 2010CPOL2 min read 35K   2.1K   29   7
An implementation of classic breakout game in Silverlight
BreakOut

Introduction  

Silverlight technology serves one of the best platforms to write web based games. The main advantage is that shapes in Silverlight draw themselves and they support the same events as other elements. So we don’t need to worry about painting process of shapes, etc. This game also serves as the basics to develop a game in Silverlight.

Game Play

gamestart.png

After selecting the game mode in the first screen, you will see game board; the game will start using “space bar” key. Left and right arrow keys are used to move the bar left or right.

Game Components

The solution of Breakout game consists of the following folder structure.

BreakOut

Brick Component

Brick.xaml file is the representation of Brick in game. A brick is initialized using its contructor, c is a canvas on which brick is drawn in a specified location and color.

C#
public Brick(Canvas c, Point location, Color color)
{
    InitializeComponent();
    _color = color;
    brickColor.Color = _color;
    this.X = location.X;
    this.Y = location.Y;
    c.Children.Add(this);
}

When a brick is destroyed, an animation plays that will make the size of brick to 0 and Sounds\BrickDestroyed.mp3 sound is played.

XML
<storyboard x:name="brickDestroyed">
    <doubleanimationusingkeyframes begintime="00:00:00" 
	storyboard.targetname="scaleTransform" storyboard.targetproperty="ScaleY">
        <splinedoublekeyframe keytime="00:00:01" value="0">
    </doubleanimationusingkeyframes>
    <doubleanimationusingkeyframes begintime="00:00:00" 
	storyboard.targetname="scaleTransform" storyboard.targetproperty="ScaleX">
        <splinedoublekeyframe keytime="00:00:01" value="0">
    </doubleanimationusingkeyframes>
</storyboard>

Ball Component

Ball is moved on canvas using specified speed, Move() method in ball class will move ball to new X and Y location.

C#
/// <summary>
/// This method will move ball according to its current speed and direction
/// </summary>
public void Move()
{
   X += ((_leftDirection) * SPEED);
   Y += ((_topDirection) * SPEED);
}

Bar Component

XML
<Canvas Background="Transparent">
        <Rectangle x:Name="bar" Stroke="#FF000000" RadiusY="20" RadiusX="20">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Brown" Offset="0"/>
                    <GradientStop Color="Black" Offset="0.6"/>
                    <GradientStop Color="Maroon" Offset="0.7"/>
                    <GradientStop Color="Red" Offset="1"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
</Canvas>
C#
/// <summary>
/// This function will move bar to right side according to its speed
/// </summary>
public void MoveRight()
{
    if ((X + SPEED) < Utility.PlayingAreaWidth - Bar.BarWidth)
    {
       X += SPEED;
    }
}

/// <summary>
/// This function will move bar to left side according to its speed
/// </summary>
public void MoveLeft()
{
    if ((X-SPEED) > 0)
    {
       X -= SPEED;
    }
}

Game Board

Gameboard logic is contained in GameBoard.xaml and GameBoard.xaml.cs file. I used canvas layout container as this container provides X and Y axis coordinates system to postion child element

XML
<canvas x:name="mainArea" width="500" height="600"><canvas.background>
    <imagebrush imagesource="Images/background.jpg"></canvas.background>
    <mediaelement x:name="gameBackGroundSound" 
	source="Sounds/BackGroundSound.mp3" autoplay="True" volume="0.3"
                mediaended="gameBackGroundSound_MediaEnded">
    <mediaelement x:name="gameOver" source="Sounds/GameOver.mp3" autoplay="False">
</canvas>

This class contains _mainTimer member variable that will trigger timer tick event to perform some tasks, like moving ball to its new location, checking whether game is over or not, collision detection, etc.

C#
DispatcherTimer _mainTimer = new DispatcherTimer();
/// <summary>
/// Main Game Loop
/// </summary>
void _mainTimer_Tick(object sender, EventArgs e)
{
   _ball.Move(); // move ball
   CheckGameOver(); // check game is over or not
   DetectCollision(); // collision detection
}

Collision Detection

DetectCollision() method checks collision of ball with bricks, board sides and bar. It uses the Utility.GetDistance(Point point1, Point point2) method in utility class to calculate the distance between two points.

C#
/// <summary>
/// Collision detection logic
/// </summary>
private void DetectCollision()
{   
   // Check collision with sides
   CheckCollisionWithSides();

   // Check collision with bar
   Point p1;
   Point p2;
   CheckCollisionWithBar(out p1, out p2);

   // Collision with Bricks
   Brick brickToRemove = null;
   CheckCollisionWithBricks(ref p1, ref p2, ref brickToRemove);

   if (brickToRemove != null)
   {
       _bricks.Remove(brickToRemove);
       score += 10;
   }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


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

Comments and Discussions

 
GeneralMy vote of 5 Pin
kaishen12-Aug-10 20:06
kaishen12-Aug-10 20:06 
GeneralRe: My vote of 5 Pin
Yasser Azeem22-Sep-10 2:11
Yasser Azeem22-Sep-10 2:11 
GeneralMy vote of 4 Pin
Howard Richards30-Jun-10 10:07
Howard Richards30-Jun-10 10:07 
GeneralRe: My vote of 4 Pin
Yasser Azeem6-Jan-11 23:43
Yasser Azeem6-Jan-11 23:43 
GeneralExcellent work Pin
shahzadafzal10-Apr-10 8:39
shahzadafzal10-Apr-10 8:39 
GeneralGood example for starters Pin
junaid10910-Apr-10 7:50
junaid10910-Apr-10 7:50 
GeneralExcellent Article for game developers new to Silverlight Pin
Nausherwan10-Apr-10 7:39
Nausherwan10-Apr-10 7:39 

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.