Java Assignment 11 -- 2 Player Pong

Green Paddle: Press q for up, z for down, a for automatic play
Magenta Paddle: Press o for up, m for down, k for automatic play
Press p to pause game

Pong was the first video game to achieve commercial success and it was the application that brought computers into peoples homes for the first time. It was invented in 1972 at Atari. Nolan Bushnell, the head of Atari, is usually given credit for inventing Pong, but the person who actually wrote the code for the game is Alan Alcorn, a Lowell graduate.

In this assignment you will make a recreation of the original two player Pong game. Your completed assignment will have at least three classes: the “Applet” class, a Ball class and a Paddle class.

Since this is a large assignment, it probably best to complete it in steps. First create a new applet project. Then add a Ball class, and and finally add the paddle class.

Threads and the Applet class

All animation is based on the same Erase-Move-Draw-Wait sequence. In a C++ application we would just use a delay to make the computer wait, but you wouldn’t want to do that in an applet. Using a simple delay would make EVERY PROCESS the computer was working stop for the specified period of time. That’s unacceptable in when an applet is just one of several active items on a computer. Instead, we need a way that will make ONLY OUR APPLET wait for the specified time. To do this we will use a thread.

public class Pong extends Applet implements Runnable
{
    Thread animation;  //declares a thread called animation
    static final int REFRESH_RATE = 50;  //Constant for “delay”
    
    //declare other class data members
    
    public void init()
    { 
       //initialize class data members
        
    }
    public void paint(Graphics g)
    {

		 //painting
    }
    public void start()
    {
	    animation = new Thread(this);
          if(animation != null)
          {
	      animation.start();
          }
    }
    public void run()
    {
         while(true)
         {
            //put code that runs in loop here
            repaint();
            try
            {
	         Thread.sleep(REFRESH_RATE);
            }catch(Exception exc){};
         }
    }

    public void stop() 
    {
	    animation = null;
    }

}

Part One: The Ball class

  1. Write a ball class. The class definition should be outside your “Pong” class, you can even put it in a seperate file if you want. The class should have the following data members:
    1. The X and Y of the center of the ball
    2. boolean variables for the Up/Down direction (bUp) and the Left/Right direction (bRight).
    3. The distance the ball moves each turn.
    4. You may also want data members for the Color and size of the ball, the Applet Width and Applet Height, and positions of the two paddles (you can add these later).
  2. Your ball class will also need several methods:
    1. Ball() the class constructor. You may want to add arguments for the frame height and width of the frame and the x coordinate of the paddles (you can add these later).
    2. void move () checks bUp and bRight to move ball in the correct direction.
    3. void bounce() Checks to see if the ball is moving off the screen. If it is it "bounces" the ball by changing myUpDown and/or myLeftRight.
    4. void draw (Graphics g) draws the ball at its current position.
  3. Once you’ve finished writing the class, you’ll want to declare and initialize an instance of the ball class as a data member in the "Pong" class. Move and bounce the ball in the loop and draw the ball in the paint method.
  4. You should now be able to display the bouncing ball to the screen.

Part Two: Adding the Paddle class

  1. Write a paddle class. Your paddle class will need data members for the X and Y position of the top left corner of the paddle, its Width ,Height and Color.
  2. Your paddle class will also need some methods:
    1. Paddle(int nXpos, int nYpos, Color aColor) the class constructor
    2. void moveUp()
    3. void moveDown()
    4. void draw (Graphics g)
    5. int yPos() an accessor method that returns the y position of the paddle.
  3. Add implements KeyListener to the "Pong" class. (Remember, if your applet implements more than one interface, separate the interfaces with commas).
  4. Add import java.awt.event.*;
  5. Add three three methods to your Pong class:
    1. public void keyPressed (KeyEvent ke)
    2. public void keyReleased (KeyEvent ke)
    3. public void keyTyped (KeyEvent ke)
  6. Add addKeyListener(this); and requestFocus(); to the init method.
  7. Declare and initialize two instances of the Paddle class in the “Pong” class.
  8. You will now need to go back to the bounce method in the ball class and modify it so that the ball will bounce off the paddles.

Moving the Paddles

One way to move the paddles is with keyPressed and keyReleased. Declare and initialize four booleans in the “Pong” class :
boolean bLeftUp=false, bLeftDown=false, bRightUp=false, bRightDown=false;
In keyPressed, set up a switch statement to set bLeftUp (and the other booleans) to true if the correct key is pressed. In keyReleased, setup an similar switch statement to set the booleans to false. Then in the loop you can move the paddles with code like:
    if(bLeftUp)
       Paddle1.moveUp();

Adding Double Buffering

The simple method of double buffering from the web site is too slow for animation. To implement a more efficient version of double buffering you will need to make 6 changes:
public class Pong . . . .
{
     //1.  two added declarations
	Graphics offscreen;
	Image image;
	
     public void init()
     {
		. . . .
        
             //2.  two added initializations
             image = createImage(nSCREEN_WIDTH, nSCREEN_HEIGHT);
             offscreen = image.getGraphics();
     }
     public void paint(Graphics g)
     {
		//3.  clear offscreen
		offscreen.setColor(Color.white);
		offscreen.fillRect(0,0,nSCREEN_WIDTH, nSCREEN_HEIGHT);
		
		//4.  modify code so that drawing is offscreen
		theBall.draw(offscreen);
                . . . . 
		
		//5.  copy offscreen to visible screen
		g.drawImage(image,0,0,this);
     }
	   
     //6.  override update()
     public void update(Graphics g)
     {
   		paint(g);
     }
	
}

Extensions

If you have extra time, you can add extra features to your pong game: an automated opponent, scoring, targets, obstacles, extra balls and paddles, angles other than 45 degrees etc.

You will need a web page to display your applet. Your homepage should have a link to the web page for this assignment.

Submit the URL of your applet along with your Java code (the .java file(s)) in an email message to mrsimon@lycos.com.