
For today’s article we’ll have a look at one of the old classics – Pong!
Getting started
First of all you must open a new solution in Visual Studio. If you cannot afford a licence for the whole studio you can download Visual C# Epxress Edition for free from www.msdn.com. Right, let’s get going. No matter of what version you use, choose New Project from the File menu.
Write “Pong” in the Name textbox and make sure to have a suiteable location path for your project in the Location textbox. This is where some of you goes: “hey- isn’t there copyright & trademark regulations to consider here?” Well, the thought striked me as well, so I went and surfed around a bit to find out more about it. It seems, according to this Australian document www.copyright.org.au/g016.pdf, that the name of a computer game is not protected by copywright. I suppose you can registered explicitly but then again, as long as you do not try to sell the stuff as your own work you and only use it for private studies, you should be just fine. So fire away.
Adding Contents
Contents resources used by the game during runtime such as images, fonts and sound clips. If you look in your project you’ll notice that a Content library already has been created as part of your project. Right click on it in the Solution Explorer and choose Add > New Folder from the context menu. Create a new folder called Sprites and save the two images below into the folder.
Program.cs
The program module will automaticly be part of your project when its created. If you have a look at it you find that its a very slim static method that will work as an entry point for your game when it is executed. You can leave this module as it is, for now.
GameObject.cs
Before doing anything else, we will create the base class that we will use creating the rest of the game. In games we see different objects interacting with each other. Most of these objects share common properties and functionality. By creating a general class with these features we do not have to code the same thing over and over for each single item.
Add a new class item to your project and name it GameObject. At the top of the document, make sure to put using statements for the System, Microsoft.Xna.FrameWork and the Microsoft.Xna.Framework.Graphics namespaces. It should look like this:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
The using statements lets us write less code and usually makes it easier to read as well. With it, we can refer to objects belonging to that namespace without having to declare the full path to it. For example, we can now simply refer to the Vector2 class without having to write the full lenght path Microsoft.Xna.Framework.Vector2. As you can imagine, this saves us quite some time when we are implementing our code.
OK, the next thing we should do in our GameObject class is to add some public properties. Add the following declarations and make sure they end up inside the brackets of your class:
public Texture2D sprite;
public Vector2 position;
public float rotation;
public Vector2 velocity;
public bool alive;
By making these fields public means that they can be accessed by other objects outside of this class. Usually I would recommend to use private fields and wrap them with public properties. But that it outside the scope of this post, and we want to keep things simple here so we’ll stick to this “shortcut” of doing things.
Next thing to do is add a public constructor method to our class. A constructor is a method that is executed when a class is being instantiated (created), that is whenever you put a statement like “new GameObject();” in your code. A constructor is added by creating a public method with the same name as the class itself. Inside the method we want to give some inital values to the fields we just added to the class. Just under the field lines, write the following lines being your constructor:
public GameObject(Texture2D loadedTexture)
{
rotation = 0.0f;
position = Vector2.Zero;
sprite = loadedTexture;
velocity = Vector2.Zero;
alive = false;
}
There, your GameObject class should be ready to be used now. Lets move on and build the rest of the game shall we? Next we’ll have a look at the PongGame class.
PongGame.cs
The Game class inherits from Microsoft.Xna.Framework.Game and it represents your actual game. You can consider this as the core object of your game project. Note that this is also the class that is created in the Main sub of the Program module. When you create a new project you might notice that this file is named Game1.cs. Well, feel free to rename it to something more apppropriate. Naming the file to only PongGame.cs is good enough. When the file has been renamed make sure to open it and also rename the actual class it containts.
public class PongGame: Microsoft.Xna.Framework.Game
Most often you will be prompted when changing the name of file if you also want to change the class as well. If so, agree and you will spare yourself the energy of opening the file and doing it manually yourself. When the Game class has renamed you should be able to compile and run the game for the first time. Press F5 to start the Debugger. See? Everything runs perfectly! But yes I agree, so far the game is not so sexy, all you see is a window with a skyblue background. This is because we haven’t added any code to the PongGame class yet. So stop the Debugger and we’ll get right to work!
Open the PongGame file and begin with adding a using statement to the System.Text namespace if it is not already there. Then we need to have some fields again for the game to work. The class should already have a SpriteBatch and a GraphicsDeviceManager field, so add the following fields in the upper region of your class right under the existing two fields:
GameObject player1Paddle;
GameObject player2Paddle;
Rectangle viewportRectangle;
GamePadState gamePadStade = GamePad.GetState(PlayerIndex.One);
KeyboardState keyboardState = Keyboard.GetState();
SoundEffect bounceSound;
SpriteFont scoreFont;
int player1Score = 0;
int player2Score = 0;
Random random;
To make use of these fields they must be instantiated. The proper place to do this would be in the LoadContent method. Scroll down to it and write it to look like this (please excuse the layout of the text, this blog sort of messes it up completely):
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
viewportRectangle = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
player1Paddle = new GameObject(Content.Load<Texture2D>(“Sprites//Paddle”));
player1Paddle.position = new Vector2(0, viewportRectangle.Height / 2 – player1Paddle.sprite.Height / 2);
player2Paddle = new GameObject(Content.Load<Texture2D>(“Sprites//Paddle”));
player2Paddle.position = new Vector2(viewportRectangle.Width – player2Paddle.sprite.Width, viewportRectangle.Height / 2 – player2Paddle.sprite.Height / 2);
ball = new GameObject(Content.Load<Texture2D>(“Sprites//Ball”));
ball.position = new Vector2(viewportRectangle.Width / 2, viewportRectangle.Height / 2);
random = new Random();
}
Right. If you try to compile your project you will notice that we still get an empty blue screen. This is because we must also add some drawing logic in order to get the game to display our objects. This is done in the Draw() method of the PongGame class. Scroll down to it and code it to look like this:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteBlendMode.AlphaBlend);
spriteBatch.Draw(player1Paddle.sprite, player1Paddle.position, Color.White);
spriteBatch.Draw(player2Paddle.sprite, player2Paddle.position, Color.White);
if (ball.alive)
{
spriteBatch.Draw(ball.sprite, ball.position, Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
Press F5 and compile it and… YEAH! We have two paddles! Unfortunetly there is no ball and the paddles won’t move. Keeping track of the ball and adjusting its positions takes quite a few lines of code. A good thing would be to isolate that code from the rest of the Update logic and put it in its own method. So, declare a new method called UpdateBall() and make it look like this (once again, sorry about the layout):
private void UpdateBall()
{
if (ball.alive)
{
ball.position += ball.velocity;
// If the ball collides with the upper or lower walls, we can change it’s horizontal direction
// by mutliplying the Y value of it’s velocity vector by -1.
if (ball.position.Y <= 0 | ball.position.Y >= viewportRectangle.Height – ball.sprite.Height)
{
ball.velocity = new Vector2(ball.velocity.X, ball.velocity.Y * -1);
}
if ((ball.position.X <= player1Paddle.position.X + player1Paddle.sprite.Width &
ball.position.Y >= player1Paddle.position.Y &
ball.position.Y <= player1Paddle.position.Y + player1Paddle.sprite.Height) ^
(ball.position.X + ball.sprite.Width >= player2Paddle.position.X &
ball.position.Y >= player2Paddle.position.Y &
ball.position.Y <= player2Paddle.position.Y + player2Paddle.sprite.Height))
{
ball.velocity = new Vector2(ball.velocity.X * -1, ball.velocity.Y);
bounceSound.Play();
}
if (!viewportRectangle.Contains(new Point(
(int)ball.position.X + ball.sprite.Width / 2,
(int)ball.position.Y + ball.sprite.Height / 2)))
{
ball.alive = false;
if (ball.position.X > 0)
{
player1Score++;
}
else
{
player2Score++;
}
}
}
else
{
ball.alive = true;
ball.position = new Vector2(viewportRectangle.Width / 2, viewportRectangle.Height / 2);
ball.velocity = new Vector2(
(float)(random.Next(-7,7)),
(float)(random.Next(-7,7)));
}
}
We need to add the last remaining code to the main Update() method and then we should be all set. This is the method that will be frequently called during the game and that will make sure we handle any user input and update the objects within the game world.
Go the Update() method and make sure it looks like the following:
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
#if !XBOX
KeyboardState keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.W))
{
player1Paddle.position.Y -= 3.5f;
}
if (keyboardState.IsKeyDown(Keys.S))
{
player1Paddle.position.Y += 3.5f;
}
if (keyboardState.IsKeyDown(Keys.Up))
{
player2Paddle.position.Y -= 3.5f;
}
if (keyboardState.IsKeyDown(Keys.Down))
{
player2Paddle.position.Y += 3.5f;
}
#endif
player1Paddle.position.Y = MathHelper.Clamp(player1Paddle.position.Y, 0, viewportRectangle.Height – player1Paddle.sprite.Height);
player2Paddle.position.Y = MathHelper.Clamp(player2Paddle.position.Y, 0, viewportRectangle.Height – player2Paddle.sprite.Height);
UpdateBall();
base.Update(gameTime);
}
And that’s it! You have just created your first Pong game. Kind a cool huh? Now, this is an never ending version of pong. Next thing you could do is try to implement logic to use the point counters to determine a winner after a certain number of scores?
Anyways. Have fun!

