<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" media="screen" href="/styles/xslt/rss.xslt"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:c9="http://channel9.msdn.com">
<channel>
	<title>Channel 9</title>
    <atom:link rel="self" type="application/rss+xml" href="http://channel9.msdn.com/Niners/c4f.Andy-Beaulieu/Posts/RSS"></atom:link>
    <itunes:summary></itunes:summary>
    <itunes:author>Microsoft</itunes:author>
    <itunes:subtitle></itunes:subtitle>
    <image>
      <url>http://mschnlnine.vo.llnwd.net/d1/Dev/App_Themes/C9/images/feedimage.png</url>
      <title>Channel 9</title>
      <link>http://channel9.msdn.com/Niners/c4f.Andy-Beaulieu/Posts</link>
    </image>
    <itunes:image href=""></itunes:image>
    <itunes:category text="Technology"></itunes:category>
    <description>Channel 9 keeps you up to date with the latest news and behind the scenes info from Microsoft that developers love to keep up with. From LINQ to SilverLight – Watch videos and hear about all the cool technologies coming and the people behind them.</description>
    <link>http://channel9.msdn.com/Niners/c4f.Andy-Beaulieu/Posts</link>
    <language>en</language>
    <pubDate>Sun, 26 May 2013 09:04:06 GMT</pubDate>
    <lastBuildDate>Sun, 26 May 2013 09:04:06 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>2</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Creating a Shuffleboard Game using Silverlight</title>
      <description><![CDATA[<p>In this walkthrough, we will create a <a href="http://en.wikipedia.org/wiki/Table_shuffleboard">
table shuffleboard</a> style game for Windows Phone 7 using Silverlight. Many bars feature these long wooden table games, in which players slide metal pucks down the length of the table, attempting to get as close as possible to the far end without sliding
 off the edge.</p>

<h3><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/6378.image_5F00_28FB581F.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/2086.image_5F00_thumb_5F00_2F422EAD.png" width="223" height="435"></a>
 Multi-Targeting</h3>
<p>Windows Phone 7 uses a version of Silverlight 3 with a few bonus features. Because this version of Silverlight is so close to the Web version of Silverlight 3, we'll take the approach of
<i>Multitargeting</i> a solution for both platforms. To do so, start with a Silverlight 3 (web) application template, and then add in a Windows Phone project with linked files that re-use the Silverlight 3 solution. This allows us to deploy to many different
 platforms using the same code base.</p>
<p>Let's get started by creating our Solution in this way.</p>
<h3>Creating the Solution and MainPage</h3>
<ol>
<li>In Expression Blend 4, create a new Silverlight Application &#43; Website template named Shuffleboard. Be sure to select “3.0” from the Version dropdown, as this is what is supported by Windows Phone (in a little bit we'll add in the Windows Phone project template
 as well). <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/4721.image_5F00_740E52E1.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/3731.image_5F00_thumb_5F00_2599C077.png" width="465" height="427"></a>
</li><li>In the Objects and Timeline Panel, select the main UserControl and set its Width to 480 and its Height to 800. This is the size of a Windows Phone UI in Portrait mode.
</li><li>Select the LayoutRoot Grid and set its Width to 480 and its Height to 800. </li><li>For games, a Canvas layout container is better than a Grid, so let's change the LayoutRoot container type. Right-click LayoutRoot and select Change Layout Type/Canvas.
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/0820.image_5F00_57252E0C.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8865.image_5F00_thumb_5F00_5DD8378F.png" width="299" height="304"></a>
</li><li>Since some parts of our UI can appear outside of the game area, we want to add a Clip to this main canvas so that the user does not see these outside elements. Add the following just under the LayoutRoot Canvas:
<br>
This XAML is snippet “<b>MainPage Clip</b>” inside snippets.txt.
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Canvas.Clip</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">RectangleGeometry</span> <span class="attr">Rect</span><span class="kwrd">=&quot;0,0,480,800&quot;</span><span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Canvas.Clip</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<!--
.csharpcode, .csharpcode 
 {font-size:small;
 color:black;
 font-family:consolas,"Courier New",courier,monospace;
 background-color:#ffffff}
.csharpcode 
 {margin:0em}
.csharpcode .rem
 {color:#008000}
.csharpcode .kwrd
 {color:#0000ff}
.csharpcode .str
 {color:#006080}
.csharpcode .op
 {color:#0000c0}
.csharpcode .preproc
 {color:#cc6633}
.csharpcode .asp
 {background-color:#ffff00}
.csharpcode .html
 {color:#800000}
.csharpcode .attr
 {color:#ff0000}
.csharpcode .alt
 {background-color:#f4f4f4;
 width:100%;
 margin:0em}
.csharpcode .lnum
 {color:#606060}
-->
</style></li><li>We'll be using some pre-built Behaviors that make it easy to introduce physics into Silverlight using the Farseer Physics Library. Right-click the Silverlight project and select Add Reference. Select the following assemblies, located in the sample download:
<br>
<br>
\ShuffleBoard\Bin\Debug\FarseerPhysics.dll <br>
\ShuffleBoard\Bin\Debug\Spritehand.FarseerHelper.dll <br>
\ShuffleBoard\Bin\Debug\Spritehand.PhysicsBehaviors.dll <br>
<br>
<strong>NOTE: </strong>To learn more about the Physics Helper Library, visit <a href="http://physicshelper.codeplex.com">
http://physicshelper.codeplex.com</a> </li></ol>
<p align="center"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="512" height="384">
<param name="source" value="http://channel9.msdn.com/App_Themes/default/VideoPlayer10_01_18.xap" />
<param name="initParams" value="deferredLoad=true,duration=0,m=http://ecn.channel9.msdn.com/o9/ch9/8/9/1/6/5/5/ShuffleboardPart1_2MB_ch9.wmv,autostart=false,autohide=true,showembed=true, thumbnail=http://ecn.channel9.msdn.com/o9/ch9/8/9/1/6/5/5/ShuffleboardPart1_512_ch9.png, postid=556198" />
<param name="background" value="#00FFFFFF" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" />
</a>
</object></p>
<h3>Creating the Game User Control</h3>
<p>Next we'll create a separate user control that will contain the core game logic. By creating a separate user control, we can easily target different platforms by placing the user control inside different MainPage elements.
</p>
<ol>
<li>Right-click the Shuffleboard Silverlight project and select Add New Item. Select UserControl and name the control “ucMainGame”.
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/0523.image_5F00_127893CB.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/7701.image_5F00_thumb_5F00_1616AEA8.png" width="299" height="324"></a>
</li><li>Change the LayoutRoot element from a Grid to a Canvas. </li><li>Set the Width to 480 and the Height to 800 for both the UserControl and LayoutRoot Canvas elements.
</li><li>Set the Background color to Black for the LayoutRoot Canvas. </li><li>Build the project by pressing Ctrl&#43;Shift&#43;B. </li><li>Back on MainPage, add an instance of ucMainGame to the page by going to the Assets Panel and expanding Controls/All. Drag an instance of ucMainGame to the artboard.
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/1513.image_5F00_5C939EB0.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/6305.image_5F00_thumb_5F00_432B9B76.png" width="496" height="296"></a>
</li><li>Rename the ucMainGame control to ucMainGame1. </li><li>Set the Left and Top properties of ucMainGame1 to 0. </li></ol>
<h3>Creating the Table</h3>
<p>We'll use a pre-rendered PNG image for the shuffleboard table.</p>
<ol>
<li>Create a new subfolder in the Silverlight project named “images”. </li><li>Add the following JPG image into the new images subfolder, located in the sample download:
<br>
\ShuffleBoard\images\shuffleboardTable.jpg </li><li>Open the ucMainGame user control. </li><li>Insert a new Canvas element named cnvTable, and set the following attributes:
<ol>
<li>Width = 480 </li><li>Height = 800 </li><li>Left = 0 </li><li>Top = 0 </li></ol>
</li><li>In the Assets Panel, expand the Behaviors category and drag a PhysicsControllerBehavior on the cnvTable. This behavior introduces the core physics simulation into the game. Set the properties of the Physics Contoller as follows (this turns of gravity and
 sets some other physics parms): <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/1512.image_5F00_14D215C9.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/7701.image_5F00_thumb_5F00_49727204.png" width="333" height="293"></a>
</li><li>Inside the cnvTable Canvas, add a second Canvas named cnvTableInner, which will hold the table image. Set the following properties on cnvTableInner:
<ol>
<li>Width = 360 </li><li>Height = 1077 </li><li>Left = 60 </li><li>Top = -277 </li></ol>
</li><li>Drag the shuffleboardTable.jpg image from the Projects Panel into cnvTableInner. Set the following properties on the image:
<ol>
<li>Width = 360 </li><li>Height = 1077 </li><li>Left = 0 </li><li>Top = 0 </li></ol>
</li><li>The Objects and Timeline Panel should look like so: <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/0042.image_5F00_223828CF.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8468.image_5F00_thumb_5F00_0144B628.png" width="278" height="221"></a>
</li><li>We will need to detect when a puck hits the edge of the table and “falls off.” Let's add in some Rectangle elements and add Physics Behaviors to them.
</li><li>Add a new Rectangle named rectSensorLeft and size it so that it covers the entire left side of the table. Set the following properties:<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/0042.image_5F00_6EFBEF65.png"><img title="image" border="0" alt="image" align="right" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/7701.image_5F00_thumb_5F00_5FE5108B.png" width="122" height="240"></a>
<ol>
<li>Width = 60 </li><li>Height = 1190 </li><li>Left = -40 </li><li>Top = -334 </li><li>Opacity = 20% </li></ol>
</li><li>Drag a PhysicsObjectBehavior from the Assets Panel Behaviors onto rectSensorLeft, and then set its IsStatic property to true.
</li><li>Add three more Rectangles by copying rectSensorLeft, so that they surround the borders of the table:
<ol>
<li>rectSensorRight </li><li>rectSensorTop </li><li>rectSensorBottom </li></ol>
</li><li>Your artboard should look similar to the following: <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8054.image_5F00_467D0D51.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/2110.image_5F00_thumb_5F00_4C57B0EA.png" width="195" height="412"></a>
</li><li>Now we'll add in the goal Rectangles at the end of the table. These will be used to determine the number of points a puck receives. Draw out three Rectangles that cover the width of the board and are 100 pixels high. Name these rectPoints3, rectPoints2,
 and rectPoints1. Set their Stroke to Red and their Fill to No brush. </li><li>Add a TextBlock element inside each Rectangle to depict the points. Set the text properties to 3, 2, and 1 so that the artboard looks similar to the following:
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/7416.image_5F00_647B1B45.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/3603.image_5F00_thumb_5F00_099865B2.png" width="430" height="353"></a>
</li><li>We'll also need a Rectangle representing the “slide zone” where players can legally slide a puck (we don't want to allow sliding all of the way down the table!). Add a Rectangle named rectInBounds and position it at the lower end of the table:
<ol>
<li>Width=360 </li><li>Height=292 </li><li>Left = 60 </li><li>Top = 508 </li><li>Fill = No Brush </li><li>Stroke = Red </li></ol>
</li></ol>
<p align="center"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="512" height="384">
<param name="source" value="http://channel9.msdn.com/App_Themes/default/VideoPlayer10_01_18.xap" />
<param name="initParams" value="deferredLoad=true,duration=0,m=http://ecn.channel9.msdn.com/o9/ch9/9/9/1/6/5/5/ShuffleboardPart2_2MB_ch9.wmv,autostart=false,autohide=true,showembed=true, thumbnail=http://ecn.channel9.msdn.com/o9/ch9/9/9/1/6/5/5/ShuffleboardPart2_512_ch9.png, postid=556199" />
<param name="background" value="#00FFFFFF" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" />
</a>
</object></p>
<h3>Adding the Pucks</h3>
<p>For the pucks, we are going to add in an existing control which has the artwork completed.
</p>
<ol>
<li>Right-click the project and select Add Existing Item. </li><li>Browse to the following two files in the sample code download: <br>
\ShuffleBoard\ucPuck.xaml <br>
\ShuffleBoard\ucPuck.xaml.cs </li><li>Open ucPuck.xaml on the artboard and notice the following in the Objects and Timeline Panel:
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/4572.image_5F00_286ED990.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8308.image_5F00_thumb_5F00_1A3060A0.png" width="494" height="179"></a>
<ol>
<li>There is a Canvas named Puck that has a PhysicsObjectBehavior applied to it. This allows each instance of this Canvas to behave like a Physics Object so it animates with velocity and force and participates in collisions. Note that this Behavior has a large
 MomentOfInertia value. This keeps the object from rotating due to torque and collisions. Also note the RestitutionCoefficient, which gives the object some “bounce.”
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/6330.image_5F00_67CC8D20.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/3108.image_5F00_thumb_5F00_7289E475.png" width="328" height="198"></a>
</li><li>There is a “cnvInner” Canvas that defines the look of the Puck. </li><li>There is a StoryBoard defined, sbLostPuck, which we will execute when the puck “falls off the edge” of the table.
</li><li>Open the code-behind file, ucPuck.xaml.cs, and note the get / set property for the color of the puck. This will allow us to create both Red and Blue pucks for each player.
</li></ol>
</li><li>Build the project by hitting Ctrl&#43;Shift&#43;F5 and go back to ucMainGame. </li><li>From the Assets Panel, expand Controls/All and find the ucPuck control. Drag an instance of this onto the artboard. Name this
<b>bluePuck1</b>. </li><li>Copy and paste bluePuck1 twice so that you have three blue pucks. Name the new pucks
<b>bluePuck2</b> and <b>bluePuck3</b>. </li><li>Copy and paste a fourth puck and name it <b>redPuck1</b>. In the Properties Panel, go to the Miscellaneous Category and change the ColorHighlight and ColorMain properties to a Red color:
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/5340.image_5F00_4B4F9B40.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/2438.image_5F00_thumb_5F00_66F42736.png" width="334" height="217"></a>
</li><li>Copy and Paste <b>redPuck1</b> two times and rename these new pucks <b>redPuck2</b> and
<b>redPuck3</b>. </li><li>Let's test our table. Find the PhysicsControllerBehavior just under the cnvTable Canvas in the Objects and Timeline Panel and set the MousePickEnabled property to true.
</li><li>Run the project by clicking F5. Try dragging some pucks around with the mouse.
</li></ol>
<p align="center"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="512" height="384">
<param name="source" value="http://channel9.msdn.com/App_Themes/default/VideoPlayer10_01_18.xap" />
<param name="initParams" value="deferredLoad=true,duration=0,m=http://ecn.channel9.msdn.com/o9/ch9/1/0/2/6/5/5/ShuffleboardPart3_2MB_ch9.wmv,autostart=false,autohide=true,showembed=true, thumbnail=http://ecn.channel9.msdn.com/o9/ch9/1/0/2/6/5/5/ShuffleboardPart3_512_ch9.png, postid=556201" />
<param name="background" value="#00FFFFFF" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" />
</a>
</object></p><h3>Adding the Scoreboard</h3>
<p>We need a way of tracking players' scores, so let's add in a simple scoreboard for Blue vs. Red.</p>
<ol>
<li>Right-click the project and select Add Existing Item. </li><li>Browse to the following two files in the download: <br>
\ShuffleBoard\ShuffleBoard\ucScoreBoard.xaml <br>
\ShuffleBoard\ShuffleBoard\ucScoreBoard.xaml.cs </li><li>Open ucScoreBoard and notice the following:
<ol>
<li>It has a TextBlock for Red scores and a TextBlock for Blue scores. </li><li>In the code-behind, there are setters and getters to set the score. </li></ol>
</li><li>Build the project by selecting Ctrl&#43;Shift&#43;B. </li><li>Switch back to ucMainGame. </li><li>Drag an instance of ucScoreBoard from the Assets Panel onto into LayoutRoot. </li><li>Name the element <b>ucScoreBoard1</b>, and position it at the top left of the Canvas like so:
</li></ol>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/3286.image_5F00_2AC85B8E.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8080.image_5F00_thumb_5F00_257974DD.png" width="227" height="373"></a>
</p>
<h3>Adding a Player Up Display</h3>
<p>We'll need a simple control that displays which player's turn it is. </p>
<ol>
<li>Right-click the Silverlight project and select Add/Existing Item. </li><li>Browse to and select the following two files in the sample folder: <br>
\ShuffleBoard\ucPlayerUp.xaml <br>
\ShuffleBoard\ucPlayerUp.xaml.cs </li><li>Note the following about ucPlayerUp:
<ol>
<li>The code-behind file has a simple property, IsBlueTurn, which shows the appropriate message in the UI.
</li></ol>
</li><li>Build the project by clicking Ctrl&#43;Shift&#43;B </li><li>Back on ucMainGame, drag an instance of ucPlayerUp into cnvTableInner. </li><li>Name the control <b>ucPlayerUp1</b> , and set the following properties: <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/5661.image_5F00_4F797305.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/5672.image_5F00_thumb_5F00_43E3B5C6.png" width="296" height="229"></a>
</li></ol>
<h3>Adding a 3D Look</h3>
<p>Let's give our table a bit of a 3D look by adding a Perspective transform so the table appears to go off into the distance.
</p>
<ol>
<li>Create a new StoryBoard named sbRotateTable. <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/2541.image_5F00_4781D0A3.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/2134.image_5F00_thumb_5F00_4E34DA26.png" width="388" height="151"></a>
</li><li>Select the cnvTable Canvas element. </li><li>Advance the timeline ahead one second. </li><li>In the Properties Panel, under Projection, set the X value to -40. <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/0871.image_5F00_54E7E3A9.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/1464.image_5F00_thumb_5F00_46A96AB9.png" width="327" height="138"></a>
</li><li>Your artboard should now look something like this: <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8802.image_5F00_3460A3F7.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/3531.image_5F00_thumb_5F00_01909D83.png" width="352" height="428"></a>
</li><li>Close the Storyboard to end recording. <br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/3124.image_5F00_59EA2158.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/0003.image_5F00_thumb_5F00_04C2856B.png" width="300" height="129"></a>
</li><li>We want to rotate the table after the PhysicsController is initialized so the Physics Helper can determine the boundaries of the physics objects properly. Start by adding in some Using statements at the top of ucMainGame.xaml.cs:
<br>
This code is snippet “<b>ucMainGame Imports</b>” inside snippets.txt.
<pre class="csharpcode"><span class="kwrd">using</span> System.Collections.Generic;
<span class="kwrd">using</span> Spritehand.FarseerHelper;
<span class="kwrd">using</span> FarseerGames.FarseerPhysics.Mathematics;
<span class="kwrd">using</span> System.ComponentModel;</pre>
</li><li>Next, let's add in some class-level declarations, which will store the physics controller, list of pucks, and some variables used to track shooting and scoring:
<br>
This code is snippet “<b>ucMainGame Declarations</b>” inside snippets.txt.
<pre class="csharpcode">PhysicsControllerMain _physicsController;
List&lt;PhysicsSprite&gt; _pucks = <span class="kwrd">new</span> List&lt;PhysicsSprite&gt;();
List&lt;PhysicsSprite&gt; _redPucks = <span class="kwrd">new</span> List&lt;PhysicsSprite&gt;();
Point _ptStartShot;
<span class="kwrd">bool</span> _draggingPuck;
<span class="kwrd">int</span> _draggingStartTick;

<span class="kwrd">int</span> _currentPuckToShoot = 0;
<span class="kwrd">int</span> _currentPuckShot = -1;
<span class="kwrd">int</span> _gameOverScore = 15;</pre>
</li><li>In the ucMainGame() constructor, add some code to set the MaxFrameRate to 30 (Windows Phone will be limited to 30 FPS) and wire up the Loaded event handler.
<br>
This code is snippet “<b>ucMainGame Constructor</b>” inside snippets.txt.
<pre class="csharpcode"><span class="kwrd">this</span>.Loaded &#43;= <span class="kwrd">new</span> RoutedEventHandler(ucMainGame_Loaded);
Application.Current.Host.Settings.MaxFrameRate = 30;</pre>
</li><li>Implement the ucMainGame_Loaded event handler, which gets a reference to the Physics Controller and wires up our event handlers.
<br>
This code is snippet “<b>ucMainGame Loaded</b>” inside snippets.txt.
<pre class="csharpcode"><span class="kwrd">void</span> ucMainGame_Loaded(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    <span class="kwrd">if</span> (DesignerProperties.GetIsInDesignMode(<span class="kwrd">this</span>))
        <span class="kwrd">return</span>;

    _physicsController = 
        cnvTable.GetValue(
            PhysicsControllerMain.PhysicsControllerProperty
        ) <span class="kwrd">as</span> PhysicsControllerMain;
    _physicsController.Initialized &#43;= _physicsController_Initialized;
    _physicsController.Collision &#43;= _physicsController_Collision;
    _physicsController.TimerLoop &#43;= _physicsController_TimerLoop;
}</pre>
</li><li>Next, we'll add in the event handlers that we just wired up in the loaded event. Note that the Initialized event starts the Rotate Table StoryBoard.
<br>
This code is “<b>ucMainGame Event Handlers</b>” inside snippets.txt.
<pre class="csharpcode"><span class="kwrd">void</span> _physicsController_Initialized(<span class="kwrd">object</span> source)
{
    sbRotateTable.Begin();
}

<span class="kwrd">void</span> _physicsController_Collision(<span class="kwrd">string</span> sprite1, <span class="kwrd">string</span> sprite2)
{ }

<span class="kwrd">void</span> _physicsController_TimerLoop(<span class="kwrd">object</span> source)
{ }</pre>
</li><li>Run the Project by clicking F5. Note the 3D look and try manipulating the pucks with the mouse.
</li></ol>
<h3>Controlling the Pucks</h3>
<p>Next, we'll add logic to control the player's turn and control and along with score. Note that, when we implement the Windows Phone version in a bit, we can take advantage of Multitouch Manipulation events. But since these events are not available in the
 Web version of Silverlight 3, we'll use a simple mouse input mechanism.</p>
<ol>
<li>Let's turn off the default mouse manipulation. Select the PhysicsControllerBehavior just under the cnvTable Canvas and set the MousePickEnabled property to false.
</li><li>We need to get references to our Pucks, which the Physics Helper has translated into PhysicsSprite objects. A Physics Sprite contains the XAML UI for the Physics Object, plus the Physics Engine attributes for the underlying physics objects–including boundary
 shape, mass, velocity, etc. <br>
This code is “<b>ucMainGame Initialized</b>” inside snippets.txt. </li><li>Now we need to handle the Mouse events on the pucks in order to control the player's shot. When the player clicks the mouse down on a puck, we track the position along with time that they clicked. When the player moves the mouse, we update the puck position
 and also check if the player paused or moved backwards. We do this in case the player is just adjusting the puck position and not yet sliding the puck for a shot. Finally, in the Mouse up event, we release the puck in the specified direction and apply an appropriate
 amount of force to it.&nbsp; Copy in the snippet “<b>Puck Mouse Control</b>” from snippets.txt.&nbsp; Code is not shown here for brevity.
</li><li>When the Physics Helper Library does its magic, it translates existing UI Elements into PhysicsSprite objects. So what if we want to get at the original controls, perhaps to execute a StoryBoard that we defined on them? We can do this by using the FindName
 method to get the original user control instance. So, add the code below, which we'll use to get a reference to the Puck Storyboard “sbLostPuck”.
<pre class="csharpcode">ucPuck GetPuckControl(<span class="kwrd">string</span> spriteName)
{
    ucPuck puck;
    var parent = PhysicsControllerMain.ParentCanvas;
    <span class="kwrd">switch</span> (spriteName)
    {
        <span class="kwrd">case</span> <span class="str">&quot;Puck&quot;</span>:
            puck = parent.FindName(<span class="str">&quot;bluePuck1&quot;</span>) 
                    <span class="kwrd">as</span> ucPuck;
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> <span class="str">&quot;Puck_1&quot;</span>:
            puck = parent.FindName(<span class="str">&quot;bluePuck2&quot;</span>) 
                    <span class="kwrd">as</span> ucPuck;
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> <span class="str">&quot;Puck_2&quot;</span>:
            puck = parent.FindName(<span class="str">&quot;bluePuck3&quot;</span>) 
                    <span class="kwrd">as</span> ucPuck;
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> <span class="str">&quot;Puck_3&quot;</span>:
            puck = parent.FindName(<span class="str">&quot;redPuck1&quot;</span>) 
                    <span class="kwrd">as</span> ucPuck;
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> <span class="str">&quot;Puck_4&quot;</span>:
            puck = parent.FindName(<span class="str">&quot;redPuck2&quot;</span>) 
                    <span class="kwrd">as</span> ucPuck;
            <span class="kwrd">break</span>;
        <span class="kwrd">default</span>:
            puck = parent.FindName(<span class="str">&quot;redPuck3&quot;</span>) 
                    <span class="kwrd">as</span> ucPuck;
            <span class="kwrd">break</span>;
    }

    <span class="kwrd">return</span> puck;
}</pre>
</li><li>Finally, to score, we'll determine if the puck lies between any of the Rectangles in the end zone.
<br>
This code is the snippet “Get Points for Puck” in snippets.txt.
<pre class="csharpcode"><span class="kwrd">int</span> GetPointsForPuck(PhysicsSprite puck)
{
    <span class="kwrd">int</span> score = 0;
    Vector2 puckPos = puck.BodyObject.Position;

    <span class="kwrd">double</span> left = Convert.ToDouble(
        rectPoints3.GetValue(Canvas.LeftProperty));
    <span class="kwrd">double</span> top = Convert.ToDouble(
        rectPoints3.GetValue(Canvas.TopProperty));

    <span class="kwrd">if</span> ((puckPos.X &gt; left &amp;&amp; puckPos.X &lt; left &#43; rectPoints3.Width) 
     &amp;&amp; (puckPos.Y &gt; top &amp;&amp; puckPos.Y &lt; top &#43; rectPoints3.Height))
        score = 3;

    left = Convert.ToDouble(rectPoints2.GetValue(Canvas.LeftProperty));
    top = Convert.ToDouble(rectPoints2.GetValue(Canvas.TopProperty));
    <span class="kwrd">if</span> ((puckPos.X &gt; left &amp;&amp; puckPos.X &lt; left &#43; rectPoints2.Width) 
     &amp;&amp; (puckPos.Y &gt; top &amp;&amp; puckPos.Y &lt; top &#43; rectPoints2.Height))
        score = 2;

    left = Convert.ToDouble(rectPoints1.GetValue(Canvas.LeftProperty));
    top = Convert.ToDouble(rectPoints1.GetValue(Canvas.TopProperty));
    <span class="kwrd">if</span> ((puckPos.X &gt; left &amp;&amp; puckPos.X &lt; left &#43; rectPoints1.Width) 
     &amp;&amp; (puckPos.Y &gt; top &amp;&amp; puckPos.Y &lt; top &#43; rectPoints1.Height))
        score = 1;

    <span class="kwrd">return</span> score;
}</pre>
</li></ol>
<h3>Implement the “Game Loop”</h3>
<p>Most games are controlled by a “Game Loop” that executes many times per second. Within this Game Loop, we can check for collisions, perform enemy AI, and scoring. The PhysicsController fires an event called “TimerLoop” that we can use for this purpose.</p>
<ol>
<li>Replace the existing TimerLoop and Collision events with the following code snippet, which checks to see if any pucks have been shot and if we are ready for the next shot. Do this by seeing if the puck velocity has slowed down to nearly a stop…
<br>
This code is snippet “<b>Timer Loop</b>” inside snippets.txt.
<pre class="csharpcode"><span class="kwrd">void</span> _physicsController_TimerLoop(<span class="kwrd">object</span> source)
{
    <span class="rem">// check to see if the current shot is completed</span>
    <span class="kwrd">if</span> (_currentPuckShot &gt;= 0)
    {
    var puck = _pucks[_currentPuckShot].BodyObject;

        <span class="kwrd">if</span> (puck.Enabled == <span class="kwrd">false</span> ||
          Math.Abs(puck.LinearVelocity.X) &lt; 3                                   
          &amp;&amp; 
          Math.Abs(puck.LinearVelocity.Y) &lt; 3)
        {
            <span class="rem">// did the shot clear the end zone?</span>
            <span class="kwrd">if</span> (!PointWithinBounds(
              <span class="kwrd">new</span> Point(puck.Position.X, 
                       puck.Position.Y)))
            {
                _currentPuckShot = -1;
                _currentPuckToShoot&#43;&#43;;
                SetupThePuck();
            }
        }
    }
}

<span class="kwrd">void</span> _physicsController_Collision(<span class="kwrd">string</span> sprite1, <span class="kwrd">string</span> sprite2)
{
    <span class="rem">// check for puck off sides</span>
    <span class="kwrd">if</span> (sprite1.StartsWith(<span class="str">&quot;rectSensor&quot;</span>) &amp;&amp; sprite2.StartsWith(<span class="str">&quot;Puck&quot;</span>))
    {
        ucPuck puck = GetPuckControl(sprite2);

        _physicsController.PhysicsObjects[sprite2].
            BodyObject.Enabled = <span class="kwrd">false</span>;

        puck.sbLostPuck.Begin();
    }
}</pre>
</li></ol>
<h3>Targeting Windows Phone</h3>
<p>So far, we've created a Silverlight 3, web-based version of a shuffleboard game. Next we'll quickly port this to Windows Phone, taking advantage of some of the platform's capabilities, such as multitouch. We'll do this by using
<i>linked files</i> that point back to our existing Silverlight 3 project.</p>
<ol>
<li>Right-click the Silverlight solution in Blend and select Add New Project. </li><li>Select Windows Phone Application and enter <b>ShuffleBoard.WindowsPhone</b> for the name.
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/6266.image_5F00_0B758EEE.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8738.image_5F00_thumb_5F00_51F27EF6.png" width="416" height="382"></a>
</li><li>Delete the <b>TitleGrid</b> and <b>ContentGrid</b> elements from the Objects and Timeline Panel.
</li><li>Convert LayoutRoot to a Canvas by right-clicking it and selecting Change Layout Type/Canvas.
</li><li>Right-click the project and select Add Reference. Browse to the following assemblies located in the sample download (these are the WindowsPhone versions of the Physics Helper and Farseer):
<br>
<br>
\ShuffleBoard.WindowsPhone\Bin\Debug\FarseerPhysics.dll <br>
\ShuffleBoard.WindowsPhone\Bin\Debug\Spritehand.FarseerHelper.dll <br>
\ShuffleBoard.WindowsPhone\Bin\Debug\Spritehand.PhysicsBehaviors.dll <br>
</li><li>We need references to the assemblies used for Behaviors. An easy way to do this is to add a Behavior to an element and then delete it. From the Assets panel, drag a PhysicsControllerBehavior onto LayoutRoot and then delete it. Note that this adds a reference
 to System.Windows.Interactivity to the project. </li><li>Next, we'll add in the linked files from the existing Silverlight 3 project. Right-click the ShuffleBoard.WindowsPhone project and select Add/Link to Existing Item. Select the following files:
<ol>
<li>ucMainGame.xaml </li><li>ucMainGame.xaml.cs </li><li>ucPlayerUp.xaml </li><li>ucPlayerUp.xaml.cs </li><li>ucPuck.xaml </li><li>ucPuck.xaml.cs </li><li>ucScoreBoard.xaml </li><li>ucScoreBoard.xaml.cs </li></ol>
</li><li>8. Add a new folder to the project named images. </li><li>9. Right-click the images folder and select Link to Existing item, then navigate to the following image in the sample folder:
<br>
\ShuffleBoard\images\shuffleboardTable.jpg <br>
</li><li>Build the project by clicking Ctrl&#43;Shift&#43;B. </li><li>From the Assets Panel, under Controls/All, find ucMainGame and drag an instance onto LayoutRoot. Set the Left and Top properties to 0.
</li><li>Right-click the WindowsPhone project and select “Startup” to set this as the startup project.
</li><li>Run the project by clicking F5. </li></ol><p align="center"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="512" height="384">
<param name="source" value="http://channel9.msdn.com/App_Themes/default/VideoPlayer10_01_18.xap" />
<param name="initParams" value="deferredLoad=true,duration=0,m=http://ecn.channel9.msdn.com/o9/ch9/5/0/2/6/5/5/ShuffleboardPart4_2MB_ch9.wmv,autostart=false,autohide=true,showembed=true, thumbnail=http://ecn.channel9.msdn.com/o9/ch9/5/0/2/6/5/5/ShuffleboardPart4_512_ch9.png, postid=556205" />
<param name="background" value="#00FFFFFF" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" />
</a>
</object></p><h3>Windows Phone Touch Input</h3>
<p>So far, we've used a simple mouse-event-based input mechanism for shooting the pucks. But on the Windows Phone 7 platform, we can do better than that by using Multitouch events. These events include an inertia property that will make our puck physics more
 realistic.</p>
<ol>
<li>Since we are going to need to support two different platforms now (Web and Windows Phone), we need to introduce a Conditional Compilation Symbol so that the compiler can differentiate between each platform's code.
</li><li>Open the solution inside Visual Studio by right-clicking it in the Projects Panel and then select “Edit in Visual Studio”
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/0410.image_5F00_7F739EB9.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/4604.image_5F00_thumb_5F00_78546241.png" width="215" height="189"></a>
</li><li>Right-click the ShuffleBoard.WindowsPhone Project and select Properties. </li><li>4. Add in a new compilation symbol for WINDOWS_PHONE. <br>
NOTE: Future releases of WP7 Tools will likely define a default compilation symbol, so you may already see one defined here.
<br>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/6366.image_5F00_713525C9.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/10025512/8726.image_5F00_thumb_5F00_09C4C31A.png" width="550" height="128"></a>
</li><li>Now we'll add in the Windows Phone-specific events for manipulation using touch. Open ucMainGame.xaml.cs and find the _physicsController_Initialized event handler. Replace the events for the mouse events with the following, which will wire up either the
 manipulation events (for Windows Phone) or the mouse events (for Silverlight Web):
<br>
This code is snippet “<b>Manipulation Events</b>” inside snippets.txt.
<pre class="csharpcode"><span class="preproc">#if</span> WINDOWS_PHONE
    puck.ManipulationStarted &#43;= 
      <span class="kwrd">new</span> EventHandler&lt;ManipulationStartedEventArgs&gt;
      (puck_ManipulationStarted);
    puck.ManipulationCompleted &#43;= 
      <span class="kwrd">new</span> EventHandler&lt;ManipulationCompletedEventArgs&gt;
      (puck_ManipulationCompleted);
    puck.ManipulationDelta &#43;= 
      <span class="kwrd">new</span> EventHandler&lt;ManipulationDeltaEventArgs&gt;
      (puck_ManipulationDelta);
<span class="preproc">#else</span>
    puck.MouseLeftButtonDown &#43;= 
      <span class="kwrd">new</span> MouseButtonEventHandler(puck_MouseLeftButtonDown);
    puck.MouseMove &#43;= 
      <span class="kwrd">new</span> MouseEventHandler(puck_MouseMove);
    puck.MouseLeftButtonUp &#43;= 
      <span class="kwrd">new</span> MouseButtonEventHandler(puck_MouseLeftButtonUp);
<span class="preproc">#endif</span></pre>
</li><li>Now we just need to implement those event handlers for manipulation. The main consideration here is that the ManipulationCompleted event passes in a FinalVelocity.LinearVelocity parameter, which we can use to create realistic physics from the user's shot:
<p>Add the code snippet “Manipulation Event Handlers” from snippets.txt</p>
<pre class="csharpcode">Vector2 force = <span class="kwrd">new</span> Vector2(
    (<span class="kwrd">float</span>)(e.FinalVelocities.LinearVelocity.X * scalePower), 
    (<span class="kwrd">float</span>)(e.FinalVelocities.LinearVelocity.Y * scalePower));</pre>
</li><li>Run the project by clicking F5, and try sliding some pucks. </li></ol>
<h3>Performance</h3>
<p>Depending on your configuration, you may experience poor performance for the shuffleboard game when running it in the Windows Phone emulator. There are different reasons for this, including video card drivers and virtualization settings. Please refer to
<a href="http://www.andybeaulieu.com/Home/tabid/67/EntryID/196/Default.aspx">this blog post</a>, which details these performance considerations.</p>
<ol>
<li>1. Inside the ucMainGame constructor, let's turn on the Frame Rate counter so we can see our current frame rate. This code is snippet “Frame Rate Counter” inside snippets.txt
<pre class="csharpcode">Application.Current.Host.Settings.EnableFrameRateCounter = <span class="kwrd">true</span>;</pre>
</li><li>Run the project by hitting F5, and note the current frame rate. <br>
<b>NOTE: Your development configuration may prevent you from having an adequate framerate in the Windows Phone Emulator! Please refer to
</b><a href="http://www.andybeaulieu.com/Home/tabid/67/EntryID/196/Default.aspx"><b>this blog post</b></a><b> for tips on emulator performance.</b>
</li></ol>
<p>One performance tweak we can easily make is taking advantage of hardware acceleration. Silverlight enables us to use the video card to render elements, which can greatly increase performance. To do this, we add a Cachemode=”BitmapCache” attribute to any
 elements we want to hardware accelerate.</p>
<ol>
<li>Open ucPuck.xaml and note that there is a CacheMode attribute on the Puck Canvas.
</li><li>Open ucMainGame.xaml and add a CacheMode attribute to the cnvTable Canvas element.
<pre class="csharpcode">&lt;Canvas x:Name=<span class="str">&quot;cnvTable&quot;</span> Width=<span class="str">&quot;480&quot;</span> Height=<span class="str">&quot;800&quot;</span> 
d:LayoutOverrides=<span class="str">&quot;Width, Height&quot;</span> CacheMode=<span class="str">&quot;BitmapCache&quot;</span>&gt;</pre>
</li><li>Run the project and note the frame rate change. </li></ol>
<p align="center"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="512" height="384">
<param name="source" value="http://channel9.msdn.com/App_Themes/default/VideoPlayer10_01_18.xap" />
<param name="initParams" value="deferredLoad=true,duration=0,m=http://ecn.channel9.msdn.com/o9/ch9/5/1/2/6/5/5/ShuffleboardPart6_2MB_ch9.wmv,autostart=false,autohide=true,showembed=true, thumbnail=http://ecn.channel9.msdn.com/o9/ch9/5/1/2/6/5/5/ShuffleboardPart6_512_ch9.png, postid=556215" />
<param name="background" value="#00FFFFFF" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" />
</a>
</object></p>
<h3>Adding Sound</h3>
<p>Sound is one area where Windows Phone and Web Silverlight differ a bit. Under Silverlight for Web, we can use the MediaElement class to play back WMA and MP3 format audio. Multiple instances of the MediaElement class can be played simultaneously, and the
 sound output will be automatically mixed.</p>
<p>However, on Windows Phone we have access to the XNA game libraries, including sound support. This is a much more efficient way to add mixed sound to a Silverlight game on Windows Phone, but it only supports WAV format sound files.
</p>
<p>The Physics Helper Library has a useful class wrapper for sounds, which we'll use to play a “hit puck” sound on both platforms.</p>
<ol>
<li>In the ShuffleBoard (Silverlight Web) project, right-click and select Add Folder.
</li><li>Name the folder sounds. </li><li>Add an existing item to the sounds folder from this location: <br>
\ShuffleBoard\ShuffleBoard\sounds\hitPuck.wma </li><li>Set the Build Action of the file to Content. </li><li>In the ShuffleBoard.WindowsPhone project, right-click and select Add Folder. </li><li>Name the folder sounds. </li><li>Add an existing item to the sounds folder from this location: <br>
\ShuffleBoard.WindowsPhone\sounds\hitPuck.wav </li><li>Set the Build Action of the file to Content. </li><li>Inside ucMainGame.xaml.cs, add a class-level declaration for a SoundMain class (this is defined in the Physics Helper Library):
<br>
This snippet is “<b>Declare the Sound</b>” inside snippets.txt.
<pre class="csharpcode">SoundMain _soundPuckHit;</pre>
</li><li>10. Inside the ucMainGame_Loaded event, add code to declare the two sounds. Note that Windows Phone uses a WAV format sound without a “/” prefix for the root.
<br>
This snippet is “<b>Declare the Sound</b>” inside snippets.txt.
<pre class="csharpcode"><span class="preproc">#if</span> WINDOWS_PHONE
    _soundPuckHit = <span class="kwrd">new</span> SoundMain(<span class="kwrd">this</span>.LayoutRoot,
                   <span class="str">&quot;sounds/hitPuck.wav&quot;</span>, 2, 0);
<span class="preproc">#else</span>
    _soundPuckHit = <span class="kwrd">new</span> SoundMain(<span class="kwrd">this</span>.LayoutRoot, 
                   <span class="str">&quot;/sounds/hitPuck.wma&quot;</span>, 2, 0);
<span class="preproc">#endif</span></pre>
</li><li>Inside the _physicscontroller_collision event, add code to play the sound if a puck-to-puck collision occurs and the velocity is &gt; 10:
<br>
This snippet is “<b>Play the Sound</b>” inside snippets.txt.
<pre class="csharpcode"><span class="rem">// check for puck to puck collsion</span>
<span class="kwrd">if</span> (sprite1.StartsWith(<span class="str">&quot;Puck&quot;</span>) &amp;&amp; sprite2.StartsWith(<span class="str">&quot;Puck&quot;</span>))
{
    PhysicsSprite sprite = _physicsController.PhysicsObjects[sprite1];

    <span class="kwrd">if</span> (Math.Abs(sprite.BodyObject.LinearVelocity.X) &gt; 10
        || Math.Abs(sprite.BodyObject.LinearVelocity.Y) &gt; 10)
    {
        _soundPuckHit.Play();
    }
}</pre>
</li><li>Run the project and try hitting pucks together. </li></ol>
<p align="center"><object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="512" height="384">
<param name="source" value="http://channel9.msdn.com/App_Themes/default/VideoPlayer10_01_18.xap" />
<param name="initParams" value="deferredLoad=true,duration=0,m=http://ecn.channel9.msdn.com/o9/ch9/9/0/2/6/5/5/ShuffleboardPart5_2MB_ch9.wmv,autostart=false,autohide=true,showembed=true, thumbnail=http://ecn.channel9.msdn.com/o9/ch9/9/0/2/6/5/5/ShuffleboardPart5_512_ch9.png, postid=556209" />
<param name="background" value="#00FFFFFF" />
<a href="http://go.microsoft.com/fwlink/?LinkID=124807" style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" />
</a>
</object></p>
<h3>Summary</h3>
<p>Since the 1.1 Alpha release, Silverlight has offered a compelling casual game development environment. With the addition of Windows Phone, along with demos of Silverlight running on other embedded devices, you can bet the future of Silverlight for gaming
 is bright.</p>
<p>Here are a few resources for more information:</p>
<blockquote>
<p>Andy's blog <br>
<a href="http://www.andybeaulieu.com">http://www.andybeaulieu.com</a></p>
<p>Andy's Silverlight Demos <br>
<a href="http://www.spritehand.com">http://www.spritehand.com</a></p>
<p>The Physics Helper Library <br>
<a href="http://physicshelper.codeplex.com">http://physicshelper.codeplex.com</a></p>
<p>Great free resource for learning Expression Blend and Silverlight <br>
<a href="http://www.microsoft.com/design/toolbox/">http://www.microsoft.com/design/toolbox/</a></p>
</blockquote>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Beaulieu/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:30175390e92d402d81c69e7600c925c0">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-Silverlight</comments>
      <itunes:summary>In this walkthrough, we will create a 
table shuffleboard style game for Windows Phone 7 using Silverlight. Many bars feature these long wooden table games, in which players slide metal pucks down the length of the table, attempting to get as close as possible to the far end without sliding
 off the edge. 


 Multi-Targeting
Windows Phone 7 uses a version of Silverlight 3 with a few bonus features. Because this version of Silverlight is so close to the Web version of Silverlight 3, we&#39;ll take the approach of
Multitargeting a solution for both platforms. To do so, start with a Silverlight 3 (web) application template, and then add in a Windows Phone project with linked files that re-use the Silverlight 3 solution. This allows us to deploy to many different
 platforms using the same code base. 
Let&#39;s get started by creating our Solution in this way. 
Creating the Solution and MainPage

In Expression Blend 4, create a new Silverlight Application &amp;#43; Website template named Shuffleboard. Be sure to select “3.0” from the Version dropdown, as this is what is supported by Windows Phone (in a little bit we&#39;ll add in the Windows Phone project template
 as well). 

In the Objects and Timeline Panel, select the main UserControl and set its Width to 480 and its Height to 800. This is the size of a Windows Phone UI in Portrait mode.
Select the LayoutRoot Grid and set its Width to 480 and its Height to 800. For games, a Canvas layout container is better than a Grid, so let&#39;s change the LayoutRoot container type. Right-click LayoutRoot and select Change Layout Type/Canvas.


Since some parts of our UI can appear outside of the game area, we want to add a Clip to this main canvas so that the user does not see these outside elements. Add the following just under the LayoutRoot Canvas:

This XAML is snippet “MainPage Clip” inside snippets.txt.
&amp;lt;Canvas.Clip&amp;gt;
    &amp;lt;RectangleGeometry Rect=&amp;quot;0,0,480,800&amp;quot;/&amp;gt;
&amp;lt;/Canvas.Clip&amp;gt;


We&#39;ll be using some pre-built Behavior</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-Silverlight</link>
      <pubDate>Tue, 15 Jun 2010 21:23:23 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-Silverlight</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/10025512_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/10025512_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Beaulieu </dc:creator>
      <itunes:author>Andy Beaulieu </itunes:author>
      <slash:comments>8</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Creating-a-Shuffleboard-Game-using-Silverlight/RSS</wfw:commentRss>
      <category>Expression Blend</category>
      <category>Gaming</category>
      <category>Mobile</category>
      <category>Physics</category>
      <category>Silverlight</category>
      <category>Windows Phone</category>
      <category>XAML</category>
    </item>
  <item>
      <title>Creating a Pinball Game in Silverlight: Using the Physics Helper Library + Farseer Physics</title>
      <description><![CDATA[
<p>In this tutorial, we'll create a Silverlight pinball game using <u>Behaviors</u><b>,
</b>a new addition to Expression Blend 3 &amp; Silverlight that allows you to create interactivity with little or no coding.
</p>
<p>Below you'll find a video and step-by-step walkthrough. </p>

<h3>Videos:</h3>
<ul>
<li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-1-of-10/">Part 1</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-2-of-10/">Part 2</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-3-of-10/">Part 3</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-4-of-10/">Part 4</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-5-of-10/">Part 5</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-6-of-10/">Part 6</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-7a-of-10/">Part 7a</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-7b-of-10/">Part 7b</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-8-of-10/">Part 8</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-9-of-10/">Part 9</a>
</li><li><a href="http://channel9.msdn.com/posts/Clint/Silverlight-Pinball-with-Farseer-Physics-Part-10-of-10/">Part 10</a></li></ul>
<h3>Setup and Prerequisites</h3>
<p>First you have to setup Physics Helper controls into Expression Blend. Follow these steps:</p>
<ol>
<li>Download the Physics Helper ZIP file from <a href="http://physicshelper.codeplex.com/Release/ProjectReleases.aspx">
http://physicshelper.codeplex.com/Release/ProjectReleases.aspx</a> </li><li>Extract the ZIP file contents and dump them into a folder. </li><li>Run <b>install.bat</b>. (Note: this copies a few required assemblies to a folder in Blend 3.<b>)</b>
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image001.jpg">
</li></ol>
<h3><a title="_Toc237838539" name="_Toc237838539"></a>Getting Started &amp; Making the Ball</h3>
<p>Next, you create the controller and the pinball. Here's how.</p>
<ol>
<li>Open Expression Blend 3 and create a new “Silverlight 3 Application &#43; Website” named PinballGame.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image002.jpg" width="400" height="324">
</li><li>Change your default layout container to a Canvas. You can do this in the Objects and Timeline panel by right-clicking LayoutRoot and selecting Change Layout Type/Canvas. Canvas layout containers are better for games because they allow for positioning of
 elements at absolute (x,y) coordinates. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image003.jpg" width="290" height="266">
</li><li>Give the application a bigger default size. Select the UserControl element in the Objects and Timeline panel. Then, in the Properties panel, change the Width to 800 and the Height to 600.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image004.png" width="269" height="190">
</li><li>Add a <b>Physics Controller Behavior</b> to our main game Canvas. From the Asset Panel, find the PhysicsController Behavior and drag it to the Objects and Timeline Panel. Then, drop it on the LayoutRoot Canvas.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image005.jpg" width="233" height="253">
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image006.jpg" width="233" height="122">
</li><li>Change a few of the PhysicsController's properties, to make it easier to use. In the Objects and Timeline Panel, select the PhysicsControllerBehavior assigned to LayoutRoot. Then, set the highlighted properties as follows in the Properties Window:
<br>
1.)&nbsp; Decrease the vertical gravity to 250 <br>
2.)&nbsp; Increase the iterations to 200. This will help with collision detection in a fast-action game.
<br>
3.)&nbsp; Set MousePickEnabled to true. This will allow us to manipulate objects with the mouse during development and testing.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image007.png" width="261" height="218">
</li><li>Create a &quot;playing field&quot; for the pinball. To do this, draw out a Rectangle onto the artboard, just off the bottom of the user control bounds. Set the properties of the Rectangle as follows:
<br>
<br>
<b>Name</b>: rectPlatform <br>
<b>Fill</b>: select a color of your choosing (light blue is selected below). <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image008.jpg" width="364" height="317">
</li><li>To make “rectPlatform” a physics element, we need to add a PhysicsObjectBehavior to it. Find the PhysicsObjectBehavior in the Assets panel and drag/drop it onto rectPlatform on the Artboard.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image009.png" width="343" height="369">
</li><li>In the Objects and Timeline Panel, select the PhysicsObjectBehavior belonging to rectPlatform. Then in the Properties Panel, set the IsStatic property to True so that the platform will stay in place.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image010.png" width="264" height="173">
</li><li>Next we'll create the ball. Draw out an Ellipse near the very top of the UserControl and set the following properties:
<br>
<b><br>
Name: </b>ellBall<b> <br>
Height</b>: 50 <br>
<b>Width</b>: 50 <br>
<b>Fill</b>: A color of your choosing. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image011.jpg" width="378" height="326">
</li><li>To make the ball a Physics Object, we need to add a PhysicsObjectBehavior to it. From the Asset Library, drag and drop a PhysicsObjectBehavior onto ellBall.
</li><li>Run the project by clicking F5. The ball should fall and hit the platform. Use the mouse to manipulate the ball.
</li></ol>
<h3><a title="_Toc237838540" name="_Toc237838540"></a>Making the Flippers</h3>
<p>In a pinball game, the Flippers are controlled by the player and are used to move the ball up the playfield. Standard pinball games have one right and one left flipper, but many games have three or more flippers located in various locations on the playfield.
 We'll create two user controls to represent the flippers – a right flipper and a left flipper – that way we can easily add as many flippers as we want to our main playfield.</p>
<ol>
<li>In the Projects Panel, right-click the PinballGame (Silverlight) project and select Add New Item. Select UserControl and name the control LeftFlipper.xaml.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image012.jpg" width="222" height="241">
</li><li>In the Objects and Timeline Panel, right-click LayoutRoot and select Change Layout Type/Canvas. This is required for the Physics Helper to work with nested User Controls.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image013.jpg" width="256" height="281">
</li><li>In the Objects and Timeline Panel, select the UserControl element and set its Width and Height to 200 x 200 pixels in the Properties Panel.
</li><li>Draw out a Rectangle that is about 200 x 50 pixels big, centered in the user control. Round the corners of the Rectangle.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image014.png" width="235" height="185">
</li><li>From the main Blend menu, select Object/Path/Convert to Path. This will create a new Path element from the Rectangle primitive. Then select the Direct Selection tool from the Toolbox, which will allow you to manipulate the individual points on the Path.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image015.png" width="37" height="84">
</li><li>Select the top, left two points on the Path and move them down so that you end up with a more “flipper like” shape:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image016.png" width="224" height="171">
</li><li>In the Toolbox, select the Selection arrow and rotate the flipper 45 degrees so that it looks similar to this (be sure the flipper is still within the bounds of the user control):
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image017.jpg" width="196" height="186">
</li><li>Right-click the flipper Path and select Group Into/Canvas. Name the Canvas <b>
cnvLeftFlipper</b> and resize it so that it surrounds the entire flipper Path. Note that you could “embellish” the cnvLeftFlipper with additional elements if you wish.
</li><li>Next we'll create a Joint so that the Flipper can rotate on an axis. We'll need something to anchor the joint to, so first let's add a small Static object to hold the Joint in place. Draw out a Rectangle at the upper left of the flipper and name the Rectangle
<b>rectHolder</b>. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image018.jpg" width="196" height="197">
</li><li>To add a Joint, we will need a UI element to visually represent where we want the joint created. You can use any element you want for this, but an Ellipse works pretty well. Draw out an Ellipse on top of the rectHolder.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image019.jpg" width="196" height="197">
</li><li>Now we can add all of the required Physics Behaviors to the User Control.
<ol>
<li>From the Asset Library, drag a PhysicsObjectBehavior to the rectHolder Rectangle. Set its IsStatic property to True. Since we don't really want to see the rectHolder in our UI, just send it to the back of the elements (Right-click, then select Order/Send
 to Back). </li><li>Drag a PhysicsObjectBehavior to the cnvLeftFlipper Canvas. Set the RestitutionCoefficent property to “0.1”. (This makes the flipper a bit more “bouncy” on collisions)
</li><li>Drag a PhysicsJointBehavior to the Ellipse. Set the Body1 property to “cnvLeftFlipper” and the Body2 property to “rectHolder”. Set the CollisionGroup to “1” and the AngleLimitLower and AngleLimitUpper to 0 and 50 respectively. Also enable the AngleSpring:
<br>
</li><li>Drag a PhysicsApplyTorqueBehavior to cnvLeftFlipper. We want to apply Torque when the user presses the Left arrow key, so we'll create a Trigger for this. Select the Behavior and in the Properties Panel, click the New Trigger button.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image021.png" width="267" height="191">&nbsp;
<br>
<br>
Select the PhysicsKeyTrigger type from the popup. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image022.jpg" width="197" height="296">
<br>
Set the Key property for the Trigger to “Left” and the TorqueValue to -100000 <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image023.png" width="264" height="187">
</li></ol>
</li><li>Build the Project so that the LeftFlipper user control is available. </li><li>Open MainPage.xaml and drag an instance of LeftFlipper from the Asset Library onto the Artboard. Position it near the bottom of the user control and slightly to the Left.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image024.jpg" width="373" height="321">
</li><li>Run the project and try the flipper with the Left arrow key. </li><li>In this step, we'll create a copy of “LeftFlipper” to make&nbsp; a “RightFlipper”. In the Projects Panel, right-click LeftFlipper.xaml and select Copy. Then right-click the PinBallGame Project and select Paste.
<br>
You now have a new User Control named “Copy of LeftFlipper.xaml”. Rename this to RightFlipper.xaml. Then in the code-behind file, make sure the Class and Constructor are also renamed to “RightFlipper”.
<br>
Change to XAML view for RightFlipper.xaml and change the x:Class attribute so that it inherits from RightFlipper:&nbsp;
<br>
<div id="codeSnippetWrapper">
<pre id="codeSnippet"><span>&lt;</span><span>UserControl</span> <br><span>xmlns</span><span>=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;</span> <br><span>xmlns:x</span><span>=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;</span> <br><span>xmlns:d</span><span>=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;</span> <br><span>xmlns:mc</span><span>=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;</span> <br><span>mc:Ignorable</span><span>=&quot;d&quot;</span> <br><span>xmlns:i</span>=&amp;<span>amp</span>;<span>quotclr-namespace:System</span>.<span>Windows</span>.<span>Interactivity</span>;<span>assembly</span>=<span>System</span>.<span>Windows</span>.<span>Interactivity</span><span>&quot; <br>    xmlns:pb=&quot;</span><span>clr-namespace:Spritehand</span>.<span>PhysicsBehaviors</span>;<span>assembly</span>=<span>Spritehand</span>.<span>PhysicsBehaviors</span><span>&quot; <br>x:Class=&quot;</span><span>PinballGame</span>.<span>RightFlipper</span><span>&quot; <br>d:DesignWidth=&quot;</span><span>640</span><span>&quot; d:DesignHeight=&quot;</span><span>480</span><span>&quot; Height=&quot;</span><span>200</span><span>&quot; Width=&quot;</span><span>200</span>&quot;<span>&gt;</span></pre>
<br>
</div>
Open RightFlipper.xaml and find the pathLeftFlipper element. Rename this to pathRightFlipper. Then, rename “cnvLeftFlipper” to “cnvRightFlipper”. Rename “rectHolder” to “rectRightHolder” and position the rectHolder and joint ellipse so that they are in the
 correct location for the flipper: <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image026.png" width="163" height="159">
<br>
Modify the PhysicsJointBehavior for the joint in the Objects and Timeline Panel. Change BodyOne to “cnvRightFlipper”, BodyTwo to “rectRightHolder” and change the Angle limits so they are appropriate for the opposite flipper:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image027.png" width="264" height="219">
<br>
Select the PhysicsApplyTorqueBehavior for cnvRightFlipper in the Objects and Timeline Panel. Change the Key property for the trigger to “Right” so that it will initiate on the Right Arrow key down. Also change the TorqueValue so that it will apply torque clockwise:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image028.png" width="265" height="190">
<br>
</li><li>Add an instance of RightFlipper onto the MainPage.xaml and position it to the right of LeftFlipper.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image029.jpg" width="372" height="325">
</li><li>Test the project by clicking F5. You can now click left and right arrows keys to manipulate the paddles.
</li></ol>
<h3><a title="_Toc237838541" name="_Toc237838541"></a>Creating the Playfield &#43; Scrolling</h3>
<p>Now let's create more of a playfield for our Pinball game and add a Camera control so that the game will scroll and always follow the pinball. Feel free to tweak the design as you wish.</p>
<ol>
<li>Open MainPage.xaml in Expression Blend and zoom out by using Ctrl plus minus (Ctrl -).
</li><li>Draw out a Path using the Pen tool for the right border. Note that you can extend above the upper bounds of the User Control. Group this into a Canvas named “cnvLeftBorder” (right click the Path and select Group Into/Canvas).
</li><li>Drag a PhysicsObjectBehavior from the Asset Library onto cnvLeftBorder and set the IsStatic property to True. Also set the CollisionGroup property to “1” so that collisions will not occur between the border and the Flippers.
</li><li>Repeat Steps 2 and 3 above for the right border, naming that cnvRightBorder. You should have something similar to the following:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image030.jpg" width="281" height="267">
</li><li>Continue adding border controls and applying physics behaviors until you are happy with your playfield. Make the playfield completely closed in so that the ball cannot escape (except by the bottom trap of course!)
</li><li>You can also add more LeftFlipper and RightFlipper controls so that the player can more easily move the ball up the playfield. Here is one example playfield design:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image031.jpg" width="238" height="336">
</li><li>To enable scrolling, we can add a Camera Controller to the ball, causing the camera to follow the ball around the screen. Drag a PhysicsCameraBehavior from the Asset Library onto the ellBall element.
</li></ol>
<h3><a title="_Toc237838542" name="_Toc237838542"></a>Creating a Kicking Target</h3>
<p>Pinball games have lots of different types of targets – some are simple sensors which give points on contact, others are little toys that gobble up the ball for a few seconds. In this step, we'll create a Kicking Target, which gives points when hit by the
 ball but also kicks the ball back in the opposite direction.</p>
<ol>
<li>Create a new User Control named KickingTarget. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image032.jpg" width="203" height="220">
</li><li>Change the LayoutRoot container to a Canvas by right-clicking and selecting Change Layout Type/Canvas.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image033.jpg" width="255" height="234">
</li><li>Select the [UserControl] in the Objects and Timeline Panel and set its Width and Height to 100 x 100.
</li><li>Draw out an Ellipse that is 90x90 pixels, and positioned at Left, Top 5,5 (so that it is centered in the control).
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image034.png" width="484" height="141">
</li><li>Draw out a second Ellipse that is 70x70 pixels and positioned and Left, Top 15, 15.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image035.png" width="131" height="130">
</li><li>Group the two Ellipses into a Canvas by selecting them both in the Objects and Timeline Panel and selecting Group Into/Canvas. Name the Canvas “cnvKicker”.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image036.png" width="281" height="204">
</li><li>Drag a PhysicsObjectBehavior from the Asset Library onto cnvKicker. Set the IsStatic and RestitutionCoefficient properties as shown below. Setting the RestitutionCoefficient above a value of 1 will make the object “kick” things back.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image037.png" width="265" height="174">
</li><li>Build the project so that the new user control is available. Then open MainPage.xaml and add a few instance of “KickingTarget” to the page.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image038.jpg" width="208" height="296">
</li><li>Run the project and try out the Kicking Targets. </li></ol>
<h3><a title="_Toc237838543" name="_Toc237838543"></a>Optimizing Performance</h3>
<p>Our pinball game is looking up, but the performance could be a lot better. The startup time for the game is taking quite awhile because the Physics Helper Library is determining the outline of all of the shapes. Also, the frame rate is too low.</p>
<p>By default, Silverlight has a target frame rate of 60 frames per second. This is great for a lot of casual games, but Pinball requires a bit more speed. Additionally, Silverlight 3 introduces GPU Acceleration which can greatly increase the performance of
 our game by offloading graphics operations to the Video Card.</p>
<ol>
<li>Open the Default.html page in the website project. This page hosts the Silverlight control and exposes the plugin parameters. Add the following parameters to the plug in to increase the default frame rate and enable GPU Acceleration for our game.
<div id="codeSnippetWrapper">
<pre id="codeSnippet"><span>&lt;</span><span>object</span> <span>data</span><span>=&quot;data:application/x-silverlight,&quot;</span> <span>type</span><span>=&quot;application/x-silverlight-2&quot;</span> <span>width</span><span>=&quot;800&quot;</span> <span>height</span><span>=&quot;600&quot;</span><span>&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;source&quot;</span> <span>value</span><span>=&quot;ClientBin/PinballGame.xap&quot;</span><span>/&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;onerror&quot;</span> <span>value</span><span>=&quot;onSilverlightError&quot;</span> <span>/&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;background&quot;</span> <span>value</span><span>=&quot;#010141&quot;</span> <span>/&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;minRuntimeVersion&quot;</span> <span>value</span><span>=&quot;3.0.40624.0&quot;</span> <span>/&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;MaxFrameRate&quot;</span> <span>value</span><span>=&quot;160&quot;</span> <span>/&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;EnableGPUAcceleration&quot;</span> <span>value</span><span>=&quot;true&quot;</span> <span>/&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;EnableCacheVisualization&quot;</span> <span>value</span><span>=&quot;false&quot;</span> <span>/&gt;</span> <br><span>&lt;</span><span>param</span> <span>name</span><span>=&quot;autoUpgrade&quot;</span> <span>value</span><span>=&quot;true&quot;</span> <span>/&gt;</span> <br><span>&lt;</span><span>a</span> <span>href</span><span>=&quot;http://go.microsoft.com/fwlink/?LinkID=149156&amp;ampv=3.0.40624.0&quot;</span> <span>style</span><span>=&quot;text-decoration: none;&quot;</span><span>&gt;</span> <br><span>&lt;</span><span>img</span> <span>src</span><span>=&quot;http://go.microsoft.com/fwlink/?LinkId=108181&quot;</span> <span>alt</span><span>=&quot;Get Microsoft Silverlight&quot;</span> <span>style</span><span>=&quot;border-style: none&quot;</span><span>/&gt;</span> <br><span>&lt;/</span><span>a</span><span>&gt;</span> <br><span>&lt;/</span><span>object</span><span>&gt;</span></pre>
<br>
</div>
</li><li>Apply the CacheMode attribute to <b><i>all elements</i></b> in the game that are static. Since our pinball game's elements are not animated, we can apply the CacheMode to each of them. (If the objects contained animations within them, then the Cache would
 be invalidated during animation).
<div id="codeSnippetWrapper">
<pre id="codeSnippet"><span>&lt;</span><span>Rectangle</span> <span>x:Name</span><span>=&quot;rectPlatform&quot;</span> <span>CacheMode</span><span>=&quot;BitmapCache&quot;</span> <span>Fill</span><span>=&quot;#FF8AD0C9&quot;</span> <span>Height</span><span>=&quot;70&quot;</span> <span>Width</span><span>=&quot;800&quot;</span> <span>Canvas</span>.<span>Left</span><span>=&quot;-14&quot;</span> <span>Canvas</span>.<span>Top</span><span>=&quot;2172&quot;</span> <span>Opacity</span><span>=&quot;0&quot;</span><span>&gt;</span> <br><span>&lt;</span><span>i:Interaction.Behaviors</span><span>&gt;</span> <br><span>&lt;</span><span>pb:PhysicsObjectBehavior</span> <span>IsStatic</span><span>=&quot;True&quot;</span><span>/&gt;</span> <br><span>&lt;/</span><span>i:Interaction.Behaviors</span><span>&gt;</span> <br><span>&lt;/</span><span>Rectangle</span><span>&gt;</span></pre>
<br>
</div>
</li><li>Now we'll speed up the startup time by adding in a pre-calculated Point Cache. The Physics Helper Library echoes out the calculated points at runtime. Open the project in Visual Studio, and run with debugging on. In the Output Window, Find the ReadBoundaryCache
 method that was echoed out and Copy the entire method. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image041.jpg" width="523" height="218">
</li><li>Note that the copied code can contain multiple rows of the same points. You can trim out any rows that are duplicated, for example cnvRightFlipper_1 is a copy of cnvRightFlipper, so you can remove that from the list of points.
</li><li>In order to load the list of boundary outlines into the Physics Controller, we need to get a reference to the controller through code. Open up MainPage.xaml.cs and add the highlighted code:
<div id="codeSnippetWrapper">
<pre id="codeSnippet"><span>public</span> <span>partial</span> <span>class</span> MainPage : UserControl <br>{ <br>    PhysicsControllerMain _physicsController; <br>    <span>public</span> MainPage() <br>    { <br>        <span>// Required to initialize variables </span><br>        InitializeComponent(); <br>        <span>this</span>.Loaded &#43;= <span>new</span> RoutedEventHandler(MainPage_Loaded); <br>    } <br>    <span>void</span> MainPage_Loaded(<span>object</span> sender, RoutedEventArgs e) <br>    { <br>        _physicsController = LayoutRoot.GetValue( PhysicsControllerMain.PhysicsControllerProperty) <span>as</span> PhysicsControllerMain; <br>        BoundaryCache.ReadBoundaryCache(_physicsController); <br>    } <br>}</pre>
<br>
</div>
</li><li>Run the project and test the performance. Note that items that have a tint applied to them (Red, Blue, etc.) are NOT being cached and GPU accelerated.
</li></ol>
<h3><a title="_Toc237838544" name="_Toc237838544"></a>Scoring</h3>
<p>In this section, we'll embellish our game with a Score.</p>
<ol>
<li>We'll create a Canvas that overlays our main Canvas to contain a High Score TextBlock. This is so that the Score TextBlock will not scroll with the rest of the Playfield. Open MainPage.xaml and the select LayoutRoot in the Objects and Timeline Panel. Right-click
 LayoutRoot and select Group Into/Canvas. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image043.jpg" width="227" height="200">
</li><li>Add a new StackPanel into this outside Canvas that contains two TextBlock aligned Horizontally. The first TextBlock should contain the Text “Score:” and the second TextBlock should contain the Text “0”. Set the Font Size to a larger value, around 12 pt.
 Position the TextBlock at the Top, Left portion of the Canvas. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image044.jpg" width="367" height="273">
</li><li>Next we'll handle the Collision event for the Physics Controller so we can add to the score. Open MainPage.xaml.cs and add in a Property wrapper for the current&nbsp; score:
<div id="codeSnippetWrapper">
<pre id="codeSnippet"><span>public</span> <span>int</span> Score <br>{ <br>    get <br>    { <br>        <span>return</span> Convert.ToInt32(txtScore.Text); <br>    } <br>    set <br>    { <br>        txtScore.Text = <span>value</span>.ToString(); <br>    } <br>}</pre>
<br>
</div>
</li><li>Handle the Collision event for the Physics Controller and increment the Score.
<div id="codeSnippetWrapper">
<pre id="codeSnippet"><span>void</span> MainPage_Loaded(<span>object</span> sender, RoutedEventArgs e) <br>{ <br>    _physicsController = LayoutRoot.GetValue(PhysicsControllerMain.PhysicsControllerProperty) <span>as</span> PhysicsControllerMain; <br>    BoundaryCache.ReadBoundaryCache(_physicsController); <br>        _physicsController.Collision &#43;= <span>new</span> PhysicsControllerMain.CollisionHandler(_physicsController_Collision); <br>} <br><br><span>void</span> _physicsController_Collision(<span>string</span> sprite1, <span>string</span> sprite2) <br>{ <br>    <span>if</span> (sprite1 == &quot;ellBall<span>&quot; &amp;&amp; sprite2.StartsWith(&quot;ellKicker&quot;</span>)) <br>        Score &#43;= 10; <br>}</pre>
<br>
</div>
</li></ol>
<h3><a title="_Toc237838545" name="_Toc237838545"></a>Tracking Lives</h3>
<p>When the ball collides with the “rectPlatform” obstacle at the bottom, the ball has been lost and we should launch a new ball.
</p>
<ol>
<li>Add a new ChildWindow to the project named “LostTheBall.xaml”. <br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image047.jpg" width="269" height="292">
</li><li>Set the “Cancel” button's Visibility to Collapsed. </li><li>Add a TextBlock and set its Text to a message for the user stating the ball was lost.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image048.jpg" width="320" height="239">
</li><li>Add code in MainPage.xaml.cs to display the dialog and reset the ball. <br>
LostTheBall _lostTheBall;
<div id="codeSnippetWrapper">
<pre id="codeSnippet"><span>void</span> _physicsController_Collision(<span>string</span> sprite1, <span>string</span> sprite2) <br>{ <br>    <span>if</span> (sprite1 == <span>&quot;ellBall&quot;</span> &amp;&amp; sprite2.StartsWith(<span>&quot;cnvKicker&quot;</span>)) <br>    { <br>        Score &#43;= 10; <br>    } <br><br>    <span>if</span> (_lostTheBall == <span>null</span> &amp;&amp;ampsprite1 == <span>&quot;ellBall&quot;</span> &amp;&amp; sprite2 == <span>&quot;rectPlatform&quot;</span>) <br>    { <br>        _lostTheBall = <span>new</span> LostTheBall(); <br>        _lostTheBall.Closed &#43;= <span>new</span> EventHandler(dialog_Closed); <br>        _lostTheBall.Show(); <br>    } <br>} <br><br><span>void</span> dialog_Closed(<span>object</span> sender, EventArgs e) <br>{ <br>    _lostTheBall = <span>null</span>; <br>    PhysicsSprite ball = _physicsController.PhysicsObjects[<span>&quot;ellBall&quot;</span>]; <br>    ball.BodyObject.Position = <span>new</span> Vector2(460, 430); <br>    }</pre>
<br>
</div>
</li></ol>
<h3><a title="_Toc237838546" name="_Toc237838546"></a>Adding Sound Effects</h3>
<p>We can easily add buffered sound effects using the PhysicsSoundBehavior.</p>
<ol>
<li>In Visual Studio, Import two sound files into the project, score.wma and click.wma. Set their Build Action to Content.
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image050.jpg" width="220" height="315">
</li><li>Open MainPage.xaml in Expression Blend. Drag a PhysicsSoundBehavior to the LayoutRoot Canvas. Set the TriggerType to PhysicsCollisionTrigger and set the following properties:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image051.png" width="268" height="288">
</li><li>Drag another PhysicsSoundBehavior to the LayoutRoot Canvas. Set the TriggerType to PhysicsCollisionTrigger and set the following properties:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image052.png" width="265" height="263">
</li><li>Drag another PhysicsSoundBehavior to the LayoutRoot Canvas. Set the TriggerType to PhysicsCollisionTrigger and set the following properties:
<br>
<img border="0" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/9896181/image053.png" width="267" height="263">
</li><li>Run the project. </li></ol>
<h3>About the Author</h3>
<p>Andy Beaulieu is a software developer and trainer who is well versed in many Microsoft technologies including Silverlight, ASP.NET, ADO.NET and WindowsForms.
<a href="http://www.andybeaulieu.com/">Visit Andy's Blog</a> for more fun and games with Silverlight.</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Andy-Beaulieu/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:82fcceec17384a9fb98c9e7600caa7c2">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-Physics</comments>
      <itunes:summary>
In this tutorial, we&#39;ll create a Silverlight pinball game using Behaviors,
a new addition to Expression Blend 3 &amp;amp; Silverlight that allows you to create interactivity with little or no coding.
 
Below you&#39;ll find a video and step-by-step walkthrough.  

Videos:

Part 1
Part 2
Part 3
Part 4
Part 5
Part 6
Part 7a
Part 7b
Part 8
Part 9
Part 10
Setup and Prerequisites
First you have to setup Physics Helper controls into Expression Blend. Follow these steps: 

Download the Physics Helper ZIP file from 
http://physicshelper.codeplex.com/Release/ProjectReleases.aspx Extract the ZIP file contents and dump them into a folder. Run install.bat. (Note: this copies a few required assemblies to a folder in Blend 3.)



Getting Started &amp;amp; Making the Ball
Next, you create the controller and the pinball. Here&#39;s how. 

Open Expression Blend 3 and create a new “Silverlight 3 Application &amp;#43; Website” named PinballGame.


Change your default layout container to a Canvas. You can do this in the Objects and Timeline panel by right-clicking LayoutRoot and selecting Change Layout Type/Canvas. Canvas layout containers are better for games because they allow for positioning of
 elements at absolute (x,y) coordinates. 

Give the application a bigger default size. Select the UserControl element in the Objects and Timeline panel. Then, in the Properties panel, change the Width to 800 and the Height to 600.


Add a Physics Controller Behavior to our main game Canvas. From the Asset Panel, find the PhysicsController Behavior and drag it to the Objects and Timeline Panel. Then, drop it on the LayoutRoot Canvas.




Change a few of the PhysicsController&#39;s properties, to make it easier to use. In the Objects and Timeline Panel, select the PhysicsControllerBehavior assigned to LayoutRoot. Then, set the highlighted properties as follows in the Properties Window:

1.)&amp;nbsp; Decrease the vertical gravity to 250 
2.)&amp;nbsp; Increase the iterations to 200. This will help with collision detection in</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-Physics</link>
      <pubDate>Mon, 30 Nov 2009 19:20:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-Physics</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/9896181_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/9896181_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Andy Beaulieu </dc:creator>
      <itunes:author>Andy Beaulieu </itunes:author>
      <slash:comments>11</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Creating-a-Pinball-Game-in-Silverlight-Using-the-Physics-Helper-Library--Farseer-Physics/RSS</wfw:commentRss>
      <category>Gaming</category>
      <category>Silverlight</category>
    </item>    
</channel>
</rss>