




MAIN.CXX
We can accomodate a flexible number of items by using a Standard Template Library vector.
The vector class is similiar to an array but can be expanded dynamically through the push_back method.
The standard C++ library includes the function random() which can be used to regenerate a random number.
#include <vector.h>
#include <iostream.h>
#include "ball.h"
int main (void)
{
sphere mySphere;
mySphere.setRadius(10.0);
cout << "mySphere has radius: " << mySphere.getRadius() << endl;
sphere myOtherSphere;
myOtherSphere.copy(mySphere);
myOtherSphere.setPosition(3.0,4.0,10.0);
cout << "myOtherSphere has radius: " << myOtherSphere.getRadius() << endl;
cout << "myOtherSphere has X position: " << myOtherSphere.getXPosition() << endl;
vector<ball*> myBallArray;
//create a new ball
myBallArray.push_back(new ball);
//initialize the ball position
myBallArray[0]->setPosition(3.0,4.0,10.0);
myBallArray[0]->setRadius(20.0);
myBallArray[0]->setVelocity(0.2,0.0,1.0);
//generate a random number of balls to create between 0 and 200
int maxBallNumber = random()%200;
int ballNumber = 0;
while (1)
{
//report the ball position and velocity of the last ball created
cout << "myBall has position X: " << myBallArray[ballNumber]->getXPosition();
cout << " Y: " << myBallArray[ballNumber]->getYPosition();
cout << " Z: " << myBallArray[ballNumber]->getZPosition() << endl;
cout << "myBall has velocity X: " << myBallArray[ballNumber]->getXVelocity();
cout << " Y: " << myBallArray[ballNumber]->getYVelocity();
cout << " Z: " << myBallArray[ballNumber]->getZVelocity() << endl;
for ( i=0; i<ballNumber; i++)
{
//simulate the ball flight
myBallArray[i]->fall();
//start the ball again if resting
if (myBallArray[i]->getZPosition() <= 0.0)
{
myBallArray[i]->setPosition(3.0,4.0,10.0);
myBallArray[i]->setVelocity(0.2,0.0,1.0);
}
}
if (ballNumber < maxBallNumber)
{
//increment the number of balls in flight
ballNumber++;
//create a new ball
myBallArray.push_back(new ball);
//initialize the ball position
myBallArray[ballNumber]->setPosition(3.0,4.0,10.0);
myBallArray[ballNumber]->setRadius(20.0);
myBallArray[ballNumber]->setVelocity(0.2,0.0,1.0);
}
}
};