Lander in Java
Just thought I'd slip this one in here - a few days ago I thought I'd get the basics of the physics involved in the relationship between gravity and a rocket engine. With the most basic input and output I created the following program in java - the most familiar language to me.
import java.io.IOException;
public class Lander {
private static Lander instance;
private double height = 2000.0;
private double fuel = 300.0;
private double gravity = 3.0;
private double verticalSpeed = 0.0;
private double burnRate = 0.0;
private double step = 1.0;
public static void main(String args[]) {
instance = new Lander();
instance.run();
System.exit(0);
}
private void run() {
try {
boolean end = false;
while (!end) {
System.out.print("height: " + height);
System.out.print(" speed: " + verticalSpeed);
System.out.print(" burnRate: " + burnRate);
System.out.print(" fuel: " + fuel);
System.out.println();
input();
update(step);
Thread.sleep((long) (step * 1000));
end = (height <= 0.0);
}
if (verticalSpeed > -3.0) {
System.out.println("WELL DONE!");
} else {
System.out.println("CRASH!");
}
} catch (Exception e) {
System.err.println(e);
}
}
private void input() {
try {
if (System.in.available() > 0) {
char c = (char) System.in.read();
if (c == '-' && burnRate > 0.0) {
burnRate--;
} else if (c == '=' && burnRate < 6.0) {
burnRate++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void update(double elapsed) {
verticalSpeed -= (gravity * elapsed);
height = height + verticalSpeed;
if (height < 0.0) {
height = 0.0;
}
double burn = (burnRate * elapsed);
if (fuel > 0.0) {
if (burn > fuel) {
burn = fuel;
}
fuel -= burn;
} else {
burn = 0.0;
}
verticalSpeed += burn;
}
}