Archive for the ‘visual studio’ Category

Bubble Evader

January 29, 2011 2 comments

Lets proceed to create our game. XNA Game Studio uses Visual C# for programming. So, you need to be aware of some basic concepts of Object Oriented Programming(OOP) like Objects, Classes, Inheritance etc.. You can learn some of these basic things here. To create a game for Windows Phone 7, you will need Visual Studio 2010 & XNA Game Studio 4.0 along with other Windows Phone 7 developer tools, which you can get here for free. Once you have downloaded and installed Visual Studio, go to File->New Project. Under Visual C# pane on the left you go to XNA Game Studio and select Windows Phone Game(4.0) option, as you can see in the image below.

New Project (Click for a larger picture)

When the project is created, the Visual Studio IDE puts some predefined code into your project which looks like as in the image below. The lines in green colour are the comments which are ignored by the compiler, which is there for the user’s reference. You can minimize the methods by clicking on the minus (‘-’) sign on the left side of the method(function) names. Once collapsed, they would look as in the picture to the right.                          

New Project 2New Project 3

Now you can see all the predefined methods & a class. Game1 is the class where all the action takes place. It contains variables and methods for various things that you do in the game. It forms the main control. It consists of main 5 methods that keep the game running.

  • Initialize
  • LoadContent
  • UnloadContent
  • Update
  • Draw

These methods form what is called as a game loop, which continuously keeps the game running, which can be represented in a flowchart.


Initialize is the first method that is called when the game starts. So any initializations to be made (ex: Setting the number of enemies) will go here.

LoadContent is the method that contains code to load game resources like sprites, backgrounds, audio etc.. onto the memory.

UnloadContent is the method used to unload the loaded resources from the memory at the end of the game.

Draw is the method to draw whatever we want on the game screen. It may include various sprites, objects etc.. and their respective positions on the screen.

Update is the method which is called whenever there is an update to the scene to be made (ex: When the user presses a key for the sprite to jump, etc.) This method is followed by the Draw method again. These two methods form what  is called as a Game Loop, which stops only when the game is exited.

We also need to understand all things that constitute a game. Lets start with Sprites. A sprite can be regarded as a picture that you would want to associate with a player or any object like enemies, walls, doors, etc..

Sprite MarioSprite Mario 2

This is a screenshot from one of the most famous games of all times, Mario. The smaller image you see is called as a sprite. It is used to draw on the screen as you can see in the bigger picture. All those bricks and walls used in there are also sprites, which are used multiple times in the same scene. Sprites are of two types, Transparent(.png or .gif) & non-transparent(.jpg). If you use a non-transparent sprite, the entire image(including the background) gets drawn on the screen. When you use transparent sprites, the background will not be used while drawing that sprite on the screen. You don’t want a padding around your sprite while playing a game, do you? So, its obvious to use transparent sprite.

For this game, our sprites would be a simple circle and a square, which can be created using very basic image editors like MS Paint. But I would recommend a better & free tool called Paint.Net which I used and has better transparency support. A simple set of Instructions on making a sprite transparent in Paint.Net can be found here. Here are my sprites, a square and a circle.


Now, in the solution explorer(Its a pane in the right side of visual studio) right-click on the Content and go to Add->New Folder. Name that folder as Images. Now right click on Images folder and Add->Existing Item. Go to the location where your sprite is in your computer and add that image file of your sprite to the project. You should be able to see the filenames of the images in the Images folder.

Add Sprite 1Add Sprite 2


In the Game1 class, you can see that a GraphicsDeviceManager and a SpriteBatch object have been defined. Here, graphics object corresponds to the graphics device to which you will be interacting to do various things in the game, and spriteBatch object is to draw sprites, which contains many methods for different situations.

GraphicsDeviceManager graphics; SpriteBatch spriteBatch;

Now, define a Texture2D object in your Game1 class after the above code, name it whatever you want. This object will be used to load the image as a texture to draw it on the screen.

GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D texture;

Now, go to LoadContent() method and type the following line of code. Your LoadContent() should look like below. It loads the square image to texture object.

protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); texture = Content.Load<Texture2D>(@"Images/square"); }

Now, go to Draw() method and add the following lines of code. It should look as below. This code draws the sprite stored in texture object at position (0,0) on the screen.

protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(texture, Vector2.Zero, Color.White); spriteBatch.End(); base.Draw(gameTime); }

spriteBatch requires you to call Begin() and End() before and after we do any operation with the sprites. Now, run your project by pressing F5 key. You should be able to see the emulator running with a blue background and a square at top-right corner of the emulator screen. Ideally, it should have been at the top-left corner, but XNA treats Win Phone 7 to be in portrait mode by default and hence you see it at top-left corner as seen in portrait mode.


Now, lets try moving a sprite. Create another Texture2D object to store the circle sprite. Also define a Vector2 object to store the 2-Dimensional co-ordinate position of the circle. Here, I’m initializing the position vector object to zero. Also define another Vector2 object speed to add to set the speed of the circle.

Texture2D circle; Vector2 position = Vector2.Zero; Vector2 speed = new Vector2(4, 4);

Now, add the code to load the circle sprite in LoadContent() method.

   1: circle = Content.Load<Texture2D>(@"Images/ball");

Now, modify the Draw() method to draw the circle sprite.

protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(circle, position, Color.White); spriteBatch.End(); base.Draw(gameTime); }

Add the following piece of code to your Update() method to increment the position of the circle along X & Y directions. position is a Vector2 object consisting of x & Y coordinates. We will now increment these values in Update() method and also see that the circle does not go out of the screen. The screen size of Windows Phone 7 is 480 X 800.

protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); if (position.X > Window.ClientBounds.Height - circle.Width) speed.X *= -1; else if (position.X < 0) speed.X *= -1; if (position.Y > Window.ClientBounds.Width - circle.Height) speed.Y *= -1; else if (position.Y < 0) speed.Y *= -1; position += speed; base.Update(gameTime); }

The If conditions check whether the circle is inside the screen or not. If it seems to go out of the screen, the X and Y components of speed are reversed so that the ball bounces of the edge of the screen. Window.ClientBounds.Height and Window.ClientBounds.Width return the Height and  Width of the screen as in Portrait mode. That’s the reason I’m operating X coordinate with Height and Y coordinate with Width. We are subtracting the width and height of the texture to align the position of the ball. As you can see, the ball bounces off at little higher position from bottom. This is because that some space is reserved for some controls that you may want to give to the user at the bottom like some buttons, etc.. You can utilize the full screen by replacing Window.ClientBounds.Height by a particular integer value. In this case, the value will be 800.

The entire code of the game as of now will be

using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Media; namespace BubbleEvader { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D texture; Texture2D circle; Vector2 position = Vector2.Zero; Vector2 speed = new Vector2(4, 4); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333); } protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); texture = Content.Load<Texture2D>(@"Images/square"); circle = Content.Load<Texture2D>(@"Images/ball"); } protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); //if (position.X > Window.ClientBounds.Height - circle.Width) if (position.X > 750) speed.X *= -1; else if (position.X < 0) speed.X *= -1; if (position.Y > Window.ClientBounds.Width - circle.Height) speed.Y *= -1; else if (position.Y < 0) speed.Y *= -1; position += speed; base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(circle, position, Color.White); spriteBatch.End(); base.Draw(gameTime); } } }

Now, you have a ball bouncing off the edges of the screen. This would be all for now. Will be back in few days with more features. Till then, keep experimenting!

Bouncing Ball

Fighting with Visual Studio 2010

Visual Studio 2010 has been released recently and I downloaded the iso image of the Ultimate edition DVD from my MSDN account. Eager to try it, I Installed it by removing the Release Candidate of the same, which I had installed earlier. The RC was removed without any issues whatsoever. But after installing VS 2010, strangely, Visual Studio 2008 Pro started showing weird problems. At first, the designer view for ASP.Net project stopped working, it would just stop responding. I could not click anywhere in the window & had to close the IDE using the Task Manager. Since I was not much into ASP.Net, and design view was working fine in VS 2010. This error was due to the fact that some .dll file required for rendering was replaced by VS 2010 installer with a newer version of the same dll & which was not compatible with VS 2008. Since it was fine in VS 2010, I did not bother much about it.

But situation started worsening after a few days. I had installed XNA Game studio which is an add-on to VS 2008 to create games in C#. VS 2008 not only stopped opening/creating the XNA projects, but also started to fail to open any C# project! I searched over the Internet to see whether anybody else had encountered the same problem. I did not get any such cases, and hence I decided to re-install both VS 2008 & VS 2010. I first removed VS 2010 and started removing the other components it had installed with it. I could remove almost all of them except for one or two. I had to remove the remaining components using the MS Installer Cleanup Utility which is available for download here. It appeared that I had successfully removed VS 2010. Then I re-installed VS 2008 which went well without any issue.

Then came the bigger problem. I tried Installing VS 2010 back again, which used to fail repeatedly. It was trying to install VC++ 10.0 Runtime without any success. VC++ Runtime is a prerequisite for installing VS 2010. I tried installing it separately by downloading from the MS website, which would actually install, but would not be detected as installed by VS 2010 Installer, which tried to install it again & would fail. Then I looked into the installation log of VS 2010 which was in my “Temp” folder located in C:\Users\Username\AppData\Local\Temp\ . There, I found that the installer was returning error code 1603, which meant “fatal error during installation”. I digged further and I got error code 1402, which meant that a particular Registry Key was not accessible to the installer. The error message in the log file read something like Error 1402.Could not open key: UNKNOWN\Components6A0D925C8932A8379FE28AFAF97A860\B45568A682984E035AC37D33679831D4. Verify that you have sufficient access to that key, or contact your support personnel. So, I came to know that the installer has some problems accessing a particular key in the registry. I searched in the net & got a link on how to solve such type of registry inaccessible problems. As you can see, that particular Registry key had been “Orphaned”.

What happened here was that when VS 2010 was uninstalled, the uninstaller instead of removing those registry keys, had actually, Orphaned them. In the sense, that those Keys don’t belong to any particular user, & hence when the setup tries to create the key, it encounters another key with the same name & cannot modify the existing one since it doesn’t have any owner, rendering it inaccessible to any user/process. As indicated in this earlier link, I changed the permissions for that key & thought Installation would be successful this time. But, this time, another key problem came up! Again I changed the permissions. Again a problem! After doing this exercise for many times, I got fed-up & used a software called Registry Mechanic to clean the registry. It found 1000+ issues in the registry, of which most of them where this orphan registry keys. It removed all of them & finally, I could Install VS 2010! And as of now, XNA projects are successfully opening in VS 2008, but the design view issue still persists, which is enough for me as of now.