<?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.Nick-Gravelyn/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.Nick-Gravelyn/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.Nick-Gravelyn/Posts</link>
    <language>en</language>
    <pubDate>Tue, 21 May 2013 15:55:29 GMT</pubDate>
    <lastBuildDate>Tue, 21 May 2013 15:55:29 GMT</lastBuildDate>
    <generator>Rev9</generator>
    <c9:totalResults>1</c9:totalResults>
    <c9:pageCount>1</c9:pageCount>
    <c9:pageSize>25</c9:pageSize>
  <item>
      <title>Sammy The Snake: An XNA game for the Zune</title>
      <description><![CDATA[
<p><strong>Nick Gravelyn</strong>&nbsp;- <a href="http://www.nickgravelyn.com/">http://www.nickgravelyn.com/</a></p>
<p><b><b>Download: </b><a href="http://codeplex.com/sammythesnake">http://codeplex.com/sammythesnake</a>
<br>
</b><b>Software: </b><a href="http://msdn.com/express/">Visual C# Express Editions</a>,
<a href="http://creators.xna.com/en-US/downloads">XNA Game Studios 3.0</a><b> <br>
Difficulty: </b>Intermediate <br>
<b>Time Required:</b> 8 hours <br>
<b>Cost: </b>Free</p>
<p>Artwork courtesy of George Clingerman of <a href="http://www.xnadevelopment.com/">
XNADevelopment.com</a> <br>
<strong>Side note: </strong>XNA is c# only</p>
<p>In the exciting world of XNA Game Studio, the new big thing is the XNA Game Studio 3.0 Beta. This beta allows developers to glimpse what will be coming with the full release of XNA Game Studio 3.0. One of the largest new features coming with XNA Game Studio
 3.0 is the new ability to create games for Microsoft's Zune media device. What we're going to cover today is how to create a full game for the Zune, specifically a clone of the classic “Snake” game.</p>
<p>To begin you need to make sure you are set up to start working on Zune games. For all the details and instructions you will need for this step, please visit
<a href="http://creators.xna.com/en-us/3.0beta_mainpage">http://creators.xna.com/en-us/3.0beta_mainpage</a>. Once you have read and completed steps one and two, continue on with this tutorial.</p>
<p>Welcome back! Now that you're all set up with XNA Game Studio 3.0 Beta, we can start working on our game. Since we want to test our game as we go forward, we're actually going to create the game as a Windows game first and then simply convert it to be a
 Zune project when we are finished. First open up Visual Studio 2008 or Visual C# 2008 Express and create a new Windows project. Let's call it “SammyTheSnake”. Choose the location to save the project and hit Ok.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image8.png"><img border="0" alt="image" align="right" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image8_thumb.png" width="269" height="236"></a>Now that we have the project created
 let's start out first by adding in the content for our game. George Clingerman of
<a href="http://www.xnadevelopment.com/">XNADevelopment.com</a> was nice enough to create some pretty graphics for this tutorial so those are the ones we are going to add to the project. In Visual Studio you will have a panel called the
<i>Solution Explorer</i> which will show you all of the files in your project. In that window you want to find the
<i>Content</i> node of your project. Right click on the <i>Content</i> node and choose Add-&gt;New Folder. Name this new folder “Fonts”. Then add a second folder called “Sprites”. At this point your
<i>Solution Explorer</i> should look like what is to your right:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image11.png"><img border="0" alt="image" align="right" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image11_thumb.png" width="212" height="276"></a>Let's continue by adding our content
 files. The easiest way to add the sprites to our project is to simply drag and drop them in from the folder. Another method is to right click on the “Sprites” folder, select Add-&gt;Existing Item. Then you can navigate to the directory where the graphics are,
 select them, and click Ok. When completed you will see all five images are copied into the Sprites directory:</p>
<p>Next we'll create the three fonts that we will be using for the game. To create a font, right click on the “Fonts” folder and select Add-&gt;New Item. In the pop up window you will see an item called a “Sprite Font”. Select that item, name your file “MiniFont.spritefont”,
 and then press Ok. When created it will open up in Visual Studio. The .spritefont file is simply an XML document describing which font you want to use. For our purposes there are only two nodes we need to change. First find the node that looks like this:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">FontName</span><span class="kwrd">&gt;</span>MiniFont<span class="kwrd">&lt;/</span><span class="html">FontName</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>
<p>The <i>FontName</i> node specifies which font we wish to use. Let's change our font to Arial:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">FontName</span><span class="kwrd">&gt;</span>Arial<span class="kwrd">&lt;/</span><span class="html">FontName</span><span class="kwrd">&gt;</span></pre>
<p>Next we need to change the size of the font. Let's find the Size node which, by default, is set to 14:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Size</span><span class="kwrd">&gt;</span>14<span class="kwrd">&lt;/</span><span class="html">Size</span><span class="kwrd">&gt;</span></pre>
<p>And let's change our font to size 10:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Size</span><span class="kwrd">&gt;</span>10<span class="kwrd">&lt;/</span><span class="html">Size</span><span class="kwrd">&gt;</span></pre>
<p>Now that you know how to create fonts, create two more fonts: “MediumFont.spritefont” and “TitleFont.spritefont”. Both fonts should use the Arial font. MediumFont should be size 14 (the default value) and TitleFont should be size 18.</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image.png"><img border="0" alt="image" align="right" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb.png" width="271" height="406"></a>Now you have all the content our game needs.
 Let's take a look at the <i>Solution Explorer</i> one last time to make sure we have all the files in the correct locations:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image.png"></a></p>
<p>Now that all of the content is in place, we can begin working on the game. Let's start writing that code!</p>
<p>To begin we want to make sure our Windows game looks just like the Zune version will. Since the Zune screen has a resolution of 240 pixels by 320 pixels, we want to make our Windows game run in a window set at 240x320. To do this we just need to add two
 lines of code to our Game1 class's constructor:</p>
<pre class="csharpcode"><span class="kwrd">public</span> Game1()
{
    graphics = <span class="kwrd">new</span> GraphicsDeviceManager(<span class="kwrd">this</span>);
    Content.RootDirectory = <span class="str">&quot;Content&quot;</span>;

    graphics.PreferredBackBufferWidth = 240;
    graphics.PreferredBackBufferHeight = 320;
}</pre>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_3.png"><img title="image" border="0" alt="image" align="right" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_3.png" width="347" height="234"></a>The next thing to consider
 is our game's flow. Since we are making a simple game, we are only ever going to have three states in which the game can be in as illustrated by this diagram:</p>
<p>From the diagram we see that our game will have a title screen, some game play, and a game over screen. The arrows represent the changes in game state. From the title screen we can only progress to the in-game screen. From the in-game screen we can either
 quit, going back to the title screen, or we can finish the game and move to the game over screen. From the game over screen we then return to the title screen and the process repeats until the user quits.</p>
<p>Now that we have an idea of how our game will work we will start by creating the framework that will manage our game's state and make sure that we are executing the appropriate code based on the state of the game. First we'll create a new enumeration type
 to represent the three states of our game. In the Game1.cs file right above the declaration for the Game class, add this new enumeration:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">enum</span> GameState
{
    Title,
    InGame,
    GameOver
}</pre>
<p>Now in the actual Game1 class, we need to add a variable to hold the game's state:</p>
<pre class="csharpcode"><span class="kwrd">private</span> GameState state = GameState.Title;</pre>
<p>Now we need to create some new methods which will be used to handle updating and drawing our various states. First let's add three new methods to our Game1 class:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateTitleScreen()
{ }

<span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{ }

<span class="kwrd">private</span> <span class="kwrd">void</span> UpdateGameOver()
{ }</pre>
<p>From the names you can probably see that we have one for each of our three game states. Our UpdateInGame method takes in the GameTime as a parameter because it is used for moving our snake around. The other two game states don't need that value, so they
 have no parameters. Now let's make some changes to the Update method to handle calling each of these methods based on the state of our game:</p>
<pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Update(GameTime gameTime)
{
    <span class="kwrd">if</span> (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        <span class="kwrd">this</span>.Exit();

    <span class="kwrd">if</span> (state == GameState.Title)
        UpdateTitleScreen();
    <span class="kwrd">else</span> <span class="kwrd">if</span> (state == GameState.InGame)
        UpdateInGame(gameTime);
    <span class="kwrd">else</span> <span class="kwrd">if</span> (state == GameState.GameOver)
        UpdateGameOver();

    <span class="kwrd">base</span>.Update(gameTime);
}</pre>
<p>Now we'll repeat those steps to make three methods for rendering each state and updating the Draw method to call each of them as appropriate. While we're at it, we're also going to change the background from the default of CornflowerBlue to Gray to make
 it a little easier on the eyes with the white text we're going to add later:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawTitleScreen()
{ }

<span class="kwrd">private</span> <span class="kwrd">void</span> DrawInGame()
{ }

<span class="kwrd">private</span> <span class="kwrd">void</span> DrawGameOver()
{ }

<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Draw(GameTime gameTime)
{
    graphics.GraphicsDevice.Clear(Color.Gray);

    <span class="kwrd">if</span> (state == GameState.Title)
        DrawTitleScreen();
    <span class="kwrd">else</span> <span class="kwrd">if</span> (state == GameState.InGame)
        DrawInGame();
    <span class="kwrd">else</span> <span class="kwrd">if</span> (state == GameState.GameOver)
        DrawGameOver();

    <span class="kwrd">base</span>.Draw(gameTime);
}</pre>
<p>With that our game now has a fully functioning state system. Of course our game only ever has one state since we don't currently change it, and none of the game states do anything, but the functionality is there. Let's move on to create the code that will
 power the title screen.</p>
<p>First we need to add a few strings to our game which will be used on the title screen. Towards the top of your Game1 class, add these string constants:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> gameTitle = <span class="str">&quot;Sammy the Snake!&quot;</span>;
<span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> playInstructions = <span class="str">&quot;Press Play to Begin&quot;</span>;
<span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> quitInsructions = <span class="str">&quot;Press Back to Quit&quot;</span>;</pre>
<p>Now we need to add a few variables to the Game1 class to hold our fonts which we'll be using to render these strings:</p>
<pre class="csharpcode"><span class="kwrd">private</span> SpriteFont titleFont;
<span class="kwrd">private</span> SpriteFont mediumFont;
<span class="kwrd">private</span> SpriteFont miniFont;</pre>
<p>Next we'll go to our <i>LoadContent</i> method and add in the code that will load those .spritefont files we created earlier and store them in these three variables:</p>
<pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> LoadContent()
{
    spriteBatch = <span class="kwrd">new</span> SpriteBatch(GraphicsDevice);
    titleFont = Content.Load&lt;SpriteFont&gt;(<span class="str">&quot;Fonts/TitleFont&quot;</span>);
    mediumFont = Content.Load&lt;SpriteFont&gt;(<span class="str">&quot;Fonts/MediumFont&quot;</span>);
    miniFont = Content.Load&lt;SpriteFont&gt;(<span class="str">&quot;Fonts/MiniFont&quot;</span>);
}</pre>
<p>After that we also need to add two more variables. The first will store the current frame's input state. The second will store the previous frame's input state. By storing these two values, we will be able to test for when a button gets pressed by verifying
 that the button was down the frame before and is pressed in the current frame.</p>
<pre class="csharpcode"><span class="kwrd">private</span> GamePadState gamePadState;
<span class="kwrd">private</span> GamePadState lastGamePadState;</pre>
<p>Now let's go ahead and make a method which we'll use to test for new button presses for us. We'll take a parameter for which button to test and then check for that button being down in
<i>gamePadState</i> but up in <i>lastGamePadState</i>.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsNewButtonPress(Buttons button)
{
    <span class="kwrd">return</span> (gamePadState.IsButtonDown(button) &amp;&amp; lastGamePadState.IsButtonUp(button));
}</pre>
<p>We'll go ahead, now, and modify the game's Update method to handle updating those GamePadState variables we created above. We get the current state right away and then, at the end of the Update method, we store the current state in our last state variable
 for next frame. We also want to remove the default code in there for exiting when the Back button is pressed because we will handle this in our UpdateTitleScreen method:</p>
<pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Update(GameTime gameTime)
{
    gamePadState = GamePad.GetState(PlayerIndex.One);

    <span class="kwrd">if</span> (state == GameState.Title)
        UpdateTitleScreen();
    <span class="kwrd">else</span> <span class="kwrd">if</span> (state == GameState.InGame)
        UpdateInGame(gameTime);
    <span class="kwrd">else</span> <span class="kwrd">if</span> (state == GameState.GameOver)
        UpdateGameOver();

    lastGamePadState = gamePadState;

    <span class="kwrd">base</span>.Update(gameTime);
}</pre>
<p>With that in place we can move on to filling in our UpdateTitleScreen method. For our simple game, we're going to simply detect the Play/Pause button to start the game and the Back button to exit. These buttons map to the GamePadState's B and Back buttons,
 respectively.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateTitleScreen()
{
    <span class="kwrd">if</span> (IsNewButtonPress(Buttons.Back))
        Exit();

    <span class="kwrd">if</span> (IsNewButtonPress(Buttons.B))
    { }
}</pre>
<p>For now we'll leave the inside of our second if statement empty because we have not implemented the in-game game state at this point.
</p>
<p>Let's now move on to rendering our title screen. We know we are going to have to render three different strings to the screen, so what we're going to do first is write a helper method that will help us write text centered on a point. This will make it easier
 for us so that we don't have to try and calculate where to draw each string individually; we can simply use this one method everywhere we need to draw text.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawText(SpriteFont font, <span class="kwrd">string</span> text, Vector2 position)
{
    Vector2 halfSize = font.MeasureString(text) / 2f;
    position = position - halfSize;

    position.X = (<span class="kwrd">int</span>)position.X;
    position.Y = (<span class="kwrd">int</span>)position.Y;

    spriteBatch.Begin();
    spriteBatch.DrawString(
        font,
        text,
        position, 
        Color.White);
    spriteBatch.End();
}</pre>
<p>This is our first complex code so we're going to take a look at it line by line. The method itself takes in three parameters: the SpriteFont to use for rendering, the text we want to render, and the point at which we want the text centered.</p>
<p>First we use the font's MeasureString method to calculate how big the text will be (in pixels) if rendered with that font. We then divide this size by two and subtract it from the position. Why do we do all of this? In the XNA framework (and most 2D graphics
 APIs) positions of objects are specified using the top-left corner of the object. So by getting half of the size of the object and offsetting the position by it, we are able to set the center point and know that the text will be positioned properly.
</p>
<p>Once we have offset the position, we then cast each of the components to integers. We do this to avoid unnecessary blurring of our text. Since all text is rendered as whole pixels (because there's no such thing as a fractional pixel), having a position that
 is not an integer value will cause the device to try and filter the text to get it to look right, or simply render it incorrectly. So when drawing in 2D, it's always best to cast your positions to integers before using them to render.</p>
<p>Lastly our method uses a simple SpriteBatch routine to draw the text at the desired position using the desired font using the White color.</p>
<p>With that helper method out of the way, we can add three simple lines to the DrawTitleScreen method to draw our title screen:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawTitleScreen()
{
    DrawText(titleFont, gameTitle, <span class="kwrd">new</span> Vector2(120f, 25f));
    DrawText(mediumFont, playInstructions, <span class="kwrd">new</span> Vector2(120f, 200f));
    DrawText(mediumFont, quitInsructions, <span class="kwrd">new</span> Vector2(120f, 225f));
}</pre>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_4.png"><img title="image" border="0" alt="image" align="right" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_4.png" width="250" height="349"></a>Now if you run your game,
 you should see a window like this:</p>
<p>If you have an Xbox 360 controller hooked to your computer, you could press the Back button to quit, but otherwise you can simply use the close button of the window to exit the game.</p>
<p>From this point we're going to start working on the gameplay. I am only going to be showing GamePad controls for this (since we are targeting the Zune), so if you don't have an Xbox 360 controller connected to your PC, you are either going to have to deploy
 the game to the Zune each time you want to test or implement keyboard controls. You can skip down to the end of this tutorial where we convert the project to be a Zune game or use other references for that process.</p>
<p>Next we need to add in the game play code itself. Our game is rather simple. At any given time our game will have a single orange on screen, the snake, and a display of the number of oranges consumed. We're going to start with the orange, then handle the
 snake, and finally the scoring system.</p>
<p>To begin any of our rendering we need to get setup with a system for easily rendering our game. Since the whole game is grid based, we are going to make a class whose only purpose is to handle rendering a sprite at a given point using grid coordinates. We'll
 start by creating a new static class called Grid:</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> Grid
{ }</pre>
<p>Next we will define a few constants. The first sets the size of each grid cell. The second is one half of the grid cell size. We will be using a 16x16 pixel area for our grids. This number has been chosen because both 240 and 320 are even divisible by it,
 thus giving us a perfect grid for the resolution. We then have values to represent the largest row and column values in our grid:</p>
<p>Next we'll define a method called <i>PointToVector2</i>. The whole purpose of this method will be to take a
<i>Point</i> value representing cell coordinates and converting them into the pixel coordinates needed to render a sprite. To do this we simply multiply the point's coordinates by the scale and add in the half scale value. We add the half scale so that the
 resulting Vector2 is at the center of the cell. As I said before you always want to convert to integer based coordinates, but since the Point only contains integer values, and all our constants are integers, we don't need to explicitly cast the values to ints:
</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> Vector2 PointToVector2(Point p)
{
    <span class="kwrd">return</span> <span class="kwrd">new</span> Vector2(
        p.X * Scale &#43; HalfScale,
        p.Y * Scale &#43; HalfScale);
}</pre>
<p>The only other method we're going to add to our Grid class is the <i>DrawSprite</i> method.
<i>DrawSprite</i> will handle rendering a given texture at a specific point with a given angle of rotation.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> DrawSprite(
    SpriteBatch spriteBatch, 
    Texture2D texture, 
    Point point, 
    <span class="kwrd">float</span> rotation)
{
    <span class="kwrd">float</span> spriteSize = (<span class="kwrd">float</span>)Math.Max(texture.Width, texture.Height);
    Vector2 origin = <span class="kwrd">new</span> Vector2(texture.Width / 2f, texture.Height / 2f);
    spriteBatch.Draw(
        texture,
        PointToVector2(point),
        <span class="kwrd">null</span>,
        Color.White,
        rotation,
        origin,
        Scale / spriteSize,
        SpriteEffects.None,
        0);
} </pre>
<p>Let's walk through what this method is doing so that we're all clear as to how it works. We first calculate the largest dimension of the texture given to us. We do this so we know how much to scale the sprite to make it fit into a single cell of the grid.
 Then we compute the origin we'll use for rendering. I'll explain the origin below as we go through the parameters of our Draw call.</p>
<p>Next we make a large call to <i>spriteBatch.Draw</i>, where we have lots of variables going in. Let's just explain each one briefly:</p>
<ul>
<li><b>texture </b>– This represents the texture object we want to draw. </li><li><b>PointToVector2(point)</b> – Here we leverage the <i>Grid.PointToVector2 </i>
method we wrote before to convert our grid coordinate to pixel coordinates. </li><li><b>null</b> – This parameter represents the source rectangle used to render. The source rectangle is used to specify a subsection of the area of the texture to use for rendering. Since we want to draw the entire texture, we use null here.
</li><li><b>Color</b>.<b>White</b> – Using white here simply causes the sprite batch to render the texture with no color modifications.
</li><li><b>rotation – </b>The rotation (specified in radians) instructs the sprite batch to rotate the texture as desired.
</li><li><b>origin</b> – Here we use the origin value we calculated earlier. This value specifies how to place, rotate, and scale the texture. What we've done is specified the pixel value of the center of our sprites. The sprites created for us are 32x32 pixels
 making their center point 16x16. Rather than hard coding in that value, we simply divide the width and height by two. By using the center of the texture, our sprite will be positioned such that the second parameter tells the sprite batch where we want the
 center of our texture. It also means that the sprite will be rotated and scaled about its center.
</li><li><b>Scale / spriteSize</b> – Here we use our grid's Scale value and divide it by the size of the sprite. This will cause sprite batch to scale the texture so that it fits completely within a single grid cell.
</li><li><b>SpriteEffects</b>.<b>None</b> – SpriteEffects are used for flipping the texture over the horizontal axis, vertical axis, or both. We don't want to flip the texture, so we specify none.
</li><li><b>0 </b>– The last parameter is the layer depth. This can be used to specify the order in which sprites drawn in the same batch are layered when rendered with zero being the topmost drawn sprites and one being the bottom most drawn sprites. We just use
 zero here because we will be handling the rendering order by hand so that sprites we want lower will be drawn first. In addition we will rarely ever have overlapping sprites, so ordering is hardly an issue for us.
</li></ul>
<p>With the Grid class complete, we can move on to create the Orange class:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Orange
{
    Position = <span class="kwrd">new</span> Point(Grid.MaxColumn / 2, Grid.MaxRow / 2);
}</pre>
<p>Now let's think about what data our orange will need. The two obvious ones are a position and the texture. But we also need a third value: a random number generator which will be used to place the orange in a random place on the screen:</p>
<pre class="csharpcode"><span class="kwrd">public</span> Point Position;
<span class="kwrd">private</span> Texture2D texture;
<span class="kwrd">private</span> Random rand = <span class="kwrd">new</span> Random();</pre>
<p>Now we're going to add three short methods to our Orange class that will handle just about all the functionality we will need for this game:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Reposition()
{
    Position = <span class="kwrd">new</span> Point(rand.Next(Grid.MaxColumn), rand.Next(Grid.MaxRow));
}

<span class="kwrd">public</span> <span class="kwrd">void</span> Load(ContentManager content)
{
    texture = content.Load&lt;Texture2D&gt;(<span class="str">&quot;Sprites/Orange&quot;</span>);
}

<span class="kwrd">public</span> <span class="kwrd">void</span> Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Begin();
    Grid.DrawSprite(spriteBatch, texture, Position, 0f);
    spriteBatch.End();
}</pre>
<p>Our <i>Reposition</i> method is what will generate a random location in our grid at which the orange will be placed. The
<i>Load</i> method requires a <i>ContentManager</i> instance and handles loading our orange texture from file. Lastly the
<i>Draw</i> method takes in a <i>SpriteBatch</i> instance and handles rendering the orange using our Grid class's
<i>DrawSprite</i> method.</p>
<p>Before continuing on, let's give this class a try to make sure it works like we think it should. First let's head to the Game1 class and add a new variable for the orange. We'll also set our starting game state to the InGame playing state:</p>
<pre class="csharpcode"><span class="kwrd">private</span> Orange orange = <span class="kwrd">new</span> Orange();
<span class="kwrd">private</span> GameState state = GameState.InGame;</pre>
<p>Then we need to make sure call the orange's <i>Load</i> method in our <i>LoadContent</i> method:</p>
<pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> LoadContent()
{
    spriteBatch = <span class="kwrd">new</span> SpriteBatch(GraphicsDevice);
    titleFont = Content.Load&lt;SpriteFont&gt;(<span class="str">&quot;Fonts/TitleFont&quot;</span>);
    mediumFont = Content.Load&lt;SpriteFont&gt;(<span class="str">&quot;Fonts/MediumFont&quot;</span>);
    miniFont = Content.Load&lt;SpriteFont&gt;(<span class="str">&quot;Fonts/MiniFont&quot;</span>);

    orange.Load(Content);
}</pre>
<p>Next we'll go to our <i>UpdateInGame</i> method and add in some code that will call the orange's
<i>Reposition</i> method every second:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{
    <span class="kwrd">if</span> (gameTime.TotalGameTime.Milliseconds % 1000 == 0)
        orange.Reposition();
}</pre>
<p>Lastly we'll add to the <i>DrawInGame</i> method so that it call's the orange's
<i>Draw </i>method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawInGame()
{
    orange.Draw(spriteBatch);
}</pre>
<p>Build and run the game. You should see the same gray window with a single orange drawn. Every second the orange will move to a new grid location on the screen.
</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_5.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_5.png" width="250" height="349"></a>
</p>
<p>Now we will be creating our Snake class:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> Snake
{ }</pre>
<p>The Snake class is a bit more complex. Logically let's lay out what data the class will need:</p>
<ul>
<li>A list of points for each segment of the body. </li><li>The four textures (head, straight body piece, angled body piece, and tail) with which we will render the snake
</li><li>A value indicating how fast the snake should be moving. </li><li>A value indicating the snake's current direction and the direction he will be moving next.
</li><li>A value indicating whether or not to extend the snake's length the next time it moves.
</li><li>A timer value so that we can control how often the snake moves from grid cell to grid cell.
</li></ul>
<p>A good amount of data for something that seems rather simple. We'll start by creating an enumeration for those direction values we are going to need:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">enum</span> Direction
{
    Up,
    Down,
    Left,
    Right
}</pre>
<p>Next we'll go ahead and add all the variables to our Snake class itself:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">const</span> <span class="kwrd">float</span> MoveSpeed = .2f; 
<span class="kwrd">private</span> <span class="kwrd">float</span> moveTimer;
<span class="kwrd">private</span> Texture2D head, straight, angle, tail;
<span class="kwrd">private</span> List&lt;Point&gt; bodyPoints = <span class="kwrd">new</span> List&lt;Point&gt;();
<span class="kwrd">private</span> Direction currentDirection = Direction.Right;
<span class="kwrd">private</span> Direction nextDirection = Direction.Right;
<span class="kwrd">private</span> <span class="kwrd">bool</span> extending;</pre>
<p>Everything here should be rather self explanatory. The <i>MoveSpeed</i> represents the number of seconds before the snake proceeds to the next grid cell and the
<i>moveTimer</i> will be used to count up to this value. We then have our four textures, a list for the body points, and two values for the current and next direction. Lastly our bool value to tell us whether the snake should extend the next time it moves.</p>
<p>Now we're going to add a new method called <i>Reset </i>which will be called from the Snake's constructor.
<i>Reset</i> is responsible for placing our Snake it its starting position in the game.</p>
<pre class="csharpcode"><span class="kwrd">public</span> Snake()
{
    Reset();
}

<span class="kwrd">public</span> <span class="kwrd">void</span> Reset()
{
    bodyPoints.Clear();

    bodyPoints.Add(<span class="kwrd">new</span> Point(2, 0));
    bodyPoints.Add(<span class="kwrd">new</span> Point(1, 0));
    bodyPoints.Add(<span class="kwrd">new</span> Point(0, 0));

    currentDirection = Direction.Right;
    nextDirection = Direction.Right;
}</pre>
<p>In the <i>Reset</i> method, first we make sure to clear out the list of points for the snake's body. Next we add three points to the body. The first point sets the position of the head, followed by a single body piece, and lastly the tail. To finish we also
 make sure to reset both the current and next direction values to Right so that the snake begins by heading to the right.</p>
<p>Next we'll make a <i>Load</i> method which, like the Orange class, handles loading in the textures needed to render the snake:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Load(ContentManager content)
{
    head = content.Load&lt;Texture2D&gt;(<span class="str">&quot;Sprites/Head&quot;</span>);
    straight = content.Load&lt;Texture2D&gt;(<span class="str">&quot;Sprites/Straight&quot;</span>);
    angle = content.Load&lt;Texture2D&gt;(<span class="str">&quot;Sprites/Angle&quot;</span>);
    tail = content.Load&lt;Texture2D&gt;(<span class="str">&quot;Sprites/Tail&quot;</span>);
}</pre>
<p>Continuing on we're going to implement the rendering for the snake. This is the most complex part of this entire game, but we'll take it one step at a time to make sure each line of code is explained. First let's add the five methods we'll be using:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Begin();

    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 1; i &lt; bodyPoints.Count - 1; i&#43;&#43;)
    {
        DrawBody(
            spriteBatch, 
            bodyPoints[i], 
            bodyPoints[i - 1], 
            bodyPoints[i &#43; 1]);
    }

    DrawTail(spriteBatch);
    DrawHead(spriteBatch);
    spriteBatch.End();
}

<span class="kwrd">private</span> <span class="kwrd">void</span> DrawHead(SpriteBatch spriteBatch) { }
<span class="kwrd">private</span> <span class="kwrd">void</span> DrawTail(SpriteBatch spriteBatch) { }
<span class="kwrd">private</span> <span class="kwrd">bool</span> IsAnglePiece(Point current, Point last, Point next) { }
<span class="kwrd">private</span> <span class="kwrd">void</span> DrawBody(SpriteBatch spriteBatch, Point current, Point last, Point next) { }
<span class="kwrd">private</span> <span class="kwrd">float</span> GetAngleRotation(Point current, Point last, Point next) { }</pre>
<p>We can see that we have broken the rendering up into multiple methods to make the code a bit more organized. We have the main
<i>Draw </i>method which will be used by our Game1 class to handle drawing the snake. The method has a single
<i>SpriteBatch</i> instance for a parameter. </p>
<p>Then we loop through the <i>bodyPoints</i> list starting on the second item and going up to the second to last item. We intentionally do not use the first or last points because those represent the head and tail, respectively.</p>
<p>After we draw the body, we then draw the tail and head. The order in which we call these methods will affect the graphics to a small degree. The important part is drawing the head last. By doing this we ensure that even when the head and a body piece overlap
 (for instance, when the snake runs into itself) the head will be drawn on top of the body part.</p>
<p>Next we'll go ahead and fill in the <i>DrawHead</i> method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawHead(SpriteBatch spriteBatch)
{
    Point headPoint = bodyPoints[0];
    Point nextBody = bodyPoints[1];

    <span class="kwrd">float</span> rotation;
    <span class="kwrd">if</span> (headPoint.Y == nextBody.Y - 1)
    {
        rotation = -MathHelper.PiOver2;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (headPoint.Y == nextBody.Y &#43; 1)
    {
        rotation = MathHelper.PiOver2;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (headPoint.X == nextBody.X - 1)
    {
        rotation = MathHelper.Pi;
    }
    <span class="kwrd">else</span>
    {
        rotation = 0f;
    }

    Grid.DrawSprite(spriteBatch, head, headPoint, rotation);
}</pre>
<p>While this looks really complex, it's rather simply once you look at it. First we get out the position of the head and then the first body point after that. What we then do is compare those points to figure out what angle to use when rendering the head.
 Finally we just use the <i>Grid.DrawSprite</i> method to render the head to the screen.</p>
<p>Now we'll fill in the DrawTail method. This method is almost identical to the DrawHead method so there really is no explanation needed:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawTail(SpriteBatch spriteBatch)
{
    Point tailPoint = bodyPoints[bodyPoints.Count - 1];
    Point lastBody = bodyPoints[bodyPoints.Count - 2];

    <span class="kwrd">float</span> rotation;
    <span class="kwrd">if</span> (tailPoint.Y == lastBody.Y - 1)
    {
        rotation = MathHelper.PiOver2;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (tailPoint.Y == lastBody.Y &#43; 1)
    {
        rotation = -MathHelper.PiOver2;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (tailPoint.X == lastBody.X &#43; 1)
    {
        rotation = MathHelper.Pi;
    }
    <span class="kwrd">else</span>
    {
        rotation = 0f;
    }

    Grid.DrawSprite(spriteBatch, tail, tailPoint, rotation);
}</pre>
<p>We'll tackle the <i>IsAnglePiece</i> method next. This method is used by the <i>
DrawBody</i> method to determine if a given point should be drawn with the angled body piece or the straight body piece. To do this we compare the positions of the current body piece, the previous body piece, and the next body piece to determine if they make
 up a right angle or not:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">bool</span> IsAnglePiece(Point current, Point last, Point next)
{
    <span class="kwrd">return</span> (current.X == last.X &amp;&amp; current.X != next.X &amp;&amp; current.Y != last.Y) ||
           (current.X == next.X &amp;&amp; current.X != last.X &amp;&amp; current.Y != next.Y);
}</pre>
<p>With that completed we can fill in the <i>DrawBody</i> method. This method is also pretty simple:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawBody(SpriteBatch spriteBatch, Point current, Point last, Point next)
{
    <span class="kwrd">if</span> (IsAnglePiece(current, last, next))
    {
        Grid.DrawSprite(
            spriteBatch, 
            angle, 
            current, 
            GetAngleRotation(current, last, next));
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (current.X != last.X)
    {
        Grid.DrawSprite(
            spriteBatch, 
            straight, 
            current, 
            0f);
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (current.Y != last.Y)
    {
        Grid.DrawSprite(
            spriteBatch, 
            straight, 
            current, 
            MathHelper.PiOver2);
    }
}</pre>
<p>First we check to see if the three points comprise and angle. If they do we use the
<i>Grid.DrawSprite</i> method to render the angle texture at the current position. For the angle we utilize the
<i>GetAngleRotation </i>method which we will be filling in later.</p>
<p>If we don't have an angle piece, we then figure out whether the body piece is horizontal or vertical and use that to render the straight body piece with either zero or PiOver2 as the angle.</p>
<p>Finally we come to the <i>GetAngleRotation</i> method. This method takes three Points and determines the angle at which the sprite must be drawn in order to connect the three body pieces. Here's the code for this method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">float</span> GetAngleRotation(Point current, Point last, Point next)
{
    Point negPiOver2 = <span class="kwrd">new</span> Point(next.X &#43; 1, last.Y - 1);
    Point negPiOver22 = <span class="kwrd">new</span> Point(last.X &#43; 1, next.Y - 1);

    Point pi = <span class="kwrd">new</span> Point(next.X - 1, last.Y - 1);
    Point pi2 = <span class="kwrd">new</span> Point(last.X - 1, next.Y - 1);

    Point piOver2 = <span class="kwrd">new</span> Point(next.X - 1, last.Y &#43; 1);
    Point piOver22 = <span class="kwrd">new</span> Point(last.X - 1, next.Y &#43; 1);

    <span class="kwrd">if</span> (current == negPiOver2 || current == negPiOver22)
    {
        <span class="kwrd">return</span> -MathHelper.PiOver2;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (current == pi || current == pi2)
    {
        <span class="kwrd">return</span> MathHelper.Pi;
    }
    <span class="kwrd">else</span> <span class="kwrd">if</span> (current == piOver2 || current == piOver22)
    {
        <span class="kwrd">return</span> MathHelper.PiOver2;
    }
    <span class="kwrd">else</span>
    {
        <span class="kwrd">return</span> 0f;
    }
}</pre>
<p>The method begins by calculating a set of Points. Each pair of points represents one of the combinations that will result in a particular angle. This can take a little bit to wrap your head around, so if you have trouble visualizing it, I'd recommend grabbing
 (or making) some grid paper and drawing the points out so you can see how they all fall into place.</p>
<p>We then go through and compare the current point to each set of our values. If any match up, we return that value. If none match, we don't have any rotation to apply to the sprite.</p>
<p>That completes the snake's rendering system. It was a pretty big hill to take, but with it behind us we can feel good knowing that the rest of the code will be quite a bit simpler. Before we move on, let's head back to the Game1 class to test out our new
 class and make sure it works.</p>
<p>First we'll add a new variable for the snake:</p>
<pre class="csharpcode"><span class="kwrd">private</span> Snake snake = <span class="kwrd">new</span> Snake();</pre>
<p>Next we head to the <i>LoadContent</i> method and make sure we call the snake's
<i>Load</i> method:</p>
<pre class="csharpcode">snake.Load(Content);</pre>
<p>Lastly for this test we'll just add a call to the snake's <i>Draw</i> method in our
<i>DrawInGame</i> method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawInGame()
{
    orange.Draw(spriteBatch);
    snake.Draw(spriteBatch);
}</pre>
<p>Go ahead and run the game now and you should see the little snake in the top-left corner of the screen along with the orange that we added earlier:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_6.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_6.png" width="250" height="349"></a>
</p>
<p>There is already one issue with our game. The orange, as it keeps repositioning, occasionally will position itself underneath the snake. We want to avoid this at all costs. To accomplish this we need to add a new method to the Snake class called
<i>IsBodyOnPoint</i> which will tell us whether a given grid cell is occupied by one of the snake's body parts. To do this we simply leverage the list's
<i>Contains</i> method:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">bool</span> IsBodyOnPoint(Point p)
{
    <span class="kwrd">return</span> bodyPoints.Contains(p);
}</pre>
<p>Next we will modify the Orange class's <i>Reposition </i>method to take in a snake instance and use this to make sure we generate a random point not occupied by the snake:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Reposition(Snake snake)
{
    <span class="kwrd">do</span>
    {
        Position = <span class="kwrd">new</span> Point(rand.Next(Grid.MaxColumn), rand.Next(Grid.MaxRow));
    } <span class="kwrd">while</span> (snake.IsBodyOnPoint(Position));
}</pre>
<p>By using the do-while loop, we ensure that we will run that code at least once. Then if the position is found to be occupied by the snake, the code will continue looping until an unoccupied space has been found.
</p>
<p>Let's go ahead and update our code found in the Game1 <i>UpdateInGame</i> method to match this new method signature:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{
    <span class="kwrd">if</span> (gameTime.TotalGameTime.Milliseconds % 1000 == 0)
        orange.Reposition(snake);
}</pre>
<p>Now if you run the game, you'll notice the orange will never, ever position itself underneath of the snake. We now have enough of the core to begin working on making the snake move around. Let's head to the Snake class and add a few new methods:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Update(GameTime gameTime)
{ }

<span class="kwrd">private</span> <span class="kwrd">void</span> HandleInput()
{ }

<span class="kwrd">private</span> <span class="kwrd">void</span> MoveSnake()
{ }</pre>
<p>These three methods will handle all of our update code for the snake. First we'll start by filling in the main
<i>Update</i> method:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Update(GameTime gameTime)
{
    HandleInput();

    moveTimer &#43;= (<span class="kwrd">float</span>)gameTime.ElapsedGameTime.TotalSeconds;

    <span class="kwrd">if</span> (moveTimer &lt; MoveSpeed)
    {
        <span class="kwrd">return</span>;
    }

    moveTimer = 0f;
    currentDirection = nextDirection;
    MoveSnake();
}</pre>
<p>The first thing our method does is call the <i>HandleInput. </i>Next we add the elapsed time in seconds to our
<i>moveTimer</i> variable. Then we see if the <i>moveTimer</i> is less than the <i>
MoveSpeed</i> value. If <i>moveTimer</i> is less than the <i>MoveSpeed</i> we know that enough time has not elapsed so we call ‘return' to exit out of our update method. If
<i>moveTimer</i> has exceeded the <i>MoveSpeed</i> value, we proceed on with updating. The next thing we do is reset the
<i>moveTimer</i>. Then we assign the <i>nextDirection </i>as our <i>currentDirection</i> and call the
<i>MoveSnake</i> method.</p>
<p>We'll continue by filling in the <i>HandleInput</i> method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> HandleInput()
{
    GamePadState gps = GamePad.GetState(PlayerIndex.One);

    <span class="kwrd">if</span> (gps.IsButtonDown(Buttons.DPadDown) &amp;&amp; currentDirection != Direction.Up)
    {
        nextDirection = Direction.Down;
    }
    <span class="kwrd">if</span> (gps.IsButtonDown(Buttons.DPadUp) &amp;&amp; currentDirection != Direction.Down)
    {
        nextDirection = Direction.Up;
    }
    <span class="kwrd">if</span> (gps.IsButtonDown(Buttons.DPadLeft) &amp;&amp; currentDirection != Direction.Right)
    {
        nextDirection = Direction.Left;
    }
    <span class="kwrd">if</span> (gps.IsButtonDown(Buttons.DPadRight) &amp;&amp; currentDirection != Direction.Left)
    {
        nextDirection = Direction.Right;
    }
}</pre>
<p>All we are doing here is finding out which DPad direction is down and using that for the next direction. We also check to make sure that the next direction is not the direct opposite of the current direction. Pretty simple.</p>
<p>Next is the <i>MoveSnake</i> method. This method takes care of two things for us. First it handles updating all the body points in the snake to move him around the grid. The second thing it handles is inserting new body pieces as requested. Let's take a
 look at the code:</p>
<pre class="csharpcode"> <span class="kwrd">private</span> <span class="kwrd">void</span> MoveSnake()
{
    Point p1 = bodyPoints[0];
    <span class="kwrd">switch</span> (currentDirection)
    {
        <span class="kwrd">case</span> Direction.Up:
            bodyPoints[0] = <span class="kwrd">new</span> Point(p1.X, p1.Y - 1);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> Direction.Down:
            bodyPoints[0] = <span class="kwrd">new</span> Point(p1.X, p1.Y &#43; 1);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> Direction.Left:
            bodyPoints[0] = <span class="kwrd">new</span> Point(p1.X - 1, p1.Y);
            <span class="kwrd">break</span>;
        <span class="kwrd">case</span> Direction.Right:
            bodyPoints[0] = <span class="kwrd">new</span> Point(p1.X &#43; 1, p1.Y);
            <span class="kwrd">break</span>;
    }
    <span class="kwrd">if</span> (extending)
    {
        bodyPoints.Insert(1, p1);
        extending = <span class="kwrd">false</span>;
        <span class="kwrd">return</span>;
    }
    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 1; i &lt; bodyPoints.Count; i&#43;&#43;)
    {
        Point p2 = bodyPoints[i];
        bodyPoints[i] = p1;
        p1 = p2;
    }
}</pre>
<p>Going through this little by little, what we first do is get the position of the head to store that for the next body part. We then use the
<i>currentDirection</i> value to move the head to the next position it should be at.</p>
<p>Following that we see if we need to add in a new body piece. If we need to, we simply insert the point the head used to be at into the list behind the head and exit the method since we have filled the gap left by moving our head.</p>
<p>If we did not extend, we then loop through all remaining body parts (including the tail) and update them by moving them to position of the body part in front of them.</p>
<p>We'll follow this up by again testing our code to make sure it all works. Head back to the Game1 class and update the
<i>UpdateInGame</i> method to call the snake's <i>Update</i> method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{
    <span class="kwrd">if</span> (gameTime.TotalGameTime.Milliseconds % 1000 == 0)
        orange.Reposition(snake);
    snake.Update(gameTime);
}</pre>
<p>Now when you run the game your snake will take off towards the right. You can now use the DPad of your Xbox 360 controller (or Zune if you have deployed it there) to direct the snake around.</p>
<p>At this point we have all the ground work in place. Let's go ahead and make our gameplay actually goal oriented. First let's increase functionality that lets our snake eat the oranges. For us to do this, we need to be able to see if the snake's head is in
 the same grid cell as the orange. Our orange already has a position value, so we just need to add a method to see if the snake's head is at that position. We'll add the following method now to our Snake class:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">bool</span> IsHeadAtPosition(Point position)
{
    <span class="kwrd">return</span> (bodyPoints[0] == position);
}</pre>
<p>All this method does is compare the first point in our array to the position given and return if the two values are the same. With this in place, let's fix up the
<i>UpdateInGame</i> method to only reposition the orange when the snake eats it:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{
    snake.Update(gameTime);

    <span class="kwrd">if</span> (snake.IsHeadAtPosition(orange.Position))
        orange.Reposition(snake);
}</pre>
<p>Our orange is now updated appropriately so that it only repositions itself if eaten by the snake. However our snake still doesn't actually grow like he should. So we'll add another method to the Snake class that tells our snake to extend itself:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> Extend()
{
    extending = <span class="kwrd">true</span>;
}</pre>
<p>We can now add this to our <i>UpdateInGame </i>method so that when the snake eats the orange, not only does the orange reposition itself, but the snake will also grow the next time it moves:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{
    snake.Update(gameTime);

    <span class="kwrd">if</span> (snake.IsHeadAtPosition(orange.Position))
    {
        orange.Reposition(snake);
        snake.Extend();
    }
}</pre>
<p>Now we're making some progress. We still have a big problem: there's no way to lose. In the original game of Snake you would lose by either crashing into the wall of the window or by making the snake crash into itself. We can address both of these cases
 by adding two methods to the Snake class:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">bool</span> IsLooped()
{
    <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 1; i &lt; bodyPoints.Count; i&#43;&#43;)
        <span class="kwrd">if</span> (IsHeadAtPosition(bodyPoints[i]))
            <span class="kwrd">return</span> <span class="kwrd">true</span>;

    <span class="kwrd">return</span> <span class="kwrd">false</span>;
}

<span class="kwrd">public</span> <span class="kwrd">bool</span> IsHeadOffScreen()
{
    Point h = bodyPoints[0];
    <span class="kwrd">return</span> (h.X &lt; 0 || h.Y &lt; 0 || h.X &gt;= Grid.MaxColumn || h.Y &gt;= Grid.MaxRow);
}</pre>
<p>The first method, <i>IsLooped</i>, tests all body pieces against the head to see if the head is on the same space as them. The second method,
<i>IsHeadOffScreen</i>, checks to see if the head is out of the valid grid locations. Let's head back to the
<i>UpdateInGame</i> method and add in these tests:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{
    snake.Update(gameTime);

    <span class="kwrd">if</span> (snake.IsHeadAtPosition(orange.Position))
    {
        orange.Reposition(snake);
        snake.Extend();
    }

    <span class="kwrd">if</span> (snake.IsLooped())
        state = GameState.GameOver;

    <span class="kwrd">if</span> (snake.IsHeadOffScreen())
        state = GameState.GameOver;
}</pre>
<p>We now have the ability to lose the game which brings us very close to having a completed game. Let's now add some code to the start of the
<i>UpdateInGame</i> method to let the user exit back to the title screen by pressing the Back button.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateInGame(GameTime gameTime)
{
    <span class="kwrd">if</span> (IsNewButtonPress(Buttons.Back))
        state = GameState.Title;

    snake.Update(gameTime);

    <span class="kwrd">if</span> (snake.IsHeadAtPosition(orange.Position))
    {
        orange.Reposition(snake);
        snake.Extend();
    }

    <span class="kwrd">if</span> (snake.IsLooped())
        state = GameState.GameOver;

    <span class="kwrd">if</span> (snake.IsHeadOffScreen())
        state = GameState.GameOver;
}</pre>
<p>We are just about done with all of the code for the <i>UpdateInGame</i> method. Let's finish up by adding the ability to count the oranges that have been eaten. First we need to add a new integer variable to the Game1 class to hold the score:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">int</span> score;</pre>
<p>We now just increment the score every time the snake eats and orange. Inside of our
<i>UpdateInGame</i> method, update the code for the snake eating the orange to look like this:</p>
<pre class="csharpcode"><span class="kwrd">if</span> (snake.IsHeadAtPosition(orange.Position))
{
    orange.Reposition(snake);
    snake.Extend();
    score&#43;&#43;;
}</pre>
<p>We can now focus on finishing the drawing for the <i>DrawInGame</i>. All we need to do is display the current score on the screen. We'll start by adding a new string constant to the Game1 class:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> scoreFormat = <span class="str">&quot;Oranges Eaten: {0}&quot;</span>;</pre>
<p>The “{0}” in there, if you haven't worked with format strings before, is a placeholder that specifies where we want to insert our score.</p>
<p>Now let's head down to the <i>DrawInGame</i> method and add in the code to draw the score to our screen:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> DrawInGame()
{
    orange.Draw(spriteBatch);
    snake.Draw(spriteBatch);
    DrawText(miniFont, <span class="kwrd">string</span>.Format(scoreFormat, score), <span class="kwrd">new</span> Vector2(120f, 5f));
}</pre>
<p>We can run the game and now see how well we're doing:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_7.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_7.png" width="250" height="349"></a>
</p>
<p>&nbsp;</p>
<p>We can now quickly fill in both the <i>UpdateGameOver</i> and <i>DrawGameOver</i> screens to simply display the results of the game and await input to return to the title screen. First we'll add two more string constants to the game:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> gameOver = <span class="str">&quot;Game Over!&quot;</span>;
<span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> gameOverInstructions = <span class="str">&quot;Press Play to Continue&quot;</span>;</pre>
<p>And then we can fill in the code for our two methods:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateGameOver()
{
    <span class="kwrd">if</span> (IsNewButtonPress(Buttons.B))
        state = GameState.Title;
}

<span class="kwrd">private</span> <span class="kwrd">void</span> DrawGameOver()
{
    orange.Draw(spriteBatch);
    snake.Draw(spriteBatch);

    DrawText(titleFont, gameOver, <span class="kwrd">new</span> Vector2(120f, 25f));
    DrawText(mediumFont, <span class="kwrd">string</span>.Format(scoreFormat, score), <span class="kwrd">new</span> Vector2(120f, 200f));
    DrawText(mediumFont, gameOverInstructions, <span class="kwrd">new</span> Vector2(120f, 225f));
}</pre>
<p>You can see that we not only draw text in our state, but we also draw the orange and snake. This lets the user see where things were when the game ended and is a nice touch to add to the game.</p>
<p>The last thing we add is the code to make sure that the <i>UpdateTitleScreen</i> method makes sure to reset the snake, orange, and score when the user starts a new game:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> UpdateTitleScreen()
{
    <span class="kwrd">if</span> (IsNewButtonPress(Buttons.Back))
        Exit();

    <span class="kwrd">if</span> (IsNewButtonPress(Buttons.B))
    {
        snake.Reset();
        score = 0;
        orange.Reposition(snake);
        state = GameState.InGame;
    }
}</pre>
<p>And lastly we make sure the initial state is set to the title screen:</p>
<pre class="csharpcode"><span class="kwrd">private</span> GameState state = GameState.Title;</pre>
<p>With that your game is complete! You now have a fully functional Snake clone. “But what about the Zune?”, you ask. Let's take care of that right now.</p>
<p>XNA Game Studio has always aimed to be a cross-platform tool and the new Zune support is no exception. Getting our project onto a Zune is literally just a matter of clicks. First right click on your game project in the
<i>Solution Explorer</i> and choose the <i>Create Copy of Project for Zune</i> menu item. When completed you will have a complete duplicate project that targets the Zune platform. The
<i>Solution Explorer</i> should now look like this:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_8.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_8.png" width="271" height="428"></a>
</p>
<p>Next we need to build and deploy the game to the Zune. This process is also rather simple. If you went through the tutorial on the download instructions page, this will already be familiar to you. If not, we'll cover the whole process here.
</p>
<p>Head up to the <i>Tools</i> menu and choose the <i>Launch XNA Game Studio Device Center</i> option. You will be presented with a window that looks like this:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_9.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_9.png" width="500" height="329"></a>
</p>
<p>Click on the Add Device button and you will see the following dialog:</p>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_10.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_10.png" width="500" height="303"></a>
<p>&nbsp;</p>
<p>We want to add a Zune, so click on the Zune button. You should see your Zune appear in the window now:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_11.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_11.png" width="500" height="303"></a>
</p>
<p><i>Note: If your Zune did not appear in the window,make sure you have the latest Zune firmware on your device and that the Zune Player application is closed.
</i></p>
<p>From here select your Zune and press the Next button. After a brief moment you will see the success screen:</p>
<p><a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_12.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_12.png" width="500" height="303"></a>
</p>
<p>Press the Finish button and then close the XNA Game Studio Device Center.</p>
<p>Now click on the Zune project you created earlier and go up to the <i>Build</i> menu and click on
<i>Deploy Zune Copy of SammyTheSnake</i> to begin deploying the game to your Zune.</p>
<a href="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_13.png"><img title="image" border="0" alt="image" src="http://ecn.channel9.msdn.com/o9/c4fcontent/migration/8976852/image_thumb_13.png" width="267" height="262"></a>
<p>&nbsp;</p>
<p>You should see the Zune screen update to show that the game is deploying. Once the text on the screen changes to ”connected” or “waiting for computer”, your game has been completely deployed.</p>
<p>To get to the game on your Zune, simply press the center button to exit XNA Game Studio Connect. Next navigate in your main menu to find the Games option. Inside of there will you will see your newly deployed game. Simply click Play and away you go. Enjoy
 the new snake game and good luck on your adventures of Zune game development with XNA Game Studio.</p>
 <img src="http://m.webtrends.com/dcs1wotjh10000w0irc493s0e_6x1g/njs.gif?dcssip=channel9.msdn.com&dcsuri=http://channel9.msdn.com/Niners/c4f.Nick-Gravelyn/Posts/RSS&WT.dl=0&WT.entryid=Entry:RSSView:53b97e374aee4417a8499e7600ce34a1">]]></description>
      <comments>http://channel9.msdn.com/coding4fun/articles/Sammy-The-Snake-An-XNA-game-for-the-Zune</comments>
      <itunes:summary>
Nick Gravelyn&amp;nbsp;- http://www.nickgravelyn.com/ 
Download: http://codeplex.com/sammythesnake

Software: Visual C# Express Editions,
XNA Game Studios 3.0 
Difficulty: Intermediate 
Time Required: 8 hours 
Cost: Free 
Artwork courtesy of George Clingerman of 
XNADevelopment.com 
Side note: XNA is c# only 
In the exciting world of XNA Game Studio, the new big thing is the XNA Game Studio 3.0 Beta. This beta allows developers to glimpse what will be coming with the full release of XNA Game Studio 3.0. One of the largest new features coming with XNA Game Studio
 3.0 is the new ability to create games for Microsoft&#39;s Zune media device. What we&#39;re going to cover today is how to create a full game for the Zune, specifically a clone of the classic “Snake” game. 
To begin you need to make sure you are set up to start working on Zune games. For all the details and instructions you will need for this step, please visit
http://creators.xna.com/en-us/3.0beta_mainpage. Once you have read and completed steps one and two, continue on with this tutorial. 
Welcome back! Now that you&#39;re all set up with XNA Game Studio 3.0 Beta, we can start working on our game. Since we want to test our game as we go forward, we&#39;re actually going to create the game as a Windows game first and then simply convert it to be a
 Zune project when we are finished. First open up Visual Studio 2008 or Visual C# 2008 Express and create a new Windows project. Let&#39;s call it “SammyTheSnake”. Choose the location to save the project and hit Ok. 
Now that we have the project created
 let&#39;s start out first by adding in the content for our game. George Clingerman of
XNADevelopment.com was nice enough to create some pretty graphics for this tutorial so those are the ones we are going to add to the project. In Visual Studio you will have a panel called the
Solution Explorer which will show you all of the files in your project. In that window you want to find the
Content node of your project. Right click on the Content</itunes:summary>
      <link>http://channel9.msdn.com/coding4fun/articles/Sammy-The-Snake-An-XNA-game-for-the-Zune</link>
      <pubDate>Mon, 06 Oct 2008 15:06:00 GMT</pubDate>
      <guid isPermaLink="false">http://channel9.msdn.com/coding4fun/articles/Sammy-The-Snake-An-XNA-game-for-the-Zune</guid>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/8976852_100.jpg" height="75" width="100"></media:thumbnail>
      <media:thumbnail url="http://ecn.channel9.msdn.com/o9/c4f/images/8976852_220.jpg" height="165" width="220"></media:thumbnail>      
      <dc:creator>Nick Gravelyn </dc:creator>
      <itunes:author>Nick Gravelyn </itunes:author>
      <slash:comments>18</slash:comments>
      <wfw:commentRss>http://channel9.msdn.com/coding4fun/articles/Sammy-The-Snake-An-XNA-game-for-the-Zune/RSS</wfw:commentRss>
      <category>Gaming</category>
      <category>arcade</category>
    </item>    
</channel>
</rss>