Game Development Reference
In-Depth Information
The GUI for the Soldier Game is defined in the
SoldierGame
class. As with the other GUI
classes in this topic, we won't go over every detail of the
SoldierGame
class but instead focus on
the Monte Carlo aspects of the code. The complete
SoldierGame
class code listing can be down-
loaded from the Apress website.
The first thing the
SoldierGame
class does is to declare the fields used by the class. Besides
the fields corresponding to the GUI components, the class also declares an array of
Soldier
objects. As was the case with some of the other game examples, a
Timer
object is used to slow
the action down.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.BevelBorder;
import java.awt.event.*;
import java.util.Random;
import javax.swing.Timer;
public class SoldierGame extends JFrame implements ActionListener
{
// Other field declarations not shown
private Soldier soldier[];
private SoldierUpdater soldierUpdater;
private Timer soldierTimer;
The
SoldierGame
constructor initializes the GUI and
Timer
components used by the game.
Thirty soldiers are simulated in this game. The constructor initializes the 30 individual
Soldier
objects by setting their initial x- and y-locations and speed. The soldiers are initially arranged
in two rows at the top of the square display area.
public SoldierGame() {
// Create an array of 30 soldiers and set their
// x- and y-locations.
soldier = new Soldier[30];
for(int j=0; j<15; ++j) {
soldier[j] = new Soldier();
soldier[j].setXLocation(15.0 + j*10.0);
soldier[j].setYLocation(10.0);
soldier[j].setSpeed(10.0);
soldier[j+15] = new Soldier();
soldier[j+15].setXLocation(20.0 + j*10.0);
soldier[j+15].setYLocation(20.0);
soldier[j+15].setSpeed(10.0);
}
// GUI and Timer component initialization not shown.