This hands on exercise is based on a demo by Sam Stokes called Pong in Five Minutes. I appreciate Sam’s help in this effort. You can watch Sam’s demo in a video and get the code and other files used in this lab from http://blogs.msdn.com/devschool/archive/2008/02/03/pong-in-5-minutes.aspx  If you want these materials more easily available. So I have uploaded them to Skydrive at the links below.

How To Create A Pong Game in XNA 

Includes:

  • Step by step instructions
  • Code Snippits
  • graphical content

 

Open a new Windows Game Project from the XNA Section for the C# language in Visual Studio 2008.

HOL01

Select Content from the Solution Explorer and choose the Add Existing Item option for the Project menu.

HOL02

Navigate to where you have saved the image files and add them to the project.

HOL03

Set the Copy to Output Directory property of both images to “Copy Always”

HOL04

Now we are going to add two classes to do the work of the game. We will add a ball class and a paddle class. First add the Ball class by selecting Add Class from the Project menu. This opens a window where we can name the class Ball.

 HOL05

Enter the following code for the Ball class.

       class Ball
        {
            //position of ball
            public Point pos;
            public int h_speed, v_speed;

            //constructor - position
            public Ball(int x, int y)
            {
                pos = new Point(x, y);

                Random rand = new Random();
                h_speed = rand.Next(3, 7);
                if (rand.Next(0, 2) == 0) h_speed *= -1;

                rand = new Random();
                v_speed = rand.Next(3, 7);
                if (rand.Next(0, 2) == 0) v_speed *= -1;
            }
        }

Now create the Paddle class the same way and enter the following code for the paddle.

    class Paddle
    {
        //position of paddle
        public Point pos;
        public int speed;

        //constructor - position
        public Paddle(int x, int y)
        {
            pos = new Point(x, y);
            speed = 3;
        }
    }

Add a call to the Microsoft.XNA.Framework libraries to the top of the the Ball and Paddle class files so that these libraries will be available.

HOL06

Return to the Game class and define the variables and objects we need for the game.

   public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;

        Texture2D t_paddle1, t_paddle2, t_ball;
        SpriteBatch spriteBatch;

        Paddle paddle1;
        Paddle paddle2;
        Ball ball;

        Random rand = new Random();
        KeyboardState currentState;
        GamePadState currentPad;

Now let’s create an UpdateBall class to move the ball around the screen.

                
        void UpdateBall()
        {
            //update positions
            ball.pos.X += ball.h_speed;
            ball.pos.Y += ball.v_speed;

            //check for boundaries
            //bottom
            if (ball.pos.Y > (Window.ClientBounds.Height - 10 - t_ball.Height))
                ball.v_speed *= -1;

            //top
            if (ball.pos.Y < 10)
                ball.v_speed *= -1;
        }

We also need an UpdatePaddles method to control the paddles.

     void UpdatePaddles()
        {
            //get keyboard keys
            currentState = Keyboard.GetState();
            currentPad = GamePad.GetState(PlayerIndex.One);

            //check for up and down arrow keys
            if (currentPad.Triggers.Left > 0.0)
                   paddle1.pos.Y -= paddle1.speed;

            if (currentPad.Triggers.Right > 0.0)
                    paddle1.pos.Y += paddle1.speed;        

            //paddle to move according to ball
            if (paddle2.pos.Y + (t_paddle2.Height / 2) > ball.pos.Y)
                paddle2.pos.Y -= paddle2.speed;
            else if (paddle2.pos.Y + (t_paddle2.Height / 2) < ball.pos.Y)
                paddle2.pos.Y += paddle2.speed;

            //check boundaries
            if (paddle1.pos.Y <= 10) paddle1.pos.Y = 10;
            if (paddle2.pos.Y <= 10) paddle2.pos.Y = 10;

            if (paddle1.pos.Y + t_paddle1.Height >= Window.ClientBounds.Height - 10) paddle1.pos.Y = Window.ClientBounds.Height - t_paddle1.Height - 10;
            if (paddle2.pos.Y + t_paddle2.Height >= Window.ClientBounds.Height - 10) paddle2.pos.Y = Window.ClientBounds.Height - t_paddle2.Height - 10;
        }

In the Initialize method that was created for us automatically we have to add a call to ResetGame to start our game.

        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            ResetGame();
            base.Initialize();
        }

In the LoadContent method we have to add some calls to load the images that we have already added to the project.

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
           
            t_paddle1 = Texture2D.FromFile(graphics.GraphicsDevice, @"content\paddle.png");
            t_paddle2 = Texture2D.FromFile(graphics.GraphicsDevice, @"content\paddle.png");
            t_ball = Texture2D.FromFile(graphics.GraphicsDevice, @"content\ball.png");
            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
                
            // TODO: use this.Content to load your game content here
        }

Lastly we need to add code to the Update method to call the methods that make the game run.

        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            UpdateBall();
            UpdatePaddles();
            CheckCollisions();
                
            base.Update(gameTime);
        }

Now we can run the game and use the up and down arrow buttons to control the left paddle.

HOL07

Note that you can use the Escape key to exit the program as well as the back key on an Xbox 360 Controller.

Get XNA Information at http://creators.xna.com