Complete program listing

A complete listing of the program discussed in this lesson is shown in Listing 6 .

Listing 6. Source code for BouncingBallInBox project.

/*Project BouncingBallInBox
Displays a ball bouncing around inside of a box. The
ball is allowed to move in only four directions:
northeast, southeast, southwest, or northwest. When the
ball hits a wall of the box, it doesn't bounce in the
direction that would normally be expected.  Instead it
selects one of the four possible directions and bounces
in that direction.

The ball continues to bounce until the user presses the
Esc key, at which point the program terminates.

#include <allegro.h>

int width = 220;//width of box
int height = 440;//height of box
int radius = 5;//radius of ball

int x = 110;//initial position of ball
int y = 220;//initial position of ball

int tempX;
int tempY;

//Keep track of direction of motion here.
//0= northwest 1 = southwest, 2 = northeast,
//3 = southeast
int dir;

void moveBall(){
  //Save current location of ball.
  tempX = x;
  tempY = y;

    case 0:
      //Direction is northwest.
      if((x <= radius) || (y <= radius)){
        //Ball has collided with either the left wall or
        // the top wall.
        //Get a new direction. Note that if the new
        // direction is the same as the old one, control
        // will come back to here to get still another
        // direction the next time the functionis called.
        dir = rand() % 4;
        //No collision, set new location for the ball
      }//end else
    case 1:
      //Direction is southwest.
      if(((x <= radius) || (y >= (height - radius)))){
        //get a new direction
        dir = rand() % 4;
        //set new location for the ball
      }//end else
    case 2:
      //Direction is northeast.
      if(((x >= (width - radius)) || (y <= radius))){
        //get a new direction
        dir = rand() % 4;
        //set new location for the ball
      }//end else
    case 3:
      //Direction is southeast
      if((((x >= (width - radius)) ||
                              (y >= (height - radius))))){
        //get a new direction
        dir = rand() % 4;
        //set new location for the ball
      }//end else

  }//end switch

  //Erase the current image of the ball and draw a new
  // image at the modified location coordinates.
  circlefill (screen,tempX,tempY,radius,makecol(0,0,0));
  circlefill (screen,x,y,radius,makecol( 128, 255, 0));

  rest(5);//Delay for five milliseconds
}// end moveBall function.

int main(){


  //Seed the random number generator and set the initial
  // direction based on a random number.
  srand (time(NULL));
  dir = rand() % 4;
  //Loop until the user presses the Esc key.
  while( !key[KEY_ESC]){
  }//end while loop

  return 0;
}//end main