Game Development Reference
In-Depth Information
The Start button is associated with an event listener (the
SoldierGame
class itself). When
the Start button is pressed, the
actionPerformed
method is called. This method calls the start
method on the
Timer
object that was declared in the class.
// The actionPerformed() method is called when
// the Start button is pressed.
public void actionPerformed(ActionEvent event) {
// Start the soldiers moving using a Timer object
// to slow down the action.
soldierTimer.start();
}
The
SoldierGame
class declares an inner class named
GameUpdater
that declares its own
actionPerformed
method. The
Timer
object is set up to call this
actionPerformed
method every
1 second. It is this method that computes the speed of each soldier and updates his position on
the screen. The first thing the method does is to obtain the values of the mean and standard
deviation from the text field components. It then creates a
Random
object to generate the random
numbers needed by the method.
public void actionPerformed(ActionEvent event) {
// Extract sample size number from text.field.
double mean = Double.parseDouble(meanTextField.getText());
double sigma = Double.parseDouble(sigmaTextField.getText());
// Create a Random object to generate random
// numbers. The object is seeded with the time
// in milliseconds from Jan 1, 1970.
Random random = new Random();
The
actionPerformed
method then updates the speed for each of the 30 soldier objects.
The
Random
object is used to obtain a random number between 0 and 1. This number is treated
as a probability and is used to obtain a speed according to Equation (15.3). The distribution of
speeds will follow the Gaussian probability function.
// Update the speed of each soldier based on a
// Gaussian distribution and then update the
// position of each soldier based on the new speed.
double x;
double grp1;
double grp2;
double speed;
double t;
double newY;
double dt = 1.0;
for(int j=0; j<30; ++j) {
// Generate a random number between 0 and 1.
x = random.nextDouble();