<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:blogChannel="http://backend.userland.com/blogChannelModule" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" 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:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>EXHD L.L.C.</title>
    <description>.NET Development Articles</description>
    <link>http://blog.exhd.com/</link>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <generator>BlogEngine.NET 2.0.0.59</generator>
    <language>en-US</language>
    <blogChannel:blogRoll>http://blog.exhd.com/opml.axd</blogChannel:blogRoll>
    <dc:creator>EXHD</dc:creator>
    <dc:title>EXHD L.L.C.</dc:title>
    <geo:lat>0.000000</geo:lat>
    <geo:long>0.000000</geo:long>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Exhd" /><feedburner:info uri="exhd" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>Exhd</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
      <title>LINQ Fundamentals: Using LINQ Operators</title>
      <description>&lt;p&gt;
&lt;p&gt;&lt;strong&gt;Objective&lt;/strong&gt; : Learn how to use some of the LINQ Operators&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Load an Xml Document &lt;ol&gt;
&lt;li&gt;Understand the structure of the XML Files&lt;/li&gt;
&lt;li&gt;Transverse through an XML Document&lt;/li&gt;
&lt;li&gt;Use LINQ Operators such as : Where, Group By, Join, Into, Select, Select new&lt;/li&gt;
&lt;li&gt;Project and create anonymous types&lt;/li&gt;
&lt;/ol&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;ul&gt;
&lt;li&gt;Files Needed: &lt;a href="http://exhd.com/articles/assets/Customers.xml"&gt;Customers&lt;/a&gt; and  &lt;a href="http://exhd.com/articles/assets/Orders.xml"&gt;Orders&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;First, We will be working with the Customers.xml, Notice the root  node is Customers and each Customer has an attribute of CustomerID, and  child elements.&lt;/p&gt;
&lt;p&gt;Create a new console application, add the Customers.xml and  Orders.xml files. Make sure to right click on each then go to properties  and have Copy to Output Directory set to Copy always.&lt;/p&gt;

&lt;pre class="brush:csharp"&gt;        static void Main()
        {
            var customerDoc= XDocument.Load("Customers.xml");

            var query = from c in customerDoc.Descendants("Customer")
                        select new
                                   {
                                       Name=(string)c.Element("ContactName"),
                                       ID=(string)c.Attribute("CustomerID"),
                                       CompanyName = (string)c.Element("CompanyName"),
                                       JobTitle = (string)c.Element("ContactTitle"),
                                       Address = (string)c.Element("FullAddress").Element("Address")
                                   };

            foreach (var customer in query)
            {
                Console.WriteLine("Name : {0}\n\t Company Name: {1}\n\t Job Title: {2}\n\t Address: {3}\n\t ID: {4}\n", customer.Name,
                                  customer.CompanyName, customer.JobTitle, customer.Address,customer.ID);
            }

            Console.ReadLine();
        }&lt;/pre&gt;
&lt;p&gt;We loaded up the XML Document, used the Descendants method to find  all the elements with the name of "Customer" and projected each element  into an&lt;br /&gt; anonymous type. We then looped through all the elements and outputted to the console.&lt;/p&gt;
&lt;p&gt;Now Let's say we wanted to find the Customers that lived in San  Francisco. Looking at the Customers.xml we find that only one Customer  with CustomerID of "LETSS" is a match. LINQ has a where operator that  can filter based on criteria.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        static void Main()
        {
            var customerDoc = XDocument.Load("Customers.xml");

            FindCustomerWithSpecificState(customerDoc);

            Console.ReadLine();
        }
        private static void FindCustomerWithSpecificState(XDocument customerDoc)
        {

            var query = from c in customerDoc.Descendants("Customer")
                        where (string)c.Element("FullAddress").Element("City") == "San Francisco"
                        select new
                                   {
                                       Name=(string)c.Element("ContactName"),
                                       ID = (string)c.Attribute("CustomerID"),
                                       CompanyName = (string)c.Element("CompanyName"),
                                       JobTitle = (string)c.Element("ContactTitle"),
                                       Address = (string)c.Element("FullAddress").Element("Address")
        };

            foreach (var customer in query)
            {
                Console.WriteLine("Name : {0}\n\t Company Name: {1}\n\t Job Title: {2}\n\t Address: {3}\n\t ID: {4}\n", customer.Name,
                                  customer.CompanyName, customer.JobTitle, customer.Address, customer.ID);
            }

        }&lt;/pre&gt;
&lt;p&gt;We should only get one customer back and that is exactly what happens.&lt;/p&gt;
&lt;p&gt;The next step is to find what customers live in the same region and  group them by Region. Looking at the Customers.xml we find that two  customers live in Oregon. So we will need to use the group by operator.  Group by takes a range variable that it needs to operate on and a key to  group on. In our scenario our key is the region element and our range  is "c"&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        static void Main()
        {
            var customerDoc = XDocument.Load("Customers.xml");
            GroupCustomersBasedOnRegion(customerDoc);
            Console.ReadLine();
        }

        private static void GroupCustomersBasedOnRegion(XDocument customerDoc)
        {

            var query = from c in customerDoc.Descendants("Customer")
                    group c by (string)c.Element("FullAddress").Element("Region");

            foreach (var customers in query)
            {
                Console.WriteLine(customers.Key);
                foreach (var customer in customers)
                {
                    Console.WriteLine("\tName: {0}", (string)customer.Element("ContactName"));
                }
            }

        }&lt;/pre&gt;
&lt;p&gt;Let's move on to the Orders.xml. We want to find out what orders each  customer has and output them to the console. What we need to do is to  Join both the Customers.xml and Orders.xml on some property.Looking at  both files notice that CustomerID is the common key between them and  that is what will be used to join them&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        static void Main()
        {
            var customerDoc = XDocument.Load("Customers.xml");
            var ordersDoc = XDocument.Load("Orders.xml");

            FindCustomersNameAndOrder(customerDoc, ordersDoc);
            Console.ReadLine();
        }

        private static void FindCustomersNameAndOrder(XDocument customerDoc, XDocument ordersDoc)
        {
            var query = from e in customerDoc.Descendants("Customer")
                        join o in ordersDoc.Descendants("Order") on
                            (string) e.Attribute("CustomerID") equals (string) o.Element("CustomerID")
                        select new
                                   {
                                       CustomerName = (string)e.Element("ContactName"),
                                       OrderDate = (DateTime)o.Element("OrderDate")
                                   };

            foreach (var customer in query)
            {
                Console.WriteLine("Name : {0}\n\t Order Date {1}", customer.CustomerName, customer.OrderDate);
            }
        }&lt;/pre&gt;
&lt;p&gt;We get back 22 orders but the output can be formatted a little  better. We don't need to have the name of the customer get repeated  every time there is an order. It would look better if we can group all  the orders that a customer has and list all the dates once. So Let's do  that&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        static void Main()
        {
            var customerDoc = XDocument.Load("Customers.xml");
            var ordersDoc = XDocument.Load("Orders.xml");
            GroupCustomersOrders(customerDoc, ordersDoc);

            Console.ReadLine();
        }

        private static void GroupCustomersOrders(XDocument customerDoc, XDocument ordersDoc)
        {
            var query = from e in customerDoc.Descendants("Customer")
                        join o in ordersDoc.Descendants("Order") on
                            (string) e.Attribute("CustomerID") equals (string) o.Element("CustomerID")
                        select new
                                   {

                                       CustomerName = (string)e.Element("ContactName"),
                                       OrderDate = (DateTime) o.Element("OrderDate"),

                                   }
                            into orders
                            group orders by orders.CustomerName into groupedOrders
                        select new
                                   {
                                       CustomerName= groupedOrders.Key,
                                       Orders = groupedOrders
        };

            foreach (var customers in query)
            {
                Console.WriteLine(customers.CustomerName);
                foreach (var customer in customers.Orders)
                {
                    Console.WriteLine("\t"+customer.OrderDate);
                }

            }
        }&lt;/pre&gt;
&lt;p&gt;So in our function we join the documents on CustomerID and project the OrderDate and ContactName elements into an&lt;br /&gt; anonymous type. Right now if we were to output the elements we wouldn't be better off than before.&lt;br /&gt; This time the projection is put into a temporary identifier. We can now  group the orders based on the CustomerName (The Key) and into another  group where we&lt;br /&gt; do yet another projection to get our final result. That's it!&lt;/p&gt;
&lt;/p&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/ntQLsWC_DXrgSx4lbX6TgSnytNo/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ntQLsWC_DXrgSx4lbX6TgSnytNo/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/ntQLsWC_DXrgSx4lbX6TgSnytNo/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/ntQLsWC_DXrgSx4lbX6TgSnytNo/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/rpP3kwwNWr4" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/rpP3kwwNWr4/post.aspx</link>
      <comments>http://blog.exhd.com/KB/LINQ-Fundamentals-Using-LINQ-Operators.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=e698b68b-a5e6-46e9-a14c-732d9a8d2518</guid>
      <pubDate>Sat, 21 May 2011 21:59:00 -0700</pubDate>
      <category>LINQ</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=e698b68b-a5e6-46e9-a14c-732d9a8d2518</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=e698b68b-a5e6-46e9-a14c-732d9a8d2518</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/LINQ-Fundamentals-Using-LINQ-Operators.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=e698b68b-a5e6-46e9-a14c-732d9a8d2518</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=e698b68b-a5e6-46e9-a14c-732d9a8d2518</feedburner:origLink></item>
    <item>
      <title>Snake XNA For Windows Phone</title>
      <description>&lt;p&gt;
&lt;p&gt;The snake game is one of the basic and addictive games ever. The  concept of the game is to navigate a snake to eat a food item, that is  randomly placed on the screen. For every piece that the snake eats, it  grows one more in size. The game ends when the snake dies by either  hitting the wall boundaries or its own body. &lt;a href="http://exhd.com/articles/assets/SnakeXNA.zip"&gt;Click to Download the project&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A video of the game:&lt;/p&gt;
&lt;div align="center" style="padding:10px;"&gt;[youtube:kbkJc-lHE_E]&lt;/div&gt;

&lt;p&gt;&lt;img class="mceWPmore" title="More..." src="http://exhd.com/articles/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /&gt;Create  a new project and name it SnakeEXHD.XNA. Import all the assets to the  content folder, copy and paste the ScreenManager folder to the project  folder.&amp;nbsp; Create a Screens folder which will hold our "Screens". Also  create two classes, a Snake class and a Food class and have them  implement DrawableGameComponent. Below is how the setup should look.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://exhd.com/articles/wp-content/uploads/2011/01/setup.png"&gt;&lt;img class="aligncenter size-full wp-image-243" title="setup" src="http://exhd.com/articles/wp-content/uploads/2011/01/setup.png" alt="" width="325" height="489" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now under the Screens folder. Create a MainMenuScreen class and have it implement MenuScreen.&lt;/p&gt;
&lt;p&gt;The MainMenuScreen will be the screen that presents the options of  whether to play the game, edit the game options or exit the game.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace SnakeEXHD.XNA.Screens
{
    class MainMenuScreen:MenuScreen
    {
        public MainMenuScreen():base("Main Menu")
        {
            var playGameEntry = new MenuEntry("Play Game");
            var optionsGameEntry = new MenuEntry("Options");

            var exitGameEntry = new MenuEntry("Exit Game");

            MenuEntries.Add(playGameEntry);
            MenuEntries.Add(optionsGameEntry);

            MenuEntries.Add(exitGameEntry);

            playGameEntry.Selected += PlayGameEntrySelected;
            optionsGameEntry.Selected += OptionsGameEntrySelected;

            exitGameEntry.Selected += ExitGameEntrySelected;
        }

       void ExitGameEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            ScreenManager.Game.Exit();
        }

        void OptionsGameEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            ScreenManager.AddScreen(new OptionsScreen(), null);
        }

        void PlayGameEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            ScreenManager.AddScreen(new PlayingScreen(), null);
        }
    }
}&lt;/pre&gt;
&lt;p&gt;What we did was create a Menu Entry for each option we want to  display, wired a selection event on each menu item and when fired  navigates us to the desired screen. We haven't created the OptionsScreen  or the PlayingScreen class so let's get that out of the way.&lt;/p&gt;
&lt;p&gt;Create the OptionsScreen class under the screens folder and have it  implement GameScreen. The OptionsScreen doesn't do much except cycle  through some colors. However, you're more than welcome to build on it  and make it functional.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace SnakeEXHD.XNA.Screens
{
    class OptionsScreen:MenuScreen
    {
        private readonly string[] _colorStrings = new[] {"White","Red", "Blue", "Green", "Yellow", "Orange", "Black",};
        private int _defaultColor = 0;
        private MenuEntry _colorEntry;
        private SpriteFont _font;
        public OptionsScreen():base("Options Screen")
        {
            _colorEntry = new MenuEntry(string.Empty);
            _colorEntry.Selected += ColorEntrySelected;
            ChangeMenu();
           MenuEntries.Add(_colorEntry);
        }
        private void ChangeMenu()
        {
            _colorEntry.Text = "Snake Color: " + _colorStrings[_defaultColor];

        }
        public override void LoadContent()
        {
            _font = ScreenManager.Game.Content.Load&amp;lt;SpriteFont&amp;gt;("ScoreFont");
            base.LoadContent();
        }
        public override void Draw(GameTime gameTime)
        {

            ScreenManager.SpriteBatch.Begin();
            ScreenManager.SpriteBatch.DrawString(_font, "Dummy Options for Now \nClick on Color to Fake Change it",
                                                 new Vector2(10, 300), Color.Beige);
            ScreenManager.SpriteBatch.End();
            base.Draw(gameTime);
        }
        private void ColorEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            _defaultColor++;
            if(_defaultColor&amp;gt;_colorStrings.Length-1)
            {
                _defaultColor = 0;
            }
            ChangeMenu();
        }

    }
}&lt;/pre&gt;
&lt;p&gt;That is all the OptionsScreen will do. Move on and create the  PlayingScreen class which is the location of the game play and have it  implement GameScreen.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace SnakeEXHD.XNA.Screens
{
    /// &amp;lt;summary&amp;gt;
    /// Where the Actual Playing occurs
    /// &amp;lt;/summary&amp;gt;
    class PlayingScreen:GameScreen
    {
    }
}&lt;/pre&gt;
&lt;p&gt;Go to Game1.cs and delete everything except the constructor and the graphics variable. The end result should look like this:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace SnakeEXHD.XNA
{

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;

        private ScreenManager _screenManager;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferHeight = 480;
            graphics.PreferredBackBufferWidth = 800;
            graphics.IsFullScreen = true;
            graphics.ApplyChanges();

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            _screenManager = new ScreenManager(this);
            Components.Add(_screenManager);
            _screenManager.AddScreen(new MainMenuScreen(), null);
        }

    }
}&lt;/pre&gt;
&lt;p&gt;Debug and navigate the screens. You should be able to exit the game, go to the options or play screen.&lt;/p&gt;
&lt;p&gt;We are done with the screen implementations. Time to work on the core  classes of the game. Let's get the food class out of the way first.&amp;nbsp;  The food class needs to detect if the snake's head comes in contact with  it. If contact occurs it signals a bite so we randomize the food to  another position.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace SnakeEXHD.XNA
{
    class Food:DrawableGameComponent
    {

        private Vector2 _foodPosition;
        private Texture2D _foodTexture;
        private readonly Random _random = new Random();
        private Rectangle _safeArea;
        private Rectangle _foodRectangle;
        private SpriteBatch _spriteBatch;

        public Food(Game game,Rectangle bounds):base(game)
        {
            _safeArea = bounds;
        }

        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            _foodTexture = Game.Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/food");
            base.LoadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            _spriteBatch.Begin();
            _spriteBatch.Draw(_foodTexture, _foodPosition, Color.White);
            _spriteBatch.End();
            base.Draw(gameTime);
        }
        public bool CheckFoodCollision(Rectangle rectangle)
        {
            if(_foodRectangle.Intersects(rectangle))
            {
                ResetFoodPosition();
                return true;
            }
            return false;
        }

        public void ResetFoodPosition()
        {
            //the Magic 5 is due to the bevel of the background, since we dont want the Food item to be on bevel (Doesnt look good)
            _foodPosition = new Vector2(_random.Next(0,_safeArea.Width-_foodTexture.Width-5), _random.Next(0,_safeArea.Height-_foodTexture.Height-5));
            _foodRectangle = new Rectangle((int) _foodPosition.X, (int) _foodPosition.Y, _foodTexture.Width,
                                           _foodTexture.Height);
        }
    }&lt;/pre&gt;
&lt;p&gt;The two public methods (CheckFoodCollision(), ResetFoodPosition())  are the core methods of the class.&amp;nbsp; CheckFoodCollision checks to see if  the rectangle passed in intersects with the food and if it does the  ResetFoodPosition() is called and randomizes the food's position to  another location otherwise it returns false. If false is returned we  know the snake's head did not come in contact with the food.&lt;/p&gt;
&lt;p&gt;Now that we are done with the food class, the snake class gets our attention.&lt;/p&gt;
&lt;p&gt;The variables that we will be using:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        private Texture2D _snakeTexture;
        private readonly Rectangle _safeBounds;
        private SpriteBatch _spriteBatch;

        private Vector2 _headPosition;
        private readonly Vector2 _startSnakePosition;

        private const int Speed = 16;
        public bool Ready;
        public bool GrowSnake;

        private enum TravelingDirection
        {
            Up,Down,Left,Right,None
        }

        private TravelingDirection _travelingDirection=TravelingDirection.None;
        //holds the snake bodies
        private readonly Queue&amp;lt;Vector2&amp;gt; _snakeBodies;&lt;/pre&gt;
&lt;p&gt;The _safeBounds will be used to center the snake on the screen.&lt;/p&gt;
&lt;p&gt;Have the constructor look like below.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public Snake(Game game,Rectangle safeBounds):base(game)
        {
            _safeBounds = safeBounds;
            _snakeBodies = new Queue&amp;lt;Vector2&amp;gt;();

            _headPosition = _startSnakePosition = new Vector2(_safeBounds.Center.X,_safeBounds.Center.Y);

        }&lt;/pre&gt;
&lt;p&gt;In the LoadContent method we will initialize the spriteBatch and load the snake texture.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            _snakeTexture = Game.Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/snake");

            base.LoadContent();
        }&lt;/pre&gt;
&lt;p&gt;Override the Update method. In it we want to detect what keys the  user pressed and set the direction the snake wants to go. Notice the  "Ready" flag will not allow us to proceed if we set it to false. The  purpose of the ready flag will be explained later but for now trust me  and place it in.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public override void Update(GameTime gameTime)
        {
            if (!Ready)
                return;

            var state = Keyboard.GetState();
            if (state.IsKeyDown(Keys.Up))
                _travelingDirection = TravelingDirection.Up;
            else if (state.IsKeyDown(Keys.Down))
                _travelingDirection = TravelingDirection.Down;
            else if (state.IsKeyDown(Keys.Left))
                _travelingDirection = TravelingDirection.Left;
            else if (state.IsKeyDown(Keys.Right))
                _travelingDirection = TravelingDirection.Right;

            MoveSnake(_travelingDirection);

            base.Update(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;Now create the MoveSnake method and let's figure out by how much the snake wants to move.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        private void MoveSnake(TravelingDirection direction)
        {
            Vector2 vectorDirection;
            switch (direction)
            {
                case TravelingDirection.Up:
                    vectorDirection = new Vector2(0, -Speed);
                    break;
                case TravelingDirection.Down:
                    vectorDirection = new Vector2(0,Speed);
                    break;
                case TravelingDirection.Left:
                    vectorDirection = new Vector2(-Speed, 0);
                    break;
                case TravelingDirection.Right:
                    vectorDirection = new Vector2(Speed, 0);
                    break;
                case TravelingDirection.None:
                    vectorDirection = Vector2.Zero;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("direction");
            }

           if(_travelingDirection!=TravelingDirection.None)
            UpdateSnakeCoordinates(vectorDirection);

        }

        private void UpdateSnakeCoordinates(Vector2 direction)
        {
            if(!GrowSnake)//if the snake wants to grow there is no reason to snip off a tail so we skip it once
            _snakeBodies.Dequeue();//dequeue the tail which will simulate movement

             _snakeBodies.Enqueue(_headPosition);//add whatever the position of the head was at
            _headPosition += direction;//increment the position of the head
            GrowSnake = false;
        }&lt;/pre&gt;
&lt;p&gt;If the snake wants to move up we initialize the vector with a&amp;nbsp; Speed  of (0,-16), down (0,16), left (-16,0),right (16,0). We make sure that a  travel direction has been established before calling  UpdateSnakeCoordinates. In that method, movement is simulated with  snipping off the tail by dequeueing it and adding a body behind the head  of the snake. We then increment the head of the snake by the amount of  the direction established previously.&amp;nbsp; A GrowSnake flag of true will  signal that the snake ate the food. If that scenario occurs then there  is no need to snip off the tail since an extra body needs to be added so  skip the dequeueing.&lt;/p&gt;
&lt;p&gt;Let's draw the body and the head. The head will be a seperate entity  from the body. The only reason for that is to allow us to detect when  the head collides with its body in the simplest fashion.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public override void Draw(GameTime gameTime)
        {
            _spriteBatch.Begin();
            foreach (var snakeBody in _snakeBodies)
            {
                _spriteBatch.Draw(_snakeTexture, snakeBody, Color.White);
            }
            _spriteBatch.Draw(_snakeTexture, _headPosition, Color.White);
            _spriteBatch.End();
            base.Draw(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;Below are helper methods that will be used in the PlayingScreen class.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; public bool CheckWallCollision(Rectangle[] wallRectangles)
        {
            //finds if the snake intersected with any of the walls
            return wallRectangles.Any(wallRectangle =&amp;gt; GetHeadRectangle().Intersects(wallRectangle));
        }

        public bool CheckSnakeSelfCollision()
        {
            return _snakeBodies.Contains(_headPosition);
        }

        public void ResetSnake()
        {
            _snakeBodies.Clear();
            _headPosition = _startSnakePosition;
            _travelingDirection = TravelingDirection.None;
            CreateSnakeBody();

        }
        private void CreateSnakeBody()
        {
            //start off with a Body + One tail.
            var firstTail = (new Vector2(_safeBounds.Center.X, _safeBounds.Center.Y +_snakeTexture.Height));
            _snakeBodies.Enqueue(firstTail);
        }
        //used to detect collision between it and the food.
        public Rectangle GetHeadRectangle()
        {
            return new Rectangle((int)_headPosition.X,(int) _headPosition.Y, _snakeTexture.Width, _snakeTexture.Height);
        }&lt;/pre&gt;
&lt;p&gt;The snake class is done and time to move on to the PlayingScreen class to hook everything up.&lt;/p&gt;
&lt;p&gt;Add the below variables in the PlayingScreen class.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        private Texture2D _backgroundTexture;
        private SpriteFont _scoreFont;

        private SpriteBatch _spriteBatch;
        private int _score;
        private Rectangle _safeBounds;

        private Food _food;
        private Snake _snake;

        private Rectangle[] _wallRectangles=new Rectangle[4];

        private enum GameState
        {
            PreGame,Playing,GameOver
        }

        private GameState _gameState;&lt;/pre&gt;
&lt;p&gt;The _wallRectangles variable is used to detect if the snake collided  with any of the 4 boundary walls.&amp;nbsp; The background provided is only  (800*450) so the  snake can't go beyond the 450 pixels in the y-axis.  The _safeBounds variable will hold that information and allow us to  build the boundary walls.&amp;nbsp; In the constructor initialize the  _safeBounds.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;       public PlayingScreen()
        {
            _safeBounds = new Rectangle(0, 0, 800, 450);

        }&lt;/pre&gt;
&lt;p&gt;Override the LoadContent() method and have it load the assets and add the snake and food as Components.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public override void LoadContent()
        {
            _spriteBatch = ScreenManager.SpriteBatch;
            var content = ScreenManager.Game.Content;

            _backgroundTexture = content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/Background");
            _scoreFont = content.Load&amp;lt;SpriteFont&amp;gt;("ScoreFont");

            _food = new Food(ScreenManager.Game, _safeBounds);
            ScreenManager.Game.Components.Add(_food);

            _snake = new Snake(ScreenManager.Game, _safeBounds);
            ScreenManager.Game.Components.Add(_snake);

            _wallRectangles[0] = new Rectangle(0, _safeBounds.Top, _safeBounds.Width, 1);
            _wallRectangles[1] = new Rectangle(0, _safeBounds.Bottom, _safeBounds.Width, 1);
            _wallRectangles[2] = new Rectangle(_safeBounds.Right, 0, 1, _safeBounds.Height);
            _wallRectangles[3] = new Rectangle(_safeBounds.Left, 0, 1, _safeBounds.Height);

            SetGameState(GameState.PreGame);
            base.LoadContent();
        }&lt;/pre&gt;
&lt;p&gt;Create the SetGameState(...) method&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;  private void SetGameState(GameState gameState)
      {
            _gameState = gameState;
            switch (_gameState)
            {
                case GameState.PreGame:
                    _snake.ResetSnake();
                    _food.ResetFoodPosition();
                    _score = 0;
                    break;
                case GameState.Playing:
                    _snake.Ready = true;
                    break;
                case GameState.GameOver:
                    _snake.Ready = false;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }&lt;/pre&gt;
&lt;p&gt;If we are in the PreGame state we reset everything to it's start  position as if the user had just opened the game. The "Ready" flag is  used to control when the user wants to play and take control of the  snake.&amp;nbsp; Why do we need a flag? Had we not included that flag then the  user would have been able to&amp;nbsp; control the snake regardless of what the  GameState was. The Keyboard state and movement are wired in the Snake's  class and there is no way for that class to know what the GameState we  are in is.&lt;/p&gt;
&lt;p&gt;Override the Update method and have it look like this,&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {

            switch(_gameState)
            {
                case GameState.PreGame:
                    UpdatePreGame();
                    break;
                case GameState.Playing:
                    UpdatePlayingGame();
                    break;
                case GameState.GameOver:
                    UpdateGameOver();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }&lt;/pre&gt;
&lt;p&gt;The Update method checks what the GameState is and calls the appropriate method. Let's create those three methods.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        private void UpdateGameOver()
        {
            if(TouchPanel.GetState().Count&amp;gt;0)
            {
                SetGameState(GameState.PreGame);
                SetGameState(GameState.Playing);
            }
        }

        private void UpdatePreGame()
        {
            if(TouchPanel.GetState().Count&amp;gt;0)
            {
                SetGameState(GameState.Playing);
            }
        }&lt;/pre&gt;
&lt;p&gt;If we are in the GameOver state then the UpdateGameOver would be  called. If we detect a touch on the screen the GameState is set to  PreGame to reset everything then set again to Playing as the user  signaled they want to play. If the game had been on PreGame then on a  touch we assume per instructions (Done later) that the user wants to  play.&lt;/p&gt;
&lt;p&gt;Our UpdatePlayingGame() method is responsible for the game play. It  will check to see if the snake collided with the food and set a flag to  grow the snake if a collision was detected and update the score by 10.&lt;/p&gt;
&lt;p&gt;We also check to see if the head of the snake collided with its body  or the wall, if either are true then the game state is set to GameOver.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void UpdatePlayingGame()
        {
            if(_food.CheckFoodCollision(_snake.GetHeadRectangle()))
            {
                _score += 10;
                _snake.GrowSnake = true;
            }
            if(_snake.CheckSnakeSelfCollision() || _snake.CheckWallCollision(_wallRectangles))
            {
                SetGameState(GameState.GameOver);
            }
        }&lt;/pre&gt;
&lt;p&gt;Almost done. Time to get things on the screen. Override the draw  method to draw the background and check what game state we are in to  draw the appropriate instructions.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;  public override void Draw(GameTime gameTime)
        {

            _spriteBatch.GraphicsDevice.Clear(Color.White);
            _spriteBatch.Begin();
            _spriteBatch.Draw(_backgroundTexture, Vector2.Zero, Color.White);
            DrawScore(_spriteBatch);

            switch (_gameState)
            {
                case GameState.PreGame:
                    DrawPreGame(_spriteBatch);
                    break;
                case GameState.Playing:
                    break;
                case GameState.GameOver:
                    DrawGameOver(_spriteBatch);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            _spriteBatch.End();

            base.Draw(gameTime);
        }
        private void DrawScore(SpriteBatch spriteBatch)
        {
            var str = "Score: " + _score;
            var pos = _scoreFont.MeasureString(str);
            spriteBatch.DrawString(_scoreFont, str, new Vector2(0, 480 - pos.Y), Color.Blue);
        }
        private void DrawGameOver(SpriteBatch spriteBatch)
        {
            var str = "Game Over!!!!!";
            var pos = _scoreFont.MeasureString(str);
            spriteBatch.DrawString(_scoreFont, str, new Vector2(200, 480 - pos.Y), Color.Black);
        }
        private void DrawPreGame(SpriteBatch spriteBatch)
        {
            var str = "Touch To start and Key Arrows to Navigate";
            var pos = _scoreFont.MeasureString(str);
            spriteBatch.DrawString(_scoreFont, str, new Vector2(230, 480 - pos.Y), Color.Black);
        }&lt;/pre&gt;
&lt;p&gt;Debug and click or touch the screen to start. Use the arrow keys to navigate. That's it. Your own Snake in XNA&lt;/p&gt;
&lt;/p&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/I8EmOcdS2roFVvFNOvpA-QH8HFc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/I8EmOcdS2roFVvFNOvpA-QH8HFc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/I8EmOcdS2roFVvFNOvpA-QH8HFc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/I8EmOcdS2roFVvFNOvpA-QH8HFc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/h9hMCuTGnHw" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/h9hMCuTGnHw/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Snake-XNA-For-Windows-Phone.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=77ae216e-ffad-402e-a7bc-973b6ec2d5c0</guid>
      <pubDate>Tue, 04 Jan 2011 21:58:00 -0700</pubDate>
      <category>Windows Phone</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=77ae216e-ffad-402e-a7bc-973b6ec2d5c0</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=77ae216e-ffad-402e-a7bc-973b6ec2d5c0</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Snake-XNA-For-Windows-Phone.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=77ae216e-ffad-402e-a7bc-973b6ec2d5c0</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=77ae216e-ffad-402e-a7bc-973b6ec2d5c0</feedburner:origLink></item>
    <item>
      <title>Bat Escape XNA-Part 2 of 2</title>
      <description>&lt;p&gt;
&lt;p&gt;Now that we have Part 1 finished and have a functional game. Let's  finish the stray ends and create the obstacles that fly towards the bat,  the game states with different screen instructions and save/load the  furthest distance that the user flew. &lt;a href="http://exhd.com/articles/assets/BatEscapeFull.zip"&gt;Click to download the assets&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Here is a refresher video of what the game was about and a link to &lt;a href="http://exhd.com/articles/windows-phone/bat-escape-xna-part-1-of-2/"&gt;Part1&lt;/a&gt;&lt;/p&gt;
&lt;div align="center" style="padding:10px;"&gt;[youtube:I3kdoT_hedo]&lt;/div&gt;

&lt;p&gt;&lt;img class="mceWPmore" title="More..." src="http://exhd.com/articles/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;First, create an Obstacle Class which will be in charge of firing the red triangles at the Bat.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; class Obstacle
    {
        public Texture2D Texture { get; private set; }
        private List&amp;lt;Vector2&amp;gt; _position;
        private readonly Vector2 _velocity;
        private Viewport _view;
        private readonly Random _random= new Random();
        public Obstacle(Texture2D texture,Viewport view)
        {
            Texture = texture;
            _velocity = new Vector2(4, 0);
            _view = view;

        }
        public void Update(GameTime gameTime)
        {
            for (var i = 0; i &amp;lt; _position.Count; i++)
            {
                _position[i] -= _velocity;
                if(_position[i].X &amp;lt; -_view.Width/2f)
                {
                    var vec = new Vector2(_view.Width + Texture.Width, _random.Next(104, 336));
                    _position[i] = vec;
                }
            }

        }
       public void ResetBlock()
        {
            _position = new List&amp;lt;Vector2&amp;gt;
                            {
                                new Vector2(_view.Width + Texture.Width,  _random.Next(104, 336)),
                                new Vector2((float) (1.75*_view.Width),  _random.Next(104, 336))
                            };
        }
        public List&amp;lt;Vector2&amp;gt; GetBlockPositions()
        {
            return _position;
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            foreach (var position in _position)
            {
                spriteBatch.Draw(Texture, position, Color.Red);
            }

        }
    }&lt;/pre&gt;
&lt;p&gt;We will only work with two triangles since we are staying true to the  original Helicopter Game. If you play it long enough you will notice  that only two blocks appear, when one is about to disappear the other  appears on the screen. So, all we do is detect when one triangle is  about to leave the screen and just reset it back on the other side with a  random Y-Axis value. The Numbers (104,336) were obtained from knowing  how low the top wall comes down/how high the Bottom wall rises and just  subtracting the height of the triangle (Discussed in Part 1).&lt;/p&gt;
&lt;p&gt;Now back to our Game1 Class where we will spend the rest of this  tutorial on.&amp;nbsp; We want to do Pixel-By-Pixel Collision so we need to have  color array variables. We want to save/load the high scores so we need a  constant string variable that will act as our file path, and we need an  enum that will tell us what state of the game we are in-whether we are  in Pre-Game , Playing or Game Over.&lt;/p&gt;
&lt;p&gt;Edit the Game1 class and add these variables.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        private SpriteFont _scoreFont;

        private Color[] _obstacleColorData;
        private Color[] _terrainColorData;
        private Obstacle _obstacle;
        private const string BatEscapePath = "batEscape.exhd";

        public enum GameState
        {
            PreGame,
            Playing,
            GameOver
        } ;

        private GameState _gameState;

        private float _distance;
        private int _highScore;

        private readonly string[] _gameInstructions = { "Touch To Start", "Hold touch to go up", "Release to go down" };
        private readonly string[] _gameOverInstructions = { "Game Over", "Tap to Restart" };&lt;/pre&gt;
&lt;p&gt;We need to load the assets for our Obstacle and the font used to draw the score on the screen.&lt;/p&gt;
&lt;p&gt;Go to the LoadContent() method and add.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;            var obstacleTexture = Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/spike");
            _obstacle = new Obstacle(obstacleTexture, GraphicsDevice.Viewport);
            _obstacleColorData = new Color[obstacleTexture.Width * obstacleTexture.Height];
            obstacleTexture.GetData(_obstacleColorData);

            _scoreFont = Content.Load&amp;lt;SpriteFont&amp;gt;(@"Fonts/scoreFont");
            //used to control what game state we are in
            SetGameState(GameState.PreGame);&lt;/pre&gt;
&lt;p&gt;Now create a SetGameState method that will accept the GameState enum  as our parameter. The method will be in charge of resetting the  positions of our assets and loading/saving the high score data. For  example,when the user loses and they want to play again we would do call  SetGameState with GameState.PreGame as the parameter to reset  everything&amp;nbsp; then call it again and pass GameState.Playing&amp;nbsp; to start the  game.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        private void SetGameState(GameState gameState)
        {
            _gameState = gameState;
            switch (_gameState)
            {
                case GameState.PreGame:
                    _distance = 0;
                    if (_highScore == 0)
                    {
                        LoadGameData();
                    }
                    _bat.ResetPosition();
                    _terrain.ResetTerrain();
                    _obstacle.ResetBlock();
                    break;
                case GameState.Playing:
                    break;
                case GameState.GameOver:
                    SaveGameData();
                    break;

            }
        }&lt;/pre&gt;
&lt;p&gt;The PreGame state resets the distance traveled to zero, checks to see  if the high score is zero. If it is we call LoadGameData() to see if we  can load any scores. The positions of the assets are also reset. The  GameState.GameOver will only be in charge of saving the data. However,  this example does not deal with the scenario of the phone getting&amp;nbsp;  Tombstoned.&lt;/p&gt;
&lt;p&gt;The Save/Load methods are pretty standard and use the IsolatedStorageFile API.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void SaveGameData()
        {
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = storage.CreateFile(BatEscapePath))
                {
                    var bytes = BitConverter.GetBytes(_highScore);
                    stream.Write(bytes, 0, bytes.Length);
                }
            }
        }
        private void LoadGameData()
        {
            using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (storage.FileExists(BatEscapePath))
                {
                    using (var stream = storage.OpenFile(BatEscapePath, FileMode.Open))
                    {
                        //byte is 8
                        var bytesToSave = new byte[4];
                        stream.Read(bytesToSave, 0, 4);
                        _highScore = BitConverter.ToInt32(bytesToSave, 0);
                    }
                }
            }
        }&lt;/pre&gt;
&lt;p&gt;The only difficult thing that may throw you off would be the bytes in  LoadGameData method. An int is 32 bits and a Byte is 8 bits so to be  able to save an Int with the minimum possible array size we need to have  an array of 32/8 =4.&lt;/p&gt;
&lt;p&gt;Now for the Update method, we need to check what game state we are in  and call the appropriate method that deals with that state so...&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                Exit();
                SaveGameData();
            }
            switch (_gameState)
            {
                case GameState.PreGame:
                    UpdatePreGameInstructions();
                    break;
                case GameState.Playing:
                    UpdatePlayingGame(gameTime);
                    break;
                case GameState.GameOver:
                    UpdateGameOverInstructions();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            base.Update(gameTime);
        }

        private void UpdatePreGameInstructions()
        {
            var touches = TouchPanel.GetState();
            if (touches.Count &amp;gt; 0)
            {
                if (touches[0].State == TouchLocationState.Released)
                {

                    SetGameState(GameState.Playing);
                }
            }

        }
        private void UpdateGameOverInstructions()
        {

            var touches = TouchPanel.GetState();
            if (touches.Count &amp;gt; 0)
            {
                if (touches[0].State == TouchLocationState.Released)
                {
                    SetGameState(GameState.PreGame);
                    SetGameState(GameState.Playing);
                }
            }

        }&lt;/pre&gt;
&lt;p&gt;So if we are in GameState.PreGame State and a touch and release occur  we know the user wants to play, so we start the game. In the  GameState.GameOver state we know if the user touches and releases they  also want to play but the game is not where it should be (Clean Slate)  so we need to call SetGameState with GameState.PreGame state then call  the method again and pass the GameState.Playing state to achieve what  the user wants.&lt;/p&gt;
&lt;p&gt;Now work on the UpdatePlayingGame method&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void UpdatePlayingGame(GameTime gameTime)
        {
            CheckCollision();
            DetectTouch(gameTime);
            _terrain.Update(gameTime);
            UpdateDistanceAndScore(gameTime);
            _obstacle.Update(gameTime);

        }
        private void UpdateDistanceAndScore(GameTime gameTime)
        {

            _distance += (int)((gameTime.ElapsedGameTime.TotalMilliseconds / 10) * 0.45);

            if (_highScore &amp;lt; _distance)
            {
                _highScore = (int)Math.Round(_distance);
            }
        }&lt;/pre&gt;
&lt;p&gt;So on each update we check to see if the Bat collided with any  obstacle, call the update method on each asset variable and update the  distance traveled. The DetectTouch(gameTime) was written in part 1. The  CheckCollision method gone over in detail &lt;a href="http://exhd.com/articles/windows-phone/detecting-collision-multiple-objects-xna/"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void CheckCollision()
        {
            var batRect = new Rectangle((int)_bat.Position.X, (int)_bat.Position.Y, (int)_bat.GetBatWidthAndHeight().X,
                                         (int)_bat.GetBatWidthAndHeight().Y);

            for (int i = 0; i &amp;lt; _obstacle.GetBlockPositions().Count; i++)
            {
                var blockPosition = _obstacle.GetBlockPositions()[i];
                var blockRect = new Rectangle((int)blockPosition.X, (int)blockPosition.Y, _obstacle.Texture.Width,
                                              _obstacle.Texture.Height);
                if (batRect.Intersects(blockRect))
                {
                    if (PixelByPixelCollision(blockRect, _obstacleColorData, batRect, _bat.ColorData()))
                    {

                        SetGameState(GameState.GameOver);
                        return;
                    }
                }
            }
            for (int i = 0; i &amp;lt; _terrain.GetTerrainVectors().Count; i++)
            {

                var terrainPosition = _terrain.GetTerrainVectors()[i];

                if (terrainPosition.X &amp;gt; _bat.Position.X - _terrain.WallTexture.Width)
                {
                    var terrainRect = new Rectangle((int)terrainPosition.X, (int)terrainPosition.Y,
                                              _terrain.WallTexture.Width, _terrain.WallTexture.Height);

                    if (batRect.Intersects(terrainRect))
                    {
                        if (PixelByPixelCollision(terrainRect, _terrainColorData, batRect, _bat.ColorData()))
                        {

                            SetGameState(GameState.GameOver);
                            return;
                        }
                    }
                }

            }

        }

        private static bool PixelByPixelCollision(Rectangle rectA, Color[] rectAColor, Rectangle rectB, Color[] rectBColor)
        {
            var top = Math.Max(rectA.Top, rectB.Top);
            var bottom = Math.Min(rectA.Bottom, rectB.Bottom);
            var left = Math.Max(rectA.Left, rectB.Left);
            var right = Math.Min(rectA.Right, rectB.Right);

            // Check every point within the intersection bounds
            for (int y = top; y &amp;lt; bottom; y++)
            {
                for (int x = left; x &amp;lt; right; x++)
                {
                    // Get the color of both pixels at this point
                    Color colorA = rectAColor[(x - rectA.Left) +
                                         (y - rectA.Top) * rectA.Width];
                    Color colorB = rectBColor[(x - rectB.Left) +
                                         (y - rectB.Top) * rectB.Width];

                    // If both pixels are not completely transparent,
                    if (colorA.A == 0 || colorB.A == 0) continue;
                    // then an intersection has been found
                    return true;
                }
            }
            return false;

        }&lt;/pre&gt;
&lt;p&gt;The only thing that is left is to draw the assets. Go to the draw method and make it look like this&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            _spriteBatch.Begin();
            DrawAssets();
            DrawDistance();
            DrawHighScore();

            switch (_gameState)
            {
                case GameState.PreGame:
                    DrawPreGameInstructions();
                    break;
                case GameState.Playing:
                    break;
                case GameState.GameOver:
                    DrawPostGameInstructions();
                    break;

            }

            _spriteBatch.End();
            base.Draw(gameTime);
        }

        private void DrawAssets()
        {
            _terrain.Draw(_spriteBatch);
            _obstacle.Draw(_spriteBatch);
        }

        private void DrawDistance()
        {
            var str = string.Format("Distance: {0:0}", _distance);
            var pos = _scoreFont.MeasureString(str);
            _spriteBatch.DrawString(_scoreFont, str, new Vector2(20, (GraphicsDevice.Viewport.Height - pos.Y - 5)), Color.White);
        }

        private void DrawHighScore()
        {

            var str = string.Format("Best: {0:0}", _highScore);
            var pos = _scoreFont.MeasureString(str);
            _spriteBatch.DrawString(_scoreFont, str, new Vector2(GraphicsDevice.Viewport.Width - pos.X - 5, (GraphicsDevice.Viewport.Height - pos.Y - 5)), Color.White);
        }

        private void DrawPostGameInstructions()
        {
            for (var i = 0; i &amp;lt; _gameOverInstructions.Length; i++)
            {
                _spriteBatch.DrawString(_scoreFont, _gameOverInstructions[i], new Vector2(300, 200 + 30 * i), Color.White);
            }
        }

        private void DrawPreGameInstructions()
        {
            for (var i = 0; i &amp;lt; _gameInstructions.Length; i++)
            {
                _spriteBatch.DrawString(_scoreFont, _gameInstructions[i], new Vector2(300, 200 + 30 * i), Color.White);
            }
        }&lt;/pre&gt;
&lt;p&gt;So we draw the "Independent" assets that have nothing to do with what  GameState we are in and always need to be on the screen. Then, we check  using a switch statement what GameState we are in and draw the  instructions needed for that particular state.&lt;/p&gt;
&lt;p&gt;That is it! your own Helicopter game in XNA.&lt;/p&gt;
&lt;p&gt;Things that you can do:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Implement a Lives System (ex: 3 Lives)&lt;/li&gt;
&lt;li&gt;Have a Pause GameState&lt;/li&gt;
&lt;li&gt;Figure out how to solve the Tombstone dilemma&lt;/li&gt;
&lt;li&gt;Implement it as Multiplayer (Two Bats) and port it to XBox 360&lt;/li&gt;
&lt;li&gt;Have the Bat Fight back and Destroy the triangles (Particle System).&lt;/li&gt;
&lt;li&gt;Have the User Draw The Path for the Bat Flight (Using Gestures).&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/dfa5Wj7DsyMv_5icy5BWPqOYsng/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/dfa5Wj7DsyMv_5icy5BWPqOYsng/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/dfa5Wj7DsyMv_5icy5BWPqOYsng/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/dfa5Wj7DsyMv_5icy5BWPqOYsng/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/TKIoY5kIL2g" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/TKIoY5kIL2g/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Bat-Escape-XNA-Part-2-of-2.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=bb968818-0a02-4b15-9f80-b8be853a9b87</guid>
      <pubDate>Mon, 03 Jan 2011 21:56:00 -0700</pubDate>
      <category>Windows Phone</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=bb968818-0a02-4b15-9f80-b8be853a9b87</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=bb968818-0a02-4b15-9f80-b8be853a9b87</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Bat-Escape-XNA-Part-2-of-2.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=bb968818-0a02-4b15-9f80-b8be853a9b87</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=bb968818-0a02-4b15-9f80-b8be853a9b87</feedburner:origLink></item>
    <item>
      <title>Reading a RSS feed in Silverlight using SyndicationFeed</title>
      <description>&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;We will discuss how to use the SyndicationFeed class to parse a RSS  Feed, display the information in a Listbox and when an item is selected,  have a ChildWindow popup and provide detailed information on a feed  item. The&lt;a rel="nofollow" href="http://search.twitter.com/api/"&gt; Twitter search API&lt;/a&gt; will be used. This post assumes that you know what Data Binding is but if you don't, then&amp;nbsp;&lt;a rel="nofollow" href="http://msdn.microsoft.com/en-us/library/ms752347.aspx"&gt; Click here to read &lt;/a&gt;on it then come back.  &lt;a href="http://exhd.com/articles/assets/TwitterApp.zip"&gt;Click&amp;nbsp; to Download the project&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Have a look at the final product and keep reading for step by step:&lt;/p&gt;
&lt;p&gt;&lt;div id="silverlightControlHost"&gt;&lt;object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="500" height="300"&gt;&lt;param name="source" value="http://exhd.com/articles/assets/TwitterApp.xap"/&gt;&lt;param name="background" value="white" /&gt;&lt;param name="minRuntimeVersion" value="3.0.40723.0" /&gt;&lt;param name="autoupgrade" value="true" /&gt;&lt;param name="enableHtmlAccess" value="true" /&gt;&lt;a href="http://go.microsoft.com/fwlink/?LinkID=149156" style="text-decoration: none;"&gt;&lt;img src="http://storage.timheuer.com/sl4wp-ph.png" alt="Install Microsoft Silverlight" style="border-style: none; width:400px; height:200px"/&gt;&lt;/a&gt;&lt;/object&gt;&lt;iframe style="visibility:hidden;height:0;width:0;border:0px" id="_sl_historyFrame"&gt;&lt;/iframe&gt;&lt;/div&gt;&lt;br /&gt;&lt;/p&gt;


&lt;p&gt;&lt;img class="mceWPmore" title="More..." src="http://exhd.com/articles/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /&gt;&lt;/p&gt;
&lt;p&gt;The part we need to pay attention to is:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;To construct a request URL, simply append your URL-encoded query to our Atom service URL:&lt;/p&gt;
&lt;pre&gt;http://search.twitter.com/search.atom?q=&amp;lt;query&amp;gt;&lt;/pre&gt;
&lt;/blockquote&gt;
&lt;p&gt;Try it out, in the Browser's URL type  http://search.twitter.com/search.atom?q=silverlight and a list of Feed  items with the keyword Silverlight will be formatted as a RSS feed. View  the source of the page to learn about the structure. Below is a  simplification of what one node of an item looks like.&lt;/p&gt;
&lt;pre class="brush:xml"&gt; &amp;lt;entry&amp;gt;
    &amp;lt;id&amp;gt;ID BY Twitter&amp;lt;/id&amp;gt;
    &amp;lt;published&amp;gt;Date Here&amp;lt;/published&amp;gt;
    &amp;lt;link type="text/html" rel="alternate" href="The Link to the Main Status"/&amp;gt;
    &amp;lt;title&amp;gt;What the Title is&amp;lt;/title&amp;gt;
    &amp;lt;content type="html"&amp;gt;Same as Title Except Encoded in HTML&amp;lt;/content&amp;gt;
    &amp;lt;updated&amp;gt;Date If they Updated&amp;lt;/updated&amp;gt;
    &amp;lt;link type="image/png" rel="image" href="An Image of the user if provided"/&amp;gt;
    &amp;lt;twitter:geo&amp;gt;
    &amp;lt;/twitter:geo&amp;gt;
    &amp;lt;twitter:metadata&amp;gt;
      &amp;lt;twitter:result_type&amp;gt;recent&amp;lt;/twitter:result_type&amp;gt;
    &amp;lt;/twitter:metadata&amp;gt;
    &amp;lt;twitter:source&amp;gt;What Program They Posted from&amp;lt;/twitter:source&amp;gt;
    &amp;lt;twitter:lang&amp;gt;en&amp;lt;/twitter:lang&amp;gt;
    &amp;lt;author&amp;gt;
      &amp;lt;name&amp;gt;Name&amp;lt;/name&amp;gt;
      &amp;lt;uri&amp;gt;Link to the Authors' twitter&amp;lt;/uri&amp;gt;
    &amp;lt;/author&amp;gt;
&amp;lt;/entry&amp;gt;&lt;/pre&gt;
&lt;p&gt;Our focus will be on the title,image,published date, the name and uri of the twitter account.&lt;/p&gt;
&lt;p&gt;Create a TwitterItem Class and have it look like this:&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; public class TwitterItem
    {
        public string Title { get; set; }
        public Uri ImageUri { get; set; }
        public string AuthorName { get; set; }
        public string AuthorUri { get; set; }
        public DateTime Published { get; set; }
    }&lt;/pre&gt;
&lt;p&gt;The Getter/Setters are very important when it comes to binding otherwise you will see&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;System.Windows.Data Error: BindingExpression path error:  'Title' property not found on 'TwitterApp.TwitterItem'  'TwitterApp.TwitterItem' (HashCode=31700771). BindingExpression:  Path='Title' DataItem='TwitterApp.TwitterItem' (HashCode=31700771);  target element is 'System.Windows.Controls.TextBlock' (Name=''); target  property is 'Text' (type 'System.String')..&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;in your output window had you done&amp;nbsp; this instead&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public class TwitterItem
    {
       //removed the getter/setter property
        public string Title;
        public Uri ImageUri;
        public string AuthorName;
        public string AuthorUri ;
        public DateTime Published ;
    }&lt;/pre&gt;
&lt;p&gt;Back to MainPage.xaml to create the layout.&lt;/p&gt;
&lt;pre class="brush:xml"&gt; &amp;lt;Grid x:Name="LayoutRoot" Background="White"&amp;gt;
    	&amp;lt;Grid.ColumnDefinitions&amp;gt;
    		&amp;lt;ColumnDefinition Width="*"/&amp;gt;
		&amp;lt;ColumnDefinition/&amp;gt;
		&amp;lt;/Grid.ColumnDefinitions&amp;gt;
		&amp;lt;Grid.RowDefinitions&amp;gt;
		&amp;lt;RowDefinition Height="Auto"/&amp;gt;
		&amp;lt;RowDefinition/&amp;gt;
		&amp;lt;/Grid.RowDefinitions&amp;gt;
    	  &amp;lt;StackPanel Grid.Column="0" Orientation="Horizontal" Margin="5"&amp;gt;
    	  	&amp;lt;TextBox x:Name="searchTxt" Width="150" Padding="0,5,0,0"/&amp;gt;
    	     &amp;lt;Button x:Name="searchBtn" Content="Search" Margin="5" Click="searchBtn_Click" /&amp;gt;
	     &amp;lt;/StackPanel&amp;gt;
    	        &amp;lt;Border BorderBrush="Black" Grid.Row="1" BorderThickness="1" Grid.ColumnSpan="2"&amp;gt;
    		&amp;lt;ListBox x:Name="twitterListBox"&amp;gt;
                &amp;lt;ListBox.ItemTemplate&amp;gt;
                    &amp;lt;DataTemplate&amp;gt;
                        &amp;lt;Grid&amp;gt;
                            &amp;lt;Grid.ColumnDefinitions&amp;gt;
                                &amp;lt;ColumnDefinition Width="Auto"/&amp;gt;
                                &amp;lt;ColumnDefinition Width="*"/&amp;gt;
                            &amp;lt;/Grid.ColumnDefinitions&amp;gt;

                            &amp;lt;Image Source="{Binding ImageUri}" Width="50" Height="50"
                                   Stretch="UniformToFill"/&amp;gt;
                            &amp;lt;TextBlock Text="{Binding Title}" Grid.Column="1"/&amp;gt;
                        &amp;lt;/Grid&amp;gt;
                    &amp;lt;/DataTemplate&amp;gt;
                &amp;lt;/ListBox.ItemTemplate&amp;gt;
            &amp;lt;/ListBox&amp;gt;
		&amp;lt;/Border&amp;gt;
       &amp;lt;/Grid&amp;gt;&lt;/pre&gt;
&lt;p&gt;Navigate to the MainPage.xaml.cs.&lt;/p&gt;
&lt;p&gt;The two variables that will be used&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private const string TwitterUri = "http://search.twitter.com/search.atom?q=";
 private ObservableCollection&amp;lt;TwitterItem&amp;gt; _twitterItems = new ObservableCollection&amp;lt;TwitterItem&amp;gt;();&lt;/pre&gt;
&lt;p&gt;When our button is clicked we will want to check before sending any  query that some text is typed in and if so we use the WebClient to  download the results of the search.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private void searchBtn_Click(object sender, RoutedEventArgs e)
        {
            //check to make sure the text is not empty
            if(string.IsNullOrWhiteSpace(searchTxt.Text))
            {
                MessageBox.Show("The TextBox is Empty");
                return;
            }

            var wc = new WebClient();
            wc.DownloadStringAsync(new Uri(TwitterUri + searchTxt.Text));
            wc.DownloadStringCompleted += wc_DownloadStringCompleted;
        }&lt;/pre&gt;
&lt;p&gt;Since everything is asynchronous in Silverlight we need to listen for  the DownloadStringCompleted event. The event will have two parameters  and one of them will contain the information that holds what we are  after.&lt;/p&gt;
&lt;p&gt;You will need to reference the System.Xml.Linq under the .NET tab and  the SyndicationFeed class. The Assembly that contains the  SyndicationFeed can be found at C:\Program Files (x86)\Microsoft  SDKs\Silverlight\v4.0\Libraries\Client and select the  System.ServiceModel.Syndication.dll.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var xdoc = XDocument.Parse(e.Result);
            var feed = SyndicationFeed.Load(xdoc.CreateReader());
            if(feed.Items.Count()==0)
            {
                MessageBox.Show("No Results,Try Again");
                return;
            }

            var items = from item in feed.Items
                        select new TwitterItem()
                                   {
                                       AuthorName=item.Authors.First().Name,
                                       AuthorUri=item.Authors.First().Uri,
                                       Published=item.PublishDate.DateTime,
                                       ImageUri=(from img in item.Links
                                                where img.MediaType=="image/png"
                                                select img).First().Uri,
                                    Title=item.Title.Text

                                   };

            foreach (var twitterItem in items)
            {
                _twitterItems.Add(twitterItem);
            }

        }&lt;/pre&gt;
&lt;p&gt;We use the XDocument class to parse the results that were downloaded,  load up the XML and check the items count. If the items count is zero  we know twitter did not find anything with that search query and we  display a "No Results..." message. If results were found we use a LINQ  query to loop through the nodes and add them to our  ObservableCollection.&lt;/p&gt;
&lt;p&gt;Now that parsing is out of the way and done, we have one more step which is to bind the ListBox to the _twitterItems.&lt;/p&gt;
&lt;p&gt;In our MainPage constructor add this line&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;twitterListBox.ItemsSource = _twitterItems;&lt;/pre&gt;
&lt;p&gt;Debug the program, put any search string you want, click Search and you should see an organized list of feed items.&lt;/p&gt;
&lt;p&gt;Onwards to create the ChildWindow Popup. Right click on the Project  in the Solution Explorer--&amp;gt;Add--&amp;gt;New Item--&amp;gt;Silverlight Child  Window. Name it TwitterInformation and have it look like this&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;&amp;lt;controls:ChildWindow x:Class="TwitterInformation"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
           Title="More Information"&amp;gt;
    &amp;lt;Grid x:Name="LayoutRoot" Margin="2"&amp;gt;
        &amp;lt;Grid.RowDefinitions&amp;gt;
            &amp;lt;RowDefinition  Height="Auto"/&amp;gt;
            &amp;lt;RowDefinition Height="Auto" /&amp;gt;
        &amp;lt;/Grid.RowDefinitions&amp;gt;
        &amp;lt;Grid.ColumnDefinitions&amp;gt;
            &amp;lt;ColumnDefinition Width="Auto"/&amp;gt;
            &amp;lt;ColumnDefinition/&amp;gt;
        &amp;lt;/Grid.ColumnDefinitions&amp;gt;
        &amp;lt;Image Source="{Binding ImageUri}" Grid.Column="0" Width="100" Height="100" VerticalAlignment="Top"
                HorizontalAlignment="Left"/&amp;gt;

        &amp;lt;Grid Grid.Column="1" Margin="10,5,5,10"&amp;gt;

            &amp;lt;Grid.RowDefinitions&amp;gt;
                &amp;lt;RowDefinition Height="Auto"/&amp;gt;
                &amp;lt;RowDefinition Height="Auto"/&amp;gt;
                &amp;lt;RowDefinition Height="Auto"/&amp;gt;
                &amp;lt;RowDefinition Height="Auto"/&amp;gt;
            &amp;lt;/Grid.RowDefinitions&amp;gt;
            &amp;lt;StackPanel Orientation="Horizontal" Grid.Row="0"&amp;gt;
                &amp;lt;TextBlock VerticalAlignment="Top"  TextWrapping="Wrap" Text="Name: "/&amp;gt;
                &amp;lt;TextBlock VerticalAlignment="Top" Text="{Binding AuthorName}"  TextWrapping="Wrap"/&amp;gt;
            &amp;lt;/StackPanel&amp;gt;
            &amp;lt;StackPanel Orientation="Horizontal" Grid.Row="1" x:Name="urlPanel"&amp;gt;
                &amp;lt;TextBlock VerticalAlignment="Top"  TextWrapping="Wrap" Text="URL: "/&amp;gt;
                &amp;lt;HyperlinkButton VerticalAlignment="Top"  Content="{Binding AuthorUri}" NavigateUri="{Binding AuthorUri}" TargetName="_blank"
                             /&amp;gt;
            &amp;lt;/StackPanel&amp;gt;

            &amp;lt;Grid Grid.Row="2"&amp;gt;
                &amp;lt;Grid.ColumnDefinitions&amp;gt;
                    &amp;lt;ColumnDefinition Width="Auto"/&amp;gt;
                    &amp;lt;ColumnDefinition Width="*"/&amp;gt;
                &amp;lt;/Grid.ColumnDefinitions&amp;gt;

                &amp;lt;TextBlock VerticalAlignment="Top"  Text="Title: "/&amp;gt;
                &amp;lt;TextBlock VerticalAlignment="Top" Text="{Binding Title}"  TextWrapping="Wrap" Grid.Column="1"
                            HorizontalAlignment="Left"/&amp;gt;
            &amp;lt;/Grid&amp;gt;

                 &amp;lt;StackPanel Orientation="Horizontal" Grid.Row="3"&amp;gt;
                &amp;lt;TextBlock VerticalAlignment="Top"  Text="Published: "/&amp;gt;
                &amp;lt;TextBlock VerticalAlignment="Top" Text="{Binding Published}"/&amp;gt;
            &amp;lt;/StackPanel&amp;gt;
        &amp;lt;/Grid&amp;gt;

        &amp;lt;Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" Grid.Column="1" /&amp;gt;
    &amp;lt;/Grid&amp;gt;
&amp;lt;/controls:ChildWindow&amp;gt;&lt;/pre&gt;
&lt;p&gt;TwitterInformation.xaml was designed using Expression Blend to what  looked good so there is no "Walk through", however you're more than  welcome to design what you want. As long as for each item you want to  show you use the {Binding Name_Of_Getter_In_TwitterItem_Class} syntax.  For example: maybe you want to have the Title as a Button so you could  do something like this&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;TextBlock VerticalAlignment="Top"  Text="Title: "/&amp;gt;
&amp;lt;Button Content="{Binding Title}"  /&amp;gt;&lt;/pre&gt;
&lt;p&gt;Back to the MainPage.xaml. Wire a SelectionChanged event on our ListBox&lt;/p&gt;
&lt;pre class="brush:xml"&gt;&amp;lt;ListBox x:Name="twitterListBox"  SelectionChanged="twitterListBox_SelectionChanged"&amp;gt;&lt;/pre&gt;
&lt;p&gt;Now in our MainPage.Xaml.cs&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private void twitterListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var moreInfo = new TwitterInformation();
            moreInfo.DataContext = twitterListBox.SelectedItem;
            moreInfo.Show();
        }&lt;/pre&gt;
&lt;p&gt;We instantiate the TwitterInformation class and pass to the  DataContext what the item selected was. This will allow us to bind the  variables we want for display.&lt;br /&gt; Run the application. That's it your own simple Twitter App.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/bvg-68rR9wm9I_MlrGT38LbcY7s/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bvg-68rR9wm9I_MlrGT38LbcY7s/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/bvg-68rR9wm9I_MlrGT38LbcY7s/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/bvg-68rR9wm9I_MlrGT38LbcY7s/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/smj8Pha2Q6U" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/smj8Pha2Q6U/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Reading-a-RSS-feed-in-Silverlight-using-SyndicationFeed.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=61d33f51-0674-483c-bd67-e544e9b62e13</guid>
      <pubDate>Mon, 03 Jan 2011 21:53:00 -0700</pubDate>
      <category>Silverlight</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=61d33f51-0674-483c-bd67-e544e9b62e13</pingback:target>
      <slash:comments>1</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=61d33f51-0674-483c-bd67-e544e9b62e13</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Reading-a-RSS-feed-in-Silverlight-using-SyndicationFeed.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=61d33f51-0674-483c-bd67-e544e9b62e13</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=61d33f51-0674-483c-bd67-e544e9b62e13</feedburner:origLink></item>
    <item>
      <title>Bat Escape XNA-Part 1 of 2</title>
      <description>&lt;p&gt;
&lt;p&gt;Inspired by the Helicopter game,&amp;nbsp; the objective of bat escape is to  navigate the cave terrain and avoid the obstacles coming towards the  bat.&amp;nbsp; The 2D terrain and the obstacle positions are randomly generated.&lt;a href="http://exhd.com/articles/assets/BatEscapeFull.zip"&gt; Click to download the full source code and assets&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The tutorial is divided into two parts. The first part creates the  minimal functionality and the second part ties everything together.&lt;/p&gt;
&lt;p&gt;A video of what the full game will look:&lt;/p&gt;
&lt;div align="center" style="padding:10px;"&gt;[youtube:I3kdoT_hedo]&lt;/div&gt;

&lt;p&gt;&lt;img class="mceWPmore" title="More..." src="http://exhd.com/articles/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /&gt;Start with creating a Bat class. The Bat class will need to keep track of the position, color data when we do&lt;a href="http://exhd.com/articles/windows-phone/detecting-collision-multiple-objects-xna/"&gt; pixel-by pixel collision&lt;/a&gt;,  two textures, and a Boolean that determines if the bat is in flight or  descend mode to show the appropriate asset.&amp;nbsp;&amp;nbsp; The bat class can be used  in many different games so consider it as a "Game Component" and so  implement the DrawableGameComponent.&amp;nbsp; The easiest rule to determine  whether to implement the DrawableGameComponent class is: if the object  being created is well contained that if dropped into any other game will  just work out of the box with minimal code change then it is a good  candidate.&lt;/p&gt;
&lt;p&gt;So in our Bat class, the variables we need are&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;       private SpriteBatch _spriteBatch;

        private Texture2D _batTexture;
        private Texture2D _batUpTexture;

        public Vector2 Position { get; set; }

        private readonly Vector2 _startPosition;
        //keeps track of when we in flight mode or descending mode and switches the textures
        private bool _upThrust;

        private Color[] _batColorData;
        private Color[] _batUpColorData;&lt;/pre&gt;
&lt;p&gt;The constructor is where we learn about the position of the bat.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public Bat(Game game, Vector2 position)
            : base(game)
        {

            Position = position;
            _startPosition = position;

        }&lt;/pre&gt;
&lt;p&gt;Load the assets which are located in the Assets folder&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;          protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(Game.GraphicsDevice);

             _batTexture = Game.Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/1");
            _batColorData = new Color[_batTexture.Width * _batTexture.Height];
            _batTexture.GetData(_batColorData);

            _batUpTexture = Game.Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/2");
            _batUpColorData = new Color[_batUpTexture.Width * _batUpTexture.Height];
            _batUpTexture.GetData(_batUpColorData);

            base.LoadContent();
        }&lt;/pre&gt;
&lt;p&gt;The bat will fly and descend, so create a Upthrust and DownThrust  methods. To make the bat as realistic as possible we simulate fake  gravity. The bat will fly up at a much slower rate than the descend.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public void UpThrust(GameTime gameTime)
        {
           _upThrust = true;
            Position -= new Vector2(0, .16f) * (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        }
        public void DownThrust(GameTime gameTime)
        {
            _upThrust = false;
            Position += new Vector2(0, .3f) * (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        }&lt;/pre&gt;
&lt;p&gt;In the future when we determine if the bat collided with any walls or  obstacles we need a way to get the color data, the width and height of  the texture.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public Vector2 GetBatWidthAndHeight()
        {
            return new Vector2(_upThrust?_batUpTexture.Width : _batTexture.Width , _upThrust ? _batUpTexture.Height : _batTexture.Height);
        }
        public Color[] ColorData()
        {
            return _upThrust ? _batUpColorData : _batColorData;
        }&lt;/pre&gt;
&lt;p&gt;We will also need&amp;nbsp; a method that will reset the position of the bat when it crashes.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;       public void ResetPosition()
        {
            Position = _startPosition;
        }&lt;/pre&gt;
&lt;p&gt;All that is left is to draw the assets.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;       public override void Draw(GameTime gameTime)
        {
            _spriteBatch.Begin();
            _spriteBatch.Draw(_upThrust ? _batUpTexture : _batTexture, Position, Color.White);
           _spriteBatch.End();
        }&lt;/pre&gt;
&lt;p&gt;If the bat is currently in flight then the _batUpTexture will be returned otherwise the normal descending texture.&lt;/p&gt;
&lt;p&gt;Go back to the Game1 class&lt;/p&gt;
&lt;p&gt;Create a Bat variable&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private Bat _bat;&lt;/pre&gt;
&lt;p&gt;Add the Bat component in our constructor&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;       public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            _graphics.PreferredBackBufferHeight = 480;
            _graphics.PreferredBackBufferWidth = 800;
            _graphics.IsFullScreen = true;
            _graphics.ApplyChanges();
            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            _bat = new Bat(this, new Vector2(100, 200));
            Components.Add(_bat);

        }&lt;/pre&gt;
&lt;p&gt;So our bat will start out at (100, 200) and every time we call ResetPosition() (100,200) will be returned.&lt;/p&gt;
&lt;p&gt;Create a DetectTouch Method that will keep track&amp;nbsp; of the users' touch. If&amp;nbsp; a touch is detected the bat flies otherwise descend.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;      private void DetectTouch(GameTime gameTime)
        {

            var touches = TouchPanel.GetState();
            if (touches.Count &amp;gt; 0 &amp;amp;&amp;amp; touches[0].State == TouchLocationState.Moved)
            {
                _bat.UpThrust(gameTime);
            }
            else
                _bat.DownThrust(gameTime);

        }&lt;/pre&gt;
&lt;p&gt;In the Update method call the DetectTouch Method.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        protected override void Update(GameTime gameTime)
       &amp;nbsp;{
          &amp;nbsp;// Allows the game to exit
          if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                Exit();

            }
           DetectTouch(gameTime);

        }
&lt;/pre&gt;
&lt;p&gt;Debug the game, The bat will quickly fall off the screen so keep  pressing the left mouse button until it is back on the screen. Nothing  is preventing the bat from flying up or descending indefinitely, that  will be fixed in Part 2 of the tutorial. For now we are done with the  bat class. Next up, creating the terrain.&lt;/p&gt;
&lt;p&gt;Create a terrain class and rewatch the video. Notice when the top  wall is decreasing in height, the bottom wall is increasing and vice  versa. So we need to keep track of the Bottom wall and the top wall  positions and increase or decrease the height.&lt;/p&gt;
&lt;p&gt;Sometimes the terrain is smooth and others times the terrain is  jagged so a hint to an element of randomness so a random variable is  needed.&amp;nbsp; Realize there could be different phone sizes later and so we  need to determine how many walls to draw on the screen.&lt;/p&gt;
&lt;p&gt;A texture variable is also needed, and notice that there is a range that the top and bottom wall decrease and increase by.&lt;/p&gt;
&lt;p&gt;To simplify this concept we will use a draw stick that will be used to guide the terrain creation.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public Texture2D WallTexture { get; private set; }

        private const int DrawStickYstart = 80;
        private const int TopStartY = -40;
        private const int BottomStartY = 400;

        private readonly List&amp;lt;Vector2&amp;gt; _bottomWallVectorList;
        private readonly List&amp;lt;Vector2&amp;gt; _topWallVectorList;

        private readonly int _totalToDraw;
        private const int StepSpeed = 60;
        private float _range;
        private float _yspeed;
        private readonly int _amountPerScreen;
        private readonly Random _random = new Random();

        private Vector2 _drawPosition;
        private readonly Texture2D _drawStick;
&lt;/pre&gt;
&lt;p&gt;The wall is 32*120.&amp;nbsp; The top wall can be pushed or pulled by about 40  pixels so it will be drawn at (0,-40) and the bottom wall will be drawn  at (0,400).&amp;nbsp; If the top wall moves down by 40, it will be (0,0) and the  height will be 120. If the bottom wall gets pulled up then it will be  (0,360).&lt;/p&gt;
&lt;p&gt;&lt;a href="http://exhd.com/articles/wp-content/uploads/2010/12/smallStick.png"&gt;&lt;img class="aligncenter size-full wp-image-175" title="smallStick" src="http://exhd.com/articles/wp-content/uploads/2010/12/smallStick.png" alt="" width="32" height="120" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now for the constructor&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public Terrain(Texture2D wallTexture, Viewport view,Texture2D drawStick)
        {
            WallTexture = wallTexture;
            _amountPerScreen = view.Width / WallTexture.Width;
            _totalToDraw = _amountPerScreen + 1;

            _topWallVectorList = new List&amp;lt;Vector2&amp;gt;();
            _bottomWallVectorList = new List&amp;lt;Vector2&amp;gt;();

            ResetTerrain();

            _drawStick = drawStick;

            _drawPosition = new Vector2(768, 80);

            _range = _random.Next(-40, 40);
            _yspeed = _range / _random.Next(1, StepSpeed);

        }
&lt;/pre&gt;
&lt;p&gt;We figure out how many blocks need to be drawn on the screen and  increase that by 1. Why 1? To continously scroll we need one wall out of  view to be used to change the x-axis scroll and the Y-axis shift.&lt;/p&gt;
&lt;p&gt;The range variable, restricts the movement up or down by 40. the  _yspeed variable determines the aggressives of the y impulse. For  example,&amp;nbsp; If&amp;nbsp; the range came out to be 40 and the step value was 60 then  with each update the stick will move down by 0.666 pixel. If the range  came out to be -36 and the step value was 2. The stick will move up by  -18 pixels per frame and a spiked terrain will be created.&lt;/p&gt;
&lt;p&gt;We need a method to draw our terrain (ResetTerrain()), and a way to  access the positions of the wall for collision (GetTerrainVectors()).  The draw  method draws the assets.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        public void ResetTerrain()
        {
            _bottomWallVectorList.Clear();
            _topWallVectorList.Clear();
            for (var i = 0; i &amp;lt; _totalToDraw; i++)
            {
                 //first wall will be (0,-40), second will be (32 x 1, -40), third will be (32 x 2, -40)
                _topWallVectorList.Add(new Vector2(WallTexture.Width * i, TopStartY));
                _bottomWallVectorList.Add(new Vector2(WallTexture.Width * i, BottomStartY));

            }

        }
        public List&amp;lt;Vector2&amp;gt; GetTerrainVectors()
        {
            return new List&amp;lt;Vector2&amp;gt;(_bottomWallVectorList.Concat(_topWallVectorList));
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(_drawStick, _drawPosition, Color.YellowGreen);
            foreach (var wallQuee in _topWallVectorList)
            {
                spriteBatch.Draw(WallTexture, wallQuee, Color.White);
            }
            foreach (var wallVector in _bottomWallVectorList)
            {
                spriteBatch.Draw(WallTexture, wallVector, Color.White);
            }
        }&lt;/pre&gt;
&lt;p&gt;Focus now on the update method which will draw the terrain. We need  to scroll by a certain value in the x-axis. The scrolling&amp;nbsp; happens from  right to left so when the wall goes off the screen it will have a  negative x value. We remove it and add another wall.&lt;/p&gt;
&lt;p&gt;We also need to update the Y-position value of each wall we add by  the amount the stick has moved.&amp;nbsp; Finally, we need to determine if the  stick strayed off the range, if it did then we reset it back and  randomize to the opposite way.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; public void Update(GameTime gameTime)
        {
            //the amount we scroll by each update
            var scroll = (float)gameTime.ElapsedGameTime.TotalSeconds * 100;
            //loop through all the walls we have
            for (var i = 0; i &amp;lt; _topWallVectorList.Count; i++)
            {
                var topWall = _topWallVectorList[i];
                //scroll the wall by that much amount
                topWall.X -= scroll;
                _topWallVectorList[i] = topWall;

                //since we have equal walls use same loop
                var bottomWall = _bottomWallVectorList[i];
                bottomWall.X -= scroll;
                _bottomWallVectorList[i] = bottomWall;
                //so if the X position becomes -32 (Width of the wall, we know it is completely off the screen
                if (_topWallVectorList[i].X &amp;lt; -WallTexture.Width)
                {
                    //get the last position of the right most wall
                    var lastPos = _topWallVectorList[_topWallVectorList.Count - 1].X;
                    //find out how much our stick moved by.
                    var diffToAdd = _drawPosition.Y - DrawStickYstart;
                    //add the new walls
                    _topWallVectorList.Add(new Vector2(lastPos + WallTexture.Width, TopStartY + diffToAdd));
                    _bottomWallVectorList.Add(new Vector2(lastPos + WallTexture.Width, BottomStartY + diffToAdd));

                    //remove the walls that went off
                    _bottomWallVectorList.RemoveAt(i);
                    _topWallVectorList.RemoveAt(i);
                    //decrement to not skip a wall on the next loop
                    i--;
                }

            }
            //increase the stick position
            _drawPosition.Y += _yspeed;

            //stick is drawn at (768,80) so 40+80=120, 80-40=40. 40 is our range
            if (_drawPosition.Y &amp;gt;= 120)
            {
                 //if we are at positive then we need to go back to 80
                _range = _random.Next(-40, -1);
                _yspeed = _range / _random.Next(1, StepSpeed);
                _drawPosition.Y = 120;
            }
            if (_drawPosition.Y &amp;lt;= 40)
            {
                 //if it is less than 40 then we need to go the other way
                _range = _random.Next(1, 40);
                _yspeed = _range / _random.Next(1, StepSpeed);
                _drawPosition.Y = 40;
            }

        }&lt;/pre&gt;
&lt;p&gt;Back to the Game1 class to hook things up.&lt;/p&gt;
&lt;p&gt;Create a Terrain variable&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private Terrain _terrain;&lt;/pre&gt;
&lt;p&gt;in the LoadContent method load the assets&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            var terrainTexture = Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/smallStick");
            _terrain = new Terrain(terrainTexture, GraphicsDevice.Viewport,Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/drawStick"));
         }&lt;/pre&gt;
&lt;p&gt;The update method should look like&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            DetectTouch(gameTime);
            _terrain.Update(gameTime); //this got added
            base.Update(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;Go to the draw method and add&amp;nbsp; _terrain.Draw(_spriteBatch);&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            _spriteBatch.Begin();

             _terrain.Draw(_spriteBatch);//this got added
            _spriteBatch.End();
            base.Draw(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;Run the game and watch the the draw stick relative to the terrain.  Part 2, will setup the collision system, create the obstacles, implement  the game screens. So stay tuned.&lt;/p&gt;
&lt;p&gt;Below is all the code:&lt;/p&gt;
&lt;p&gt;The Bat Class&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace BatEscape
{
    class Bat : DrawableGameComponent
    {

        private SpriteBatch _spriteBatch;
        private Texture2D _batTexture;

        private Texture2D _batUpTexture;
        public Vector2 Position { get; set; }

        private readonly Vector2 _startPosition;

        private bool _upThrust;

        private Color[] _batColorData;
        private Color[] _batUpColorData;

        public Bat(Game game, Vector2 position)
            : base(game)
        {

            Position = position;
            _startPosition = position;

        }
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(Game.GraphicsDevice);

             _batTexture = Game.Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/1");
            _batColorData = new Color[_batTexture.Width * _batTexture.Height];
            _batTexture.GetData(_batColorData);

            _batUpTexture = Game.Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/2");
            _batUpColorData = new Color[_batUpTexture.Width * _batUpTexture.Height];
            _batUpTexture.GetData(_batUpColorData);

            base.LoadContent();
        }
        public void UpThrust(GameTime gameTime)
        {
           _upThrust = true;
            Position -= new Vector2(0, .16f) * (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        }
        public void DownThrust(GameTime gameTime)
        {
            _upThrust = false;
            Position += new Vector2(0, .3f) * (float)gameTime.ElapsedGameTime.TotalMilliseconds;

        }
        public Vector2 GetBatWidthAndHeight()
        {
            return new Vector2(_upThrust?_batUpTexture.Width : _batTexture.Width , _upThrust ? _batUpTexture.Height : _batTexture.Height);
        }
        public Color[] ColorData()
        {
            return _upThrust ? _batUpColorData : _batColorData;
        }
        public void ResetPosition()
        {
            Position = _startPosition;
        }
       public override void Draw(GameTime gameTime)
        {
            _spriteBatch.Begin();
            _spriteBatch.Draw(_upThrust ? _batUpTexture : _batTexture, Position, Color.White);
           _spriteBatch.End();
        }

    }
}&lt;/pre&gt;
&lt;p&gt;The Terrain Class&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace BatEscape
{
    class Terrain
    {

        public Texture2D WallTexture { get; private set; }

        private const int DrawStickYstart = 80;
        private const int TopStartY = -40;
        private const int BottomStartY = 400;

        private readonly List&amp;lt;Vector2&amp;gt; _bottomWallVectorList;
        private readonly List&amp;lt;Vector2&amp;gt; _topWallVectorList;

        private readonly int _totalToDraw;
        private const int StepSpeed = 60;
        private float _range;
        private float _yspeed;
        private readonly int _amountPerScreen;
        private readonly Random _random = new Random();

        private Vector2 _drawPosition;
        private readonly Texture2D _drawStick;

        public Terrain(Texture2D wallTexture, Viewport view,Texture2D drawStick)
        {
            WallTexture = wallTexture;
            _amountPerScreen = view.Width / WallTexture.Width;

            _topWallVectorList = new List&amp;lt;Vector2&amp;gt;();
            _bottomWallVectorList = new List&amp;lt;Vector2&amp;gt;();

            _totalToDraw = _amountPerScreen + 1;

            ResetTerrain();

            _drawStick = drawStick;
            _drawPosition = new Vector2(768, 80);

            _range = _random.Next(-40, 40);
            _yspeed = _range / _random.Next(1, StepSpeed);

        }

        public void Update(GameTime gameTime)
        {
            var scroll = (float)gameTime.ElapsedGameTime.TotalSeconds * 100;

            for (var i = 0; i &amp;lt; _topWallVectorList.Count; i++)
            {
                var topWall = _topWallVectorList[i];
                topWall.X -= scroll;
                _topWallVectorList[i] = topWall;

                //since we have equal walls use same loop
                var bottomWall = _bottomWallVectorList[i];
                bottomWall.X -= scroll;
                _bottomWallVectorList[i] = bottomWall;

                if (_topWallVectorList[i].X &amp;lt; -WallTexture.Width)
                {
                    //get the last position
                    var lastPos = _topWallVectorList[_topWallVectorList.Count - 1].X;
                    var diffToAdd = _drawPosition.Y - DrawStickYstart;

                    _topWallVectorList.Add(new Vector2(lastPos + WallTexture.Width, TopStartY + diffToAdd));
                    _bottomWallVectorList.Add(new Vector2(lastPos + WallTexture.Width, BottomStartY + diffToAdd));
                    _bottomWallVectorList.RemoveAt(i);
                    _topWallVectorList.RemoveAt(i);
                    i--;
                }

            }
            _drawPosition.Y += _yspeed;

            if (_drawPosition.Y &amp;gt;= 120)
            {
                _range = _random.Next(-40, -1);
                _yspeed = _range / _random.Next(1, StepSpeed);
                _drawPosition.Y = 120;
            }
            if (_drawPosition.Y &amp;lt;= 40)
            {
                _range = _random.Next(1, 40);
                _yspeed = _range / _random.Next(1, StepSpeed);
                _drawPosition.Y = 40;
            }

        }
        public void ResetTerrain()
        {
            _bottomWallVectorList.Clear();
            _topWallVectorList.Clear();
            for (var i = 0; i &amp;lt; _totalToDraw; i++)
            {
                _topWallVectorList.Add(new Vector2(WallTexture.Width * i, TopStartY));
                _bottomWallVectorList.Add(new Vector2(WallTexture.Width * i, BottomStartY));

            }

        }
        public List&amp;lt;Vector2&amp;gt; GetTerrainVectors()
        {
            return new List&amp;lt;Vector2&amp;gt;(_bottomWallVectorList.Concat(_topWallVectorList));
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(_drawStick, _drawPosition, Color.YellowGreen);
            foreach (var wallQuee in _topWallVectorList)
            {
                spriteBatch.Draw(WallTexture, wallQuee, Color.White);
            }
            foreach (var wallVector in _bottomWallVectorList)
            {
                spriteBatch.Draw(WallTexture, wallVector, Color.White);
            }
        }
    }
}&lt;/pre&gt;
&lt;p&gt;The Game 1 class&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;namespace BatEscape
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager _graphics;
        SpriteBatch _spriteBatch;
        private Bat _bat;
        private Terrain _terrain;
        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            _graphics.PreferredBackBufferHeight = 480;
            _graphics.PreferredBackBufferWidth = 800;
            _graphics.IsFullScreen = true;
            _graphics.ApplyChanges();
            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            _bat = new Bat(this, new Vector2(100, 200));
            Components.Add(_bat);

        }

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            var terrainTexture = Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/smallStick");
            _terrain = new Terrain(terrainTexture, GraphicsDevice.Viewport, Content.Load&amp;lt;Texture2D&amp;gt;(@"Assets/drawStick"));
        }

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            DetectTouch(gameTime);
            _terrain.Update(gameTime);
            base.Update(gameTime);
        }
        private void DetectTouch(GameTime gameTime)
        {

            var touches = TouchPanel.GetState();
            if (touches.Count &amp;gt; 0 &amp;amp;&amp;amp; touches[0].State == TouchLocationState.Moved)
            {
                _bat.UpThrust(gameTime);
            }
            else
                _bat.DownThrust(gameTime);

        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            _spriteBatch.Begin();
            _terrain.Draw(_spriteBatch);
            _spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}&lt;/pre&gt;
&lt;/p&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/MeMElCnIbkgu1kv3ARr9mYpK45g/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/MeMElCnIbkgu1kv3ARr9mYpK45g/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/MeMElCnIbkgu1kv3ARr9mYpK45g/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/MeMElCnIbkgu1kv3ARr9mYpK45g/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/HA7bfPGxp9U" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/HA7bfPGxp9U/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Bat-Escape-XNA-Part-1-of-2.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=a429000c-0961-41ae-870a-a5b71dacf765</guid>
      <pubDate>Tue, 28 Dec 2010 21:48:00 -0700</pubDate>
      <category>Windows Phone</category>
      <category>XNA</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=a429000c-0961-41ae-870a-a5b71dacf765</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=a429000c-0961-41ae-870a-a5b71dacf765</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Bat-Escape-XNA-Part-1-of-2.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=a429000c-0961-41ae-870a-a5b71dacf765</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=a429000c-0961-41ae-870a-a5b71dacf765</feedburner:origLink></item>
    <item>
      <title>Saving and loading Game Data in XNA </title>
      <description>&lt;p&gt;
&lt;p&gt;To learn how to save and load data in XNA, a simple cat and mouse  game is created where the objective is to catch a square and every 5  points the time decreases by 100 milliseconds. The high score is drawn  at the top right corner and loads the highest amount of squares that a  user caught. We save and load the data via the IsolatedStorageFile and  use the XmlSerialize to serialize and deserialize. &lt;a href="http://exhd.com/blog/assets/SavingGameScore.zip"&gt;Click to Download the project&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Notice the high score persists with all restarts:&lt;/p&gt;
&lt;div align="center" style="padding:10px;"&gt;[youtube:EzHSCnST5SI]&lt;/div&gt;

&lt;p&gt;&lt;img class="mceWPmore" title="More..." src="http://exhd.com/articles/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /&gt;&lt;br /&gt; The focus will be on Saving/Loading data. Add a reference to&amp;nbsp; System.Xml.Serialization.&lt;/p&gt;
&lt;p&gt;A struct will house the data.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public struct SaveGameData
    {
        public int HighScore;
        //Can include things like PlayerName, Options etc...
    }
&lt;/pre&gt;
&lt;p&gt;2 Variables are needed- a SaveGameData variable and a file name (arbitrarily chosen)&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private SaveGameData _gameData;
 private const string FileName = "GameData.exhd";
&lt;/pre&gt;
&lt;p&gt;To save the data we access the location of the file.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private void SaveData()
{
   using(var storage=IsolatedStorageFile.GetUserStoreForApplication())
     {
       using (var stream = storage.OpenFile(FileName, FileMode.OpenOrCreate))
        {
          var serializer = new XmlSerializer(typeof (SaveGameData));//The struct
           serializer.Serialize(stream, _gameData);
         }
     }
}
&lt;/pre&gt;
&lt;p&gt;We accessed the storage location of the file, opened or created one  with the file name had it not existed and serialized the data via  XmlSerializer to save it.&amp;nbsp; Notice the use of the&amp;nbsp; "using statement" will  automatically call dispose/close on both the storage and stream  variables, otherwise we would have received this message:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;An unhandled exception of type  'System.IO.IsolatedStorage.IsolatedStorageException' occurred in  mscorlib.dll. Additional information: Operation not permitted on  IsolatedStorageFileStream.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;To load our data, check to make sure the&amp;nbsp; file name exists otherwise  there is nothing to load yet, if the file exisits we Deserialize the  stream back into our struct variable.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private void LoadHighScore()
{
   using(var storage=IsolatedStorageFile.GetUserStoreForApplication())
    {
     if (storage.FileExists(FileName))
       {
         using (var stream = storage.OpenFile(FileName, FileMode.Open))
            {
               var xml = new XmlSerializer(typeof (SaveGameData));
                 _gameData = (SaveGameData) xml.Deserialize(stream);
             }
       }
    }
}
&lt;/pre&gt;
&lt;p&gt;That is all saving and loading data. &lt;a href="http://exhd.com/blog/assets/SavingGameScore.zip"&gt;Download the project and test it out.&lt;/a&gt;&lt;/p&gt;
&lt;/p&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/H_KneCNfB3EEvxwB_qckxtD-cRg/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/H_KneCNfB3EEvxwB_qckxtD-cRg/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/H_KneCNfB3EEvxwB_qckxtD-cRg/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/H_KneCNfB3EEvxwB_qckxtD-cRg/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/igdeW7DG24s" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/igdeW7DG24s/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Saving-and-loading-Game-Data-in-XNA-.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=c6af33ed-6ecc-4adb-8828-57400fba2982</guid>
      <pubDate>Thu, 23 Dec 2010 21:46:00 -0700</pubDate>
      <category>Windows Phone</category>
      <category>XNA</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=c6af33ed-6ecc-4adb-8828-57400fba2982</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=c6af33ed-6ecc-4adb-8828-57400fba2982</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Saving-and-loading-Game-Data-in-XNA-.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=c6af33ed-6ecc-4adb-8828-57400fba2982</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=c6af33ed-6ecc-4adb-8828-57400fba2982</feedburner:origLink></item>
    <item>
      <title>Dodge and Run XNA for Windows Phone - A simple Frogger clone. Tutorial &amp; Source Code</title>
      <description>&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The purpose of Dodge and Run is to avoid the minivans by moving the F1 car around. It can be turned into a Frogger clone or &lt;a rel="nofollow" href="http://www.addictinggames.com/kamikazerace.html"&gt;kamikaze race &lt;/a&gt;and  alot of other games.&amp;nbsp; The purpose of this tutorial is to create a  scrolling 2D background,detect collision between the car and the  minivans, and move around a car using the TouchPanel.GetState().&lt;/p&gt;
&lt;p&gt;&lt;a href="http://exhd.com/blog/assets/DodgeAndRun.zip"&gt;Click here to download the project/Assets.&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The video:&lt;/p&gt;
&lt;div align="center" style="padding:10px;"&gt;[youtube:NdDImSOIWyQ]&lt;/div&gt;

&lt;p&gt;&lt;img class="mceWPmore" title="More..." src="http://exhd.com/articles/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" alt="" /&gt;Start out by creating a MiniVan class which will be for the simulated cars.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;class MiniCar
    {
        public Texture2D MiniCarTexture{get;private set;}
        private Vector2 _miniCarVelocity;
        public Vector2 MiniCarPosition;
        private GraphicsDevice _graphics;
        public static Random Random = new Random();

        public MiniCar(Texture2D carTexture,Vector2 carPosition,GraphicsDevice graphics)
        {
            MiniCarTexture = carTexture;
            MiniCarPosition = carPosition;
            _graphics = graphics;
            RandomizeVelocity();
        }
        public void Update(GameTime gameTime)
        {
            MiniCarPosition -= _miniCarVelocity;
            if (MiniCarPosition.Y &amp;lt; -MiniCarTexture.Height)
            {
                MiniCarPosition.Y = _graphics.Viewport.Height + MiniCarTexture.Height;
            }
        }
        public void RandomizeVelocity()
        {
            _miniCarVelocity = new Vector2(0, Random.Next(4, 10));
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(MiniCarTexture, MiniCarPosition, Color.White);
        }
    }&lt;/pre&gt;
&lt;p&gt;The RandomizeVelocity() method will change the velocity of the car  every 5 seconds (Done in the Game1 class). We want to travel forwards/up  so subtract the velocity from the position. Top of the screen is (0,0),  Bottom is (0,800). We then check to see if the car is off the screen,  if it is then we reset it back down.&lt;/p&gt;
&lt;p&gt;Create a ScrollBackground class. The ScrollBackground class will be  in charge of scrolling our road texture to simulate movement.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; class ScrollBackground
    {
        private readonly Texture2D _scrollTexture;
        private Vector2 _scrollPosition;

        public ScrollBackground(Texture2D texture)
        {
            _scrollTexture = texture;
        }

        public void Update(GameTime gameTime)
        {
            _scrollPosition.Y += (float)gameTime.ElapsedGameTime.TotalSeconds * 100;
            _scrollPosition.Y = _scrollPosition.Y % _scrollTexture.Height;
        }
        public void Draw(SpriteBatch spriteBatch,Color color)
        {
            if(_scrollPosition.Y &amp;gt;0)
            {
                spriteBatch.Draw(_scrollTexture, new Vector2(0, _scrollPosition.Y - _scrollTexture.Height), color);
            }
            spriteBatch.Draw(_scrollTexture, _scrollPosition, color);
        }
     }&lt;/pre&gt;
&lt;p&gt;Focus on the Update and Draw methods.&amp;nbsp; In the update method the  texture is moved by about 3.33 pixels per second (Windows Phone runs at  33 FPS). The second line uses the modulus operator (The Percent sign),  to return the remainder. As long as the _scrollPosition.Y is less than  height the remainder will equal to the _scrollPosition.Y value (3.33%800  = 3.33, 6.66%800=6.66, etc..). However, when the _scrollPosition.Y  reaches 800 the remainder is zero and _scrollPosition.Y gets set back to  0 and the loop is complete. Since we are moving vertically no need to  worry about the x-axis.&lt;/p&gt;
&lt;p&gt;In the Draw Method once our _scrollPosition.Y becomes greater than  zero, we draw another road above. To understand why, comment out the if  statement once the tutorial is finished.&lt;/p&gt;
&lt;p&gt;Back to the Game1 class. Create the variables that will be used.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;        private ScrollBackground _scrollBackground;
        private Texture2D _f1Texture;
        private List&amp;lt;MiniCar&amp;gt; _miniCars;
        private Vector2 _f1Position;
        private Vector2 _fingerPosition; //used for touch to see where the user finger is
        private float _timeSinceLastUpdate;
        private bool _collision;&lt;/pre&gt;
&lt;p&gt;Full screen and lock the height and width. Place this code in the Game1 Constructor&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;            _graphics.PreferredBackBufferHeight = 800;
            _graphics.PreferredBackBufferWidth = 480;
            _graphics.IsFullScreen = true;
            _graphics.ApplyChanges();&lt;/pre&gt;
&lt;p&gt;Set the F1 car position and the Finger position in the Initialize method&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void Initialize()
        {
            _f1Position = _fingerPosition = new Vector2(120, 600);
            base.Initialize();
        }&lt;/pre&gt;
&lt;p&gt;Load the content and create 6 minivans for the 6 lanes. The position numbers were taken from the Photoshop file.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _scrollBackground=new ScrollBackground(Content.Load&amp;lt;Texture2D&amp;gt;("roadAsphalt"));
            _f1Texture = Content.Load&amp;lt;Texture2D&amp;gt;("f1car");
            _miniCars = new List&amp;lt;MiniCar&amp;gt;
                            {
                                new MiniCar(Content.Load&amp;lt;Texture2D&amp;gt;("miniCar"),  new Vector2(220, 100),
                                            GraphicsDevice),
                                new MiniCar(Content.Load&amp;lt;Texture2D&amp;gt;("miniCar"),  new Vector2(285, 300),
                                            GraphicsDevice),
                                 new MiniCar(Content.Load&amp;lt;Texture2D&amp;gt;("miniCar"), new Vector2(410, 500),
                                            GraphicsDevice),
                                 new MiniCar(Content.Load&amp;lt;Texture2D&amp;gt;("miniCar"), new Vector2(160, 700),
                                            GraphicsDevice),
                                new MiniCar(Content.Load&amp;lt;Texture2D&amp;gt;("miniCar"),  new Vector2(350, 800),
                                            GraphicsDevice),
                                new MiniCar(Content.Load&amp;lt;Texture2D&amp;gt;("miniCar"),  new Vector2(90, 200),
                                            GraphicsDevice)

                            };

        }&lt;/pre&gt;
&lt;p&gt;Draw the content on the screen&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            _spriteBatch.Begin();
            var color = _collision ? Color.Red : Color.White;
            _scrollBackground.Draw(_spriteBatch, color);
            _spriteBatch.Draw(_f1Texture, _f1Position,null, Color.White,0,new Vector2(_f1Texture.Width/2f,_f1Texture.Height/2f),1,SpriteEffects.None,0);
            foreach (var miniCar in _miniCars)
            {
                miniCar.Draw(_spriteBatch);
            }
            _spriteBatch.End();

            base.Draw(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;The _collision variable will check to see if the F1 car collided with  any minivan. If so, the background color is changed to red otherwise  keep it white.&lt;/p&gt;
&lt;p&gt;Our Update method needs to randomize the velocity of each minivan  every 5 seconds, call update on the _scrollBackground and the minivans,  detect when the user touches the screen, move the car to the desired  location and detect any collision between the F1 and minivans.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            _collision = false; //assume no collision with every update

            _timeSinceLastUpdate += (float) gameTime.ElapsedGameTime.TotalMilliseconds;

            if(_timeSinceLastUpdate&amp;gt;5000)//every 5 sec change the velocity
            {
                foreach (var miniCar in _miniCars)
                {
                    miniCar.RandomizeVelocity();
                }
                _timeSinceLastUpdate -= 5000;
            }

            _scrollBackground.Update(gameTime);//call update to scroll
            foreach (var miniCar in _miniCars)
            {
                miniCar.Update(gameTime);
            }

            _f1Position = _fingerPosition;//where the user touched
            _f1Position.X = MathHelper.Clamp(_f1Position.X, 110, 450); //Bound up the car so it doesn't escape
            _f1Position.Y = MathHelper.Clamp(_f1Position.Y, _f1Texture.Height/2f, GraphicsDevice.Viewport.Height-_f1Texture.Height/2f);

            DetectTouch();
            DetectCollision();
            base.Update(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;Rectangular collision detection will be good enough since the cars  have a rectangular shape so no need to pixel-by-pixel collision.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void DetectCollision()
        {
            //offset the Rectangle back to (0,0) since the origin of the car is half width,half heightin the draw method we need to take that in consideration,
            //otherwise the rectangle will start at (19,43)
            var f1Rect = new Rectangle((int)(_f1Position.X-_f1Texture.Width/2f), (int)(_f1Position.Y-_f1Texture.Height/2f), _f1Texture.Width, _f1Texture.Height);
            //LINQ expression
            if (_miniCars.Select(miniCar =&amp;gt; new Rectangle((int) miniCar.MiniCarPosition.X, (int) miniCar.MiniCarPosition.Y, miniCar.MiniCarTexture.Width, miniCar.MiniCarTexture.Height)).Any(miniRect =&amp;gt; f1Rect.Intersects(miniRect)))
            {
                _collision = true;

            }
        }&lt;/pre&gt;
&lt;p&gt;Now for the Touch method. Only allow one touch point (One Finger)&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void DetectTouch()
        {

            var touch = TouchPanel.GetState();
            if(touch.Count==1)
            {
                //get the position
                _fingerPosition = touch[0].Position;

            }

        }&lt;/pre&gt;
&lt;p&gt;That is it, run the game and move the F1 car with the mouse or finger.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/EdU7Ka4HM2M6gV89j_CanRfdSOg/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/EdU7Ka4HM2M6gV89j_CanRfdSOg/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/EdU7Ka4HM2M6gV89j_CanRfdSOg/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/EdU7Ka4HM2M6gV89j_CanRfdSOg/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/Rhb3fDbCGdg" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/Rhb3fDbCGdg/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Dodge-and-Run-XNA-for-Windows-Phone-A-simple-Frogger-clone-Tutorial-Source-Code.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=2a83f2b3-c3c5-4963-ad76-1bd1dc64e9c1</guid>
      <pubDate>Thu, 23 Dec 2010 21:44:00 -0700</pubDate>
      <category>Windows Phone</category>
      <category>XNA</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=2a83f2b3-c3c5-4963-ad76-1bd1dc64e9c1</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=2a83f2b3-c3c5-4963-ad76-1bd1dc64e9c1</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Dodge-and-Run-XNA-for-Windows-Phone-A-simple-Frogger-clone-Tutorial-Source-Code.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=2a83f2b3-c3c5-4963-ad76-1bd1dc64e9c1</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=2a83f2b3-c3c5-4963-ad76-1bd1dc64e9c1</feedburner:origLink></item>
    <item>
      <title>Simon Says XNA For Windows Phone-Tutorial &amp; Source Code</title>
      <description>&lt;p&gt;Simon Says XNA a game of repeating sequences of colors and the objective is to repeat the colors in the correct order after Simon is finished with showing you the sequence.You can use the mouse, a phone or a multi-touch monitor to test it out. If you just want to see the project,&lt;a href="http://exhd.com/blog/assets/SimonSaysXNA.zip"&gt; Click Here to Download The Project&lt;/a&gt;, otherwise keep reading for the tutorial.&lt;/p&gt;

&lt;p&gt;Here is a Video of the Game:&lt;/p&gt;
&lt;div align="center" style="padding:10px;"&gt;[youtube:TloBPVYeGo0]&lt;/div&gt;

&lt;a href="http://exhd.com/blog/assets/SimonSaysXNA.zip"&gt;Click to Download the Assets&lt;/a&gt;. They are located in the Assets folder.

&lt;p&gt;First thing is to lock the height and width and to full screen it.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);
            graphics.PreferredBackBufferHeight = 800;
            graphics.PreferredBackBufferWidth = 480;
            graphics.IsFullScreen = true;
            graphics.ApplyChanges();
           
        }&lt;/pre&gt;
So lets start out with getting the background and the buttons aligned. Since we have 4 buttons create a SimonButton Class.
&lt;pre class="brush:csharp"&gt; class SimonButton
    {

        public Vector2 Position { get; private set; }
        public Texture2D Texture { get; private set; }
        public Game1.ButtonColors ButtonColor { get; private set; }
        public bool LightUp{get;set;}
        private readonly SoundEffect _sound;

        public SimonButton(Texture2D texture, Vector2 position, Game1.ButtonColors buttonColor,SoundEffect sound)
        {
            Texture = texture;
            Position = position;
            ButtonColor = buttonColor;
            _sound = sound;
            LightUp=false;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(Texture, Position, LightUp ? Color.White : Color.Gray);
        }
        public void PlaySound()
        {
            _sound.Play();
        }
    }&lt;/pre&gt;
&lt;p&gt;We are keeping track of the position of the button, texture, the ButtonColor (We did not make the Enum so don't worry yet), a Lightup Boolean to determine when we should light up and the sound that gets played with each button. We have two methods--the Draw Method draws where the button is and checks the lightup Boolean. If  true we set the Color to white otherwise the color is gray which shows the button as dimmed. The PlaySound method does exactly what the name implies and plays the sound.&lt;/p&gt;

&lt;p&gt;Go back to the Game1 class.&lt;/p&gt;

&lt;p&gt;Create the variables that we will be using.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;private Texture2D _background;
private SpriteFont _scoreFont;
private SpriteFont _titleFont;
//keeps track of who is playing when
private bool _donePlaying;
//used to determine where the user is when they repeat pattern
private int _playerPosition;
//Simon has 4 Buttons
public enum ButtonColors
 {
 Red,
 Yellow,
 Blue,
 Green
 }
        private float _rateOfChange; //Rate of Change, Highest 1 Second, Lowest 250ms
        private int _score;
        private float _timeSinceLastUpdate;

        private List&amp;lt;ButtonColors&amp;gt; _simonColorsList;//List of All the Sequences
        private Queue&amp;lt;ButtonColors&amp;gt; _simonDisposableQueue; //Used to make our lives easier
        private readonly Random _random = new Random(); //Gota be random in life
        private List&amp;lt;SimonButton&amp;gt; _simonButtonClassList;//Just contains the 4 buttons
       private GameStates _gameState;//3 Game States

        private SoundEffect _failSound;
        //each game has a minimum of 3 States, PreGame (Instructions), Playing, GameOver.
        public enum GameStates
        {
            PreGame,
            Playing,
            GameOver
        } ;

        private readonly string[] _gameInstructions={"Do what Simon Says","Follow the Pattern of Lights","And Sounds",
                                           "Tap To Start"};
        private readonly string[] _gameOverInstructions={"Game Over", "Simon Wins","Tap to Restart"};
        private readonly string[] _mainInstructions = {"Simon Says","Developed by", "EXHD L.L.C."} ;

        private Rectangle _safeBounds;&lt;/pre&gt;
&lt;p&gt;For now focus on the variables that will get things on the screen.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _background = Content.Load&amp;lt;Texture2D&amp;gt;("simonBack");
            _scoreFont = Content.Load&amp;lt;SpriteFont&amp;gt;("ScoreFont");
            _titleFont = Content.Load&amp;lt;SpriteFont&amp;gt;("title");

            _simonButtonClassList = new List&amp;lt;SimonButton&amp;gt;
                                        {
                                    new SimonButton(Content.Load&amp;lt;Texture2D&amp;gt;("red"), new Vector2(260, 85),ButtonColors.Red, Content.Load&amp;lt;SoundEffect&amp;gt;("tone2")),
                                    new SimonButton(Content.Load&amp;lt;Texture2D&amp;gt;("blue"),new Vector2(260, 325),ButtonColors.Blue, Content.Load&amp;lt;SoundEffect&amp;gt;("tone4")),
                                    new SimonButton(Content.Load&amp;lt;Texture2D&amp;gt;("green"),new Vector2(15, 85),ButtonColors.Green,Content.Load&amp;lt;SoundEffect&amp;gt;("tone1")),
                                    new SimonButton(Content.Load&amp;lt;Texture2D&amp;gt;("yellow"),new Vector2(15, 325),ButtonColors.Yellow,Content.Load&amp;lt;SoundEffect&amp;gt;("tone3"))
                                };

            _failSound = Content.Load&amp;lt;SoundEffect&amp;gt;("fail");

        }&lt;/pre&gt;
&lt;p&gt;So far nothing too complicated, you may wonder how i got the position numbers from and that would be from the Photoshop file (Comes with the Project).&lt;/p&gt;

&lt;p&gt;Now onto the Draw Method&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            _spriteBatch.Begin();
            _spriteBatch.Draw(_background, Vector2.Zero, Color.White);
            DrawButtons();
            DrawScore();
            DrawTitle();
            switch (_gameState)
            {
                case GameStates.PreGame:
                    DrawPreGameInstructions();
                    break;
                case GameStates.Playing:
                    break;
                case GameStates.GameOver:
                    DrawPostGameInstructions();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            _spriteBatch.End();

            base.Draw(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;For The PreGame and GameOver state we will have different sets of instructions.&lt;/p&gt;

&lt;p&gt;Now the code for the methods&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void DrawPostGameInstructions()
        {
            for (int i = 0; i &amp;lt; _gameOverInstructions.Length; i++)
            {
                var gameOverInstruction = _gameOverInstructions[i];
                var post = _titleFont.MeasureString(gameOverInstruction);
                _spriteBatch.DrawString(_titleFont, gameOverInstruction,
                                       new Vector2((GraphicsDevice.Viewport.Width - post.X) / 2f, 550 + 30 * i), Color.White);
            }
        }

        private void DrawPreGameInstructions()
        {
            for (int i = 0; i &amp;lt; _gameInstructions.Length; i++)
            {
                var gameInstruction = _gameInstructions[i];
                var post = _titleFont.MeasureString(gameInstruction);
                _spriteBatch.DrawString(_titleFont, gameInstruction,
                                       new Vector2((GraphicsDevice.Viewport.Width - post.X) / 2f, 550+30 * i), Color.White);
            }
        }

        private void DrawTitle()
        {
            var x=0;
            for (int i = _mainInstructions.Length-1; i &amp;gt;=0; i--)
            {
                var pos = _titleFont.MeasureString(_mainInstructions[i]);
                _spriteBatch.DrawString(_titleFont, _mainInstructions[i],
                                       new Vector2(0, (GraphicsDevice.Viewport.Height-pos.Y-(30*x))), Color.Honeydew);
                x++;
            }
        }

        private void DrawButtons()
        {
            foreach (var simonButton in _simonButtonClassList)
            {
                simonButton.Draw(_spriteBatch);
            }
        }
        private void DrawScore()
        {
            _spriteBatch.DrawString(_scoreFont, string.Format("{0:000}", _score), new Vector2(212, 320), Color.Aquamarine);
        }&lt;/pre&gt;
&lt;p&gt;All the numbers (ex:550,30,212,320) were just trial and error to make it look nice.  The DrawButtons Method just loops through the list and calls the Draw Method on each SimonButton instance that we created in the LoadContent().&lt;/p&gt;

&lt;p&gt;Now you are ready to run the project and you should see the game on the screen.&lt;/p&gt;

Go to your initialize method:
&lt;pre class="brush:csharp"&gt; protected override void Initialize()
        {

            _safeBounds = new Rectangle(0, 86, 480, 469);
            base.Initialize();
        }&lt;/pre&gt;
&lt;p&gt;What is the purpose of the _safeBounds? Well if you think about it, the Phone is 480X800 but the Simon Game is roughly 480*480. So that means when we detect the touch collision on the buttons, a user could technically tap outside of the "Simon Says" bounds which would be counted as a hit. Now since there is no button outside that area the user would be greeted with the GameOver screen and be frustrated.&lt;/p&gt;

&lt;a href="http://exhd.com/blog/wp-content/uploads/2010/12/simon.png"&gt;&lt;img align="middle"  title="simon" src="http://exhd.com/blog/wp-content/uploads/2010/12/simon.png" alt="" width="394" height="733" /&gt;&lt;/a&gt;

&lt;p&gt;The white box shows the Dead areas that you don't want to detect touch in.&lt;/p&gt;

&lt;p&gt;Go to Update(GameTime gameTime) method and&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                Exit();

            switch (_gameState)
            {
                case GameStates.PreGame:
                    UpdatePreGameInstruction();
                    break;
                case GameStates.Playing:
                    UpdateGamePlayingState(gameTime);
                    break;
                case GameStates.GameOver:
                    UpdateGameOverInstructions();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            
            base.Update(gameTime);
        }&lt;/pre&gt;
&lt;p&gt;
We check what our game state is and call the appropriate method.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;   private void UpdatePreGameInstruction()
        {
            var touches = TouchPanel.GetState();
            if(touches.Count&amp;gt;0)
            {
                if(touches[0].State==TouchLocationState.Pressed)
                {
                    SetGameState(GameStates.Playing);
                }
            }

        }
        private void UpdateGameOverInstructions()
        {
            var touches = TouchPanel.GetState();
            if (touches.Count &amp;gt; 0)
            {
                if (touches[0].State == TouchLocationState.Pressed)
                {
                    SetGameState(GameStates.PreGame);
                    SetGameState(GameStates.Playing);
                }
            }
        }&lt;/pre&gt;
&lt;p&gt;So if we detected a Touch we update the the GameStates. So when we start from PreGame and the User touches the screen we know they want to play. If we are at the GameOver State and the user taps then we know they want to restart and play again. So we go to the PreGame State first to reset everything and onto the Playing State.&lt;/p&gt;

&lt;p&gt;Create the SetGameState() method.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void SetGameState(GameStates gameState)
        {
            _gameState = gameState;
            switch (gameState)
            {
                case GameStates.PreGame:
                    _score = 0;
                    _rateOfChange = 1000;
                    _simonColorsList = new List&amp;lt;ButtonColors&amp;gt; {GenerateNextColor()};
                     _simonDisposableQueue = new Queue&amp;lt;ButtonColors&amp;gt;(_simonColorsList);
                    _timeSinceLastUpdate = 0;
                    break;
                case GameStates.Playing:
                    break;
                case GameStates.GameOver:
                    _donePlaying = false;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("gameState");
            }
        }&lt;/pre&gt;
&lt;p&gt;
So the PreGame state resets everything back and loads up the list with a color and creates a deep copy for the _simoneDisposableQueue. Why do we need a Queue? Well Simon says is based on a Queue system, that is, First in First out. All we need to do then is Dequeue each step and we have the next sequence to be played. Could we have used the list and just looped through it? Sure, but using a Queue is alot simpler and easier even if it requires that extra step.&lt;/p&gt;

&lt;p&gt;Do not forget to SetGameState as PreGame when the game starts otherwise we have no state, so in our LoadContent().  Add this&lt;/p&gt;
&lt;pre class="brush:csharp"&gt;  SetGameState(GameStates.PreGame);&lt;/pre&gt;
Now on to the GenerateNextColor() Method. It is used to generate what random color will be next.
&lt;pre class="brush:csharp"&gt; private ButtonColors GenerateNextColor()
       {
           //we use the ButtonColors enum
           var randomColor = _random.Next(0, typeof(ButtonColors).GetFields().Count() - 1);
           return (ButtonColors)randomColor;

       }&lt;/pre&gt;
&lt;p&gt;
Finally, the heart of the game.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void UpdateGamePlayingState(GameTime gameTime)
        {
           _timeSinceLastUpdate += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            if (_timeSinceLastUpdate &amp;gt; _rateOfChange/2)
            {
                foreach (var simonButton in _simonButtonClassList)
                {
                    simonButton.LightUp = false;
                }
            }
            if (_timeSinceLastUpdate &amp;gt; _rateOfChange)
            {

                if (_simonDisposableQueue.Count &amp;gt; 0)
                {
                    var color = _simonDisposableQueue.Dequeue();
                    var choosenbutton = (_simonButtonClassList.Where(button =&amp;gt; button.ButtonColor == color)).FirstOrDefault();
                    choosenbutton.LightUp = true;
                   choosenbutton.PlaySound();
                    
                }
                else
                {
                    _donePlaying = true;
                }
               
                _timeSinceLastUpdate -= _rateOfChange;

            }
            DetectTouch();
           
        }&lt;/pre&gt;
&lt;p&gt;
We are giving each color a one second interval before the next and half a second to light up. We check the queue count and if  it is greater than zero more sequences need to be played by Simon. Dequeue the next sequence, find what color it is , light it up and play the sound.&lt;/p&gt;
&lt;p&gt;
Otherwise we have a Boolean that tells us that Simon is done playing the sequence and we need to wait on the user to copy the pattern. The DetectTouch() method will determine if the user is progressing correctly on the pattern or not.&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; private void DetectTouch()
        {

            if (!_donePlaying) return;
            if (_playerPosition &amp;gt; _simonColorsList.Count-1)
            {
                _score++;
                _playerPosition = 0;
                _simonColorsList.Add(GenerateNextColor());
                _simonDisposableQueue = new Queue&amp;lt;ButtonColors&amp;gt;(_simonColorsList);
                _timeSinceLastUpdate = 0;
                _donePlaying = false;
                return;
            }
           
            var touches = TouchPanel.GetState();

            if (touches.Count &amp;gt; 0)
            {
                if (touches[0].State == TouchLocationState.Pressed)
                {
                    
                    if (_safeBounds.Contains((int)touches[0].Position.X, (int)touches[0].Position.Y))
                    {

                        var button =
                            _simonButtonClassList.Where(n =&amp;gt; _simonColorsList[_playerPosition] == n.ButtonColor).
                                FirstOrDefault();


                        var rectangle = new Rectangle((int) button.Position.X, (int) button.Position.Y,
                                                      button.Texture.Width,
                                                      button.Texture.Height);


                        if (
                            rectangle.Intersects(new Rectangle((int) touches[0].Position.X, (int) touches[0].Position.Y,
                                                               10, 10)))
                        {
                            //we could do pixel by pixel collision, but not really worth it
                            button.LightUp = true;
                            button.PlaySound();
                            _playerPosition++;

                        }
                        else
                        {
                            SetGameState(GameStates.GameOver);
                            _failSound.Play();
                        }
                    }
                }
            }
        }&lt;/pre&gt;
&lt;p&gt;
So What is going on? Well if Simon is not done playing then we exit from the method as there is no need to go on further.  Now the next if statement checks to see where the _playerPosition is. What is the purpose of  _playerPosition variable? Each time the user gets a pattern right we increment that variable by one and that moves us to the next color. So If the _playerPosition is greater than what the _simonColorslist we know the user successfully finished the pattern. So reset back to zero, update the score, generate another color,  queue the list, reset _timeSinceLastUpdate to zero and _donePlaying to false. Why? well Simon will need to replay the pattern with one more addition and exit out since we know Simon is up.&lt;/p&gt;
&lt;p&gt;
However, if the first two options are skipped then the users' turn is up. So we get the State of the Touch Panel, we check to make sure the touch is within the bounds of the rectangle  otherwise do nothing.  If within the bounds then look up what color is up in the sequence using the _playerPosition, create a Rectangle of the button and touch. Give the touch rectangle a width and height of 10 to allow a bit of error outside the button since the touches may not be perfect.If the button rectangle intersects with the touch rectangle  then the user got that pattern correct, increment the _playerPosition by one for the next sequence. However, if there is no intersection at the correct button color then we set the game state to GameOver and play the fail sound. That is it!&lt;/p&gt;
&lt;p&gt;
Here are things that you can do to improve on it :&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;Decrement the _rateOfChange every 5 points until you are down to 250ms.&lt;/li&gt;
	&lt;li&gt;Instead of doing Rectangle intersection take it one level deeper and do Pixel-By-Pixel collision for more accuracy.&lt;/li&gt;
	&lt;li&gt;Create Menu options (Sound Turn off, Vibrate On, Sound Turn on)&lt;/li&gt;
	&lt;li&gt;Save the High Score and load it up when the game restarts.&lt;/li&gt;
	&lt;li&gt;Add a Total Elapsed Game Time&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/AUcdVSDK4K5Q-Qg2gJwsygCg7DQ/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AUcdVSDK4K5Q-Qg2gJwsygCg7DQ/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/AUcdVSDK4K5Q-Qg2gJwsygCg7DQ/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/AUcdVSDK4K5Q-Qg2gJwsygCg7DQ/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/040VA3ooLUA" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/040VA3ooLUA/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Simon-Says-XNA-For-Windows-Phone-Tutorial-Source-Code.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=85f0bea2-6aba-476c-be34-18c6a9ab7a0c</guid>
      <pubDate>Wed, 22 Dec 2010 21:37:00 -0700</pubDate>
      <category>Windows Phone</category>
      <category>XNA</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=85f0bea2-6aba-476c-be34-18c6a9ab7a0c</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=85f0bea2-6aba-476c-be34-18c6a9ab7a0c</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Simon-Says-XNA-For-Windows-Phone-Tutorial-Source-Code.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=85f0bea2-6aba-476c-be34-18c6a9ab7a0c</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=85f0bea2-6aba-476c-be34-18c6a9ab7a0c</feedburner:origLink></item>
    <item>
      <title>Capture And Avoid a 2D XNA Game for Windows Phone  with Source Code</title>
      <description>So here is a simple game that uses techniques like  instruction screens, transformation collision detection, pixel-by-pixel collision detection. The objective of the game is to capture targets( The circles) with the Capture Box and avoid all the nukes when they spawn. The game runs for 1 minute and you need to capture as many targets and avoid as many nukes possible otherwise you get the game over screen. With each captured target you get an addition of 10 points per second. The only thing that is complicated about this game is the need to use Transformation collision Detection since the objects scale up and rotate.A normal pixel by pixel collision detection will not work that well since it will not take into consideration the scaling or rotation of the objects so that is where matrices come in to save the day.  The Project is commented well enough so there is no need to go in detail, just run it. Remember to press Page Up to activate the keyboard for the phone.&lt;a href="http://exhd.com/blog/assets/CaptureAndAvoid.zip"&gt;Click here to download the project&lt;/a&gt;.

Here is a video of what the game looks like:
&lt;div align="center" style="padding :10px;"&gt;[youtube:3NLvr4j3wfc]&lt;/div&gt;
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/aJQE-3KCUfKxupfgQihD1se-Onc/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/aJQE-3KCUfKxupfgQihD1se-Onc/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/aJQE-3KCUfKxupfgQihD1se-Onc/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/aJQE-3KCUfKxupfgQihD1se-Onc/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/_4EbZEwVpk0" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/_4EbZEwVpk0/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Capture-And-Avoid-a-2D-XNA-Game-for-Windows-Phone-with-Source-Code.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=712caf8c-1d61-4911-8970-c7127af7cbd8</guid>
      <pubDate>Tue, 21 Dec 2010 21:35:00 -0700</pubDate>
      <category>Windows Phone</category>
      <category>XNA</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=712caf8c-1d61-4911-8970-c7127af7cbd8</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=712caf8c-1d61-4911-8970-c7127af7cbd8</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Capture-And-Avoid-a-2D-XNA-Game-for-Windows-Phone-with-Source-Code.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=712caf8c-1d61-4911-8970-c7127af7cbd8</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=712caf8c-1d61-4911-8970-c7127af7cbd8</feedburner:origLink></item>
    <item>
      <title>Animating Sprite Sheets In XNA</title>
      <description>The problem we are going to tackle is what if you want to animate a Character that shoots, ducks and runs in XNA for a game that your developing for Windows Phone 7, XBox 360 or the ZuneHD. How would you go about that? The simplest way would be to create a sprite sheet of frame animations and loop through it. That is the only viable solution since  GIFs are not supported in XNA. So, We are going to animate a character named Lucas made by Naruto[NU] and can be found &lt;a rel="nofollow" href="http://www.spriters-resource.com/custom_edited/supersmashbros/sheet/23211"&gt;Here&lt;/a&gt;.  &lt;a href="http://exhd.com/blog/wp-content/uploads/2010/12/lucas.png"&gt;Click Here to Download the Assets&lt;/a&gt;

A Video of what the end result:
&lt;div align="center" style="padding: 10 px;"&gt; [youtube:WPWomHw1jVg]&lt;/div&gt;

A snapshot of what the sprite sheet looks&lt;a href="http://exhd.com/blog/wp-content/uploads/2010/12/lucas.png"&gt;&lt;img class="aligncenter size-full wp-image-122" title="lucas" src="http://exhd.com/blog/wp-content/uploads/2010/12/lucas.png" alt="" width="360" height="144" /&gt;&lt;/a&gt;
&lt;p&gt;So the SpriteSheet has three rows, the top row has a Standing/Breathing Lucas, second row has a running Lucas and the third row has a jumping Lucas.  Let's create an Animation class and start coding and thinking what we need to do.&lt;/p&gt;

The variables that we will use are
&lt;pre class="brush:csharp"&gt;        public Texture2D Texture { get; set; }
        public Vector2 FrameCoordinates { get; set; }
        public Vector2 FrameSize { get; set; }
        private int _currentFrameX;
        public Vector2 Position;
        private readonly int _msPerFrame;
        public bool Flip;
        private SpriteEffects _spriteEffects;
        private int _timeSinceLastUpdate;
&lt;/pre&gt;
&lt;p&gt;FrameCoordinates will tell us how long the frame is. For example, the first row would have a X value of 3 (start at 0) and a Y value of 0 since we are not moving at all in the Y-direction and moving 4 frames (0 to 3) in the X-direction to complete the frame animation. Second row would have a X value of 7 and a Y value of 1 since we moved down 1. Third row would have a X value of 8 and a Y value of 2.&lt;/p&gt;
&lt;p&gt;
FrameSize just tells us how big the character frame is and the Lucas Character is 40*48.  _currentFrameX will be what we will increment by 1 so we can shift and animate the character.  _msPerFrame is a variable that will control how fast the animation progresses. For example, if we were to run the animation at 33 FPS then the animation would move too fast and not look natural. The value used  is 100 which is roughly 11 FPS, change the value lower or higher and see the results. The flip and _spriteEffects variables are used for one reason. Notice in the second row  the character only runs towards the right directions but what happens if the user wants to move to the left. The character will animate and appear to be running backwards so we use the Flip variable to determine if the _spriteEffects variable needs to be set to SpriteEffects.FlipHorizontally or SpriteEffects.None. Finally the _timeSinceLastUpdate is what controls when we are allowed to shift to the next frame in the animation.&lt;/p&gt;
&lt;p&gt;
Now the only thing that is left is to create the Constructor, have an Update and Draw Method and plug and chug in the variables&lt;/p&gt;
&lt;pre class="brush:csharp"&gt; public Animation(Texture2D texture, Vector2 position, Vector2 frameCoordinates, Vector2 frameSize, int msPerFrame)
        {
            Texture = texture;
            FrameCoordinates = frameCoordinates;
            FrameSize = frameSize;
            Position = position;
            _msPerFrame = msPerFrame;
        }

        public void Update(GameTime gameTime)
        {
            _timeSinceLastUpdate += gameTime.ElapsedGameTime.Milliseconds;

            if (_timeSinceLastUpdate &amp;gt; _msPerFrame)
            {
                _timeSinceLastUpdate -= _msPerFrame;

                if (_currentFrameX &amp;gt;= FrameCoordinates.X)//if we are at the Max we know we need to loop back to 0
                {
                    _currentFrameX = 0;
                }
                _currentFrameX++;
            }

            _spriteEffects = Flip ? SpriteEffects.FlipHorizontally : SpriteEffects.None;

        }
        public void Draw(SpriteBatch spriteBatch)
        {
            /**so for the First Row the Source Rectangle will be
              (0,0)
              (40,0)
              (120,0)
            and will have a width of 40 and a height of 48.
            **/ 
            spriteBatch.Draw(Texture, Position,
                             new Rectangle((int)(_currentFrameX * FrameSize.X), (int)(FrameCoordinates.Y * FrameSize.Y), (int)FrameSize.X, (int)FrameSize.Y), Color.White, 0,
                             new Vector2(FrameSize.X / 2f, FrameSize.Y / 2f), 1, _spriteEffects, 0);

        }&lt;/pre&gt;
Now we go back to the Game1 Class and
&lt;pre class="brush:csharp"&gt;public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private Animation _lucasAnimation;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);
            graphics.IsFullScreen = true;
            graphics.ApplyChanges();
        }
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
             //start with the Breathing lucas
            _lucasAnimation = new Animation(Content.Load&amp;lt;Texture2D&amp;gt;("lucas"), new Vector2(graphics.PreferredBackBufferWidth/2f,graphics.PreferredBackBufferHeight-24),new Vector2(3, 0), new Vector2(40, 48),100);
        }
        private KeyboardState _keyboard = Keyboard.GetState();
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            var state = Keyboard.GetState();
            if(state.IsKeyDown(Keys.Left) &amp;amp;&amp;amp; _keyboard.IsKeyDown(Keys.Left))
            {
                _lucasAnimation.FrameCoordinates = new Vector2(7, 1);
                _lucasAnimation.Position -= new Vector2(3, 0);
                _lucasAnimation.Flip = true;

            }
            if (state.IsKeyDown(Keys.Right) &amp;amp;&amp;amp; _keyboard.IsKeyDown(Keys.Right))
            {
                _lucasAnimation.FrameCoordinates = new Vector2(7, 1);
                _lucasAnimation.Position += new Vector2(3, 0);
                _lucasAnimation.Flip = false;
            }
            if (state.IsKeyDown(Keys.Up) &amp;amp;&amp;amp; _keyboard.IsKeyDown(Keys.Up))
            {
                _lucasAnimation.FrameCoordinates = new Vector2(8, 2);
             }
            //If No Keys are Pressed then we set it back to the Breathing Lucas Animation
            if(!state.IsKeyDown(Keys.Left) &amp;amp;&amp;amp; !state.IsKeyDown(Keys.Right) &amp;amp;&amp;amp; !state.IsKeyDown(Keys.Up))
            {
                _lucasAnimation.FrameCoordinates = new Vector2(3, 0);
            }
            _lucasAnimation.Position.X = MathHelper.Clamp(_lucasAnimation.Position.X, _lucasAnimation.FrameSize.X,
                                                         graphics.PreferredBackBufferWidth -
                                                         _lucasAnimation.FrameSize.X); //prevent Lucas from leaving the Phone Area.

            _lucasAnimation.Update(gameTime);
            _keyboard = state;
            base.Update(gameTime);
        }

       protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin();
            _lucasAnimation.Draw(spriteBatch);
            spriteBatch.End();
            base.Draw(gameTime);
        }
    }&lt;/pre&gt;
Now one thing you may ask is why do we need to have two keyboard Variables. Well we want to determine which keys are being held     down and the only way to do that is to have two states. If the "previous state" has the left Key pressed and in the "new state" has the left key is also pressed then we know the user is continuously pressing on the left key otherwise no key is being held and we can return Lucas to the standing animation.
&lt;p&gt;&lt;a href="http://feedads.g.doubleclick.net/~a/XsN-PyzGzZ6pgLTeIsLtVw_7x40/0/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/XsN-PyzGzZ6pgLTeIsLtVw_7x40/0/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;br/&gt;
&lt;a href="http://feedads.g.doubleclick.net/~a/XsN-PyzGzZ6pgLTeIsLtVw_7x40/1/da"&gt;&lt;img src="http://feedads.g.doubleclick.net/~a/XsN-PyzGzZ6pgLTeIsLtVw_7x40/1/di" border="0" ismap="true"&gt;&lt;/img&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://feeds.feedburner.com/~r/Exhd/~4/QC9iP1T0o0Y" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/Exhd/~3/QC9iP1T0o0Y/post.aspx</link>
      <comments>http://blog.exhd.com/KB/Animating-Sprite-Sheets-In-XNA.aspx#comment</comments>
      <guid isPermaLink="false">http://blog.exhd.com/post.aspx?id=daea4438-7bd1-418e-ae9d-f3ee8025764c</guid>
      <pubDate>Mon, 20 Dec 2010 21:32:00 -0700</pubDate>
      <category>Windows Phone</category>
      <category>XNA</category>
      <dc:publisher>EXHD</dc:publisher>
      <pingback:server>http://blog.exhd.com/pingback.axd</pingback:server>
      <pingback:target>http://blog.exhd.com/post.aspx?id=daea4438-7bd1-418e-ae9d-f3ee8025764c</pingback:target>
      <slash:comments>0</slash:comments>
      <trackback:ping>http://blog.exhd.com/trackback.axd?id=daea4438-7bd1-418e-ae9d-f3ee8025764c</trackback:ping>
      <wfw:comment>http://blog.exhd.com/KB/Animating-Sprite-Sheets-In-XNA.aspx#comment</wfw:comment>
      <wfw:commentRss>http://blog.exhd.com/syndication.axd?post=daea4438-7bd1-418e-ae9d-f3ee8025764c</wfw:commentRss>
    <feedburner:origLink>http://blog.exhd.com/post.aspx?id=daea4438-7bd1-418e-ae9d-f3ee8025764c</feedburner:origLink></item>
  </channel>
</rss>

