CEN-3024-Code-Implementation/Vehicle.java

80 lines
2.7 KiB
Java

import java.util.concurrent.*;
public class Vehicle implements Runnable{
private int currentSpeed;
private int targetSpeed;
private double fuelLevel;
private int distanceRemaining;
Route currentRoute;
public void run() {
navigateRoute();
}
public Vehicle() {
fuelLevel = getFuelLevel();
currentSpeed = 0;
}
public void setTargetSpeed(int newSpeed) {targetSpeed = newSpeed;}
public int getCurrentSpeed() {return currentSpeed;}
public double getFuelLevel() {return fuelLevel;}
public void updateFuelLevel() {
//would check fuel sensor and update accordingly
fuelLevel = 0.75;
}
public void navigateRoute() {
System.out.println("Start navigation");
for (String[] el : currentRoute.getSelectedRouteSteps()) {
boolean turnCompleted = false; //flag to validate completion of moveset instruction
targetSpeed = Integer.parseInt(el[2]);
while (!turnCompleted) {
if (currentSpeed < 15 || el[0] == "STRAIGHT") {
changeDirection(el[0]);
turnCompleted = true;
} else {
applyBrakes();
}
}
while (distanceRemaining > 0.2) {
System.out.println(distanceRemaining + " to next instruction");
distanceRemaining -= (currentSpeed/3600); //travel distance in one second
controlThrottle();
try {TimeUnit.MINUTES.sleep(1);} //sleep action for 1 second to simulate continuous movement
catch (InterruptedException e) {System.err.println("Sleep interrupted");}
}
}
}
public void changeDirection(String direction) {
switch (direction) {
case "LEFT":
System.out.println("Turning left...");
break;
case "RIGHT":
System.out.println("Turning right...");
break;
case "STRAIGHT":
System.out.println("Continuing straight...");
break;
}
}
public void controlThrottle() {
if (currentSpeed < targetSpeed && (targetSpeed - currentSpeed) > 6) { //normal acceleration
currentSpeed += 6;
} else if (currentSpeed < targetSpeed && (targetSpeed - currentSpeed) < 6) { //partial acceleration to reach speed limit
currentSpeed += (currentSpeed - targetSpeed);
} else if (currentSpeed > targetSpeed) { //deceleration by coasting
currentSpeed -= 1;
}
}
public void applyBrakes() {
if (currentSpeed >= 10) {currentSpeed -= 10;}
else if (currentSpeed < 10) {currentSpeed = 0;}
}
}