Created
December 20, 2019 10:55
-
-
Save jasongorman/a2a86dd809199d5b590e0800b5eec4fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.codemanship.xmastrain; | |
public class TrainMotion { | |
private static final int SECONDS_PER_HOUR = 3600; | |
private static final int METRES_PER_KM = 1000; | |
private final double acceleration; | |
private final double topSpeed; | |
private double velocity; | |
private double distance; | |
private final Sensor sensor; | |
private double lastSensorDistance = 0; | |
public TrainMotion(double accelerationMs2, double initialVelocityKph, double topSpeedKph, double distanceKm, Sensor sensor) { | |
this.acceleration = accelerationMs2; | |
this.velocity = (initialVelocityKph * METRES_PER_KM) / SECONDS_PER_HOUR; | |
this.topSpeed = (topSpeedKph * METRES_PER_KM) / SECONDS_PER_HOUR; | |
this.distance = distanceKm * METRES_PER_KM; | |
this.sensor = sensor; | |
} | |
public void move(int timeMilliseconds) { | |
distance += distanceAdded(timeMilliseconds); | |
checkForSensorPass(); | |
} | |
private void checkForSensorPass() { | |
if (distance - lastSensorDistance >= METRES_PER_KM) { | |
sensor.passed(distance / METRES_PER_KM, velocity); | |
lastSensorDistance = distance; | |
} | |
} | |
double velocityAfterAcceleration(int timeMilliseconds) { | |
velocity = velocity + (acceleration * asSeconds(timeMilliseconds)); | |
if (velocity > topSpeed) | |
velocity = velocity - (velocity % topSpeed); | |
return velocity; | |
} | |
private int asSeconds(int timeMilliseconds) { | |
return timeMilliseconds / 1000; | |
} | |
double distanceAdded(int timeMilliseconds) { | |
double avgVelocity = (velocity + velocityAfterAcceleration(timeMilliseconds)) / 2; | |
return avgVelocity * (asSeconds(timeMilliseconds)); | |
} | |
double getDistanceTravelledKm() { | |
return distance / METRES_PER_KM; | |
} | |
double getVelocity() { | |
return velocity; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment