Java Reference
In-Depth Information
long velocity = 0; // 0 mm/s (= 0 m/s)
long height = 1000000; // 1000000 mm = 1000 m = 1 km
long fuel = 100000; // ms = 120 s = 2 min
long thrust = 0;
class Simulation extends Thread {
long time = System.currentTimeMillis();
public void run() {
do {
long dt = System.currentTimeMillis() - time;
velocity += ((GRAVITY - (ACCELERATION * thrust)
/ 100) * dt) / 1000;
height -= (velocity * dt) / 1000;
time += dt;
fuel -= (thrust * dt) / 100;
try {
EventQueue.invokeAndWait (screenManager);
}
catch (Exception e) {
throw new RuntimeException (e.toString());
}
}
while (height > 0);
}
}
The screenManager , which contains the run method indirectly called from the Simulation
object, is responsible for updating the user interface according to the simulation state. It also reads the
new thrust setting and determines if the lander has landed safely or crashed into the ground. The helper
method milliToStr() just converts the fine grained units to the usual units by dividing them by
1000. The maximum allowable landing speed is one meter per second:
static final long MAX_VELOCITY = 1099;
Label velocityDisplay = new Label();
Label heightDisplay = new Label();
Label fuelDisplay = new Label();
Scrollbar thrustSlider =
new Scrollbar (Scrollbar.HORIZONTAL, 0, 0, 0, 100);
ScreenManager screenManager = new ScreenManager();
class ScreenManager implements Runnable {
public String milliToStr (long milli) {
return (milli / 1000) + "." + Math.abs ((milli % 1000) / 100);
}
public void run() {
if (height <= 0)
heightDisplay.setText
(velocity <= MAX_VELOCITY ? "Landed" : "Crashed!");
else
heightDisplay.setText (milliToStr (height));
Search WWH ::




Custom Search