Compare commits

...
Author SHA1 Message Date
romanschenk37 6ac4f64456 Javadoc in PathFollowerMoveStrategy.java 2022-03-23 08:55:32 +01:00
romanschenk37 45918124df refactoring and javadoc in PathFollowerMoveStrategy.javaa 2022-03-23 08:48:46 +01:00
romanschenk37 c59e4a30d8 Update MoveListStrategy.java 2022-03-22 18:31:15 +01:00
romanschenk37 eddf9d3daa implemented PathFollowerMoveStrategy.java 2022-03-22 18:20:23 +01:00
Andrin Fassbind b467a79596 Changed mainClass in build.gradle to Main 2022-03-20 13:44:54 +01:00
fassband d7a593be30 Merge pull request #27 from PM2-IT21bWIN-ruiz-mach-krea/GameTest
GameTest startet
2022-03-20 13:40:48 +01:00
Andrin Fassbind 8826561963 GameTest startet
++ Game and Main clean up
2022-03-19 13:20:19 +01:00
romanschenk37 a80ea0fa1c fix doCarTurn in Game.java 2022-03-18 22:01:03 +01:00
romanschenk37 fc78b10365 optimized Main Class. added Method quit to UserInterface.java 2022-03-18 21:48:27 +01:00
romanschenk37 fec3aceaa6 Merge pull request #26 from PM2-IT21bWIN-ruiz-mach-krea/MoveListFeature
Move list feature
2022-03-18 20:54:27 +01:00
romanschenk37 833b122d2b Update Game.java
Removed System.out.println...
2022-03-18 20:54:04 +01:00
fassband 67c5a79174 Merge pull request #25 from PM2-IT21bWIN-ruiz-mach-krea/track-feature
Track feature
2022-03-18 19:57:18 +01:00
Andrin Fassbind 837297cd31 MoveListStrategy implemented 2022-03-18 19:44:47 +01:00
Andrin Fassbind c30d7a2988 merge 2022-03-18 18:20:28 +01:00
Andrin Fassbind 21da4feaf5 dev MoveListStrategy and test 2022-03-18 18:02:10 +01:00
romanschenk37 dad57ea8ac fix in CardoesCrash in Track.java (remove Car when crash) 2022-03-18 17:32:16 +01:00
romanschenk37 e6fc0fde39 fix in makeCarMoveInTrack in Track.java (redraw finish line if car was on finish line) 2022-03-18 17:23:50 +01:00
romanschenk37 9869e8e74d fix in getWinner in Game.java 2022-03-18 16:48:37 +01:00
romanschenk37 1c618ad09a change in gamephase in Game.java 2022-03-18 16:45:16 +01:00
romanschenk37 3684b5589e fixes in Game.java and Track.java 2022-03-18 16:13:37 +01:00
romanschenk37 fd4513e0d0 fixes in Game.java 2022-03-18 15:37:17 +01:00
10 changed files with 539 additions and 132 deletions
+1 -1
View File
@@ -44,7 +44,7 @@ version = '2022.1'
application { application {
// Define the main class for the application. // Define the main class for the application.
mainClass = 'ch.zhaw.pm2.racetrack.ConsoleApp' mainClass = 'ch.zhaw.pm2.racetrack.Main'
} }
run { run {
+19
View File
@@ -0,0 +1,19 @@
(X:40, Y:22)
(X:43, Y:22)
(X:46, Y:21)
(X:48, Y:19)
(X:48, Y:17)
(X:46, Y:15)
(X:41, Y:13)
(X:41, Y:10)
(X:46, Y:9)
(X:49, Y:4)
(X:40, Y:2)
(X:30, Y:2)
(X:21, Y:3)
(X:16, Y:7)
(X:13, Y:10)
(X:14, Y:14)
(X:11, Y:19)
(X:13, Y:22)
(X:24, Y:22)
+168 -104
View File
@@ -1,10 +1,7 @@
package ch.zhaw.pm2.racetrack; package ch.zhaw.pm2.racetrack;
import ch.zhaw.pm2.racetrack.given.GameSpecification; import ch.zhaw.pm2.racetrack.given.GameSpecification;
import ch.zhaw.pm2.racetrack.strategy.DoNotMoveStrategy; import ch.zhaw.pm2.racetrack.strategy.*;
import ch.zhaw.pm2.racetrack.strategy.MoveListStrategy;
import ch.zhaw.pm2.racetrack.strategy.PathFollowerMoveStrategy;
import ch.zhaw.pm2.racetrack.strategy.UserMoveStrategy;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@@ -21,7 +18,7 @@ import static ch.zhaw.pm2.racetrack.PositionVector.Direction;
public class Game implements GameSpecification { public class Game implements GameSpecification {
public static final int NO_WINNER = -1; public static final int NO_WINNER = -1;
private Track track; private Track track;
int currentCarIndex; private int currentCarIndex;
UserInterface userInterface; UserInterface userInterface;
@@ -30,54 +27,92 @@ public class Game implements GameSpecification {
} }
public boolean initPhase() throws InvalidTrackFormatException, FileNotFoundException { public boolean initPhase() throws InvalidTrackFormatException {
File folder = new File("tracks"); File folder = new File("tracks");
File[] listOfFiles = folder.listFiles(); File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0) { if (listOfFiles.length > 0) {
List<String> tracks = new ArrayList<>(); List<String> tracks = new ArrayList<>();
for(File file : listOfFiles){ for (File file : listOfFiles) {
tracks.add(file.getName()); tracks.add(file.getName());
} }
File selectedTrack = listOfFiles[userInterface.selectOption("Select Track file", tracks)]; File selectedTrack = listOfFiles[userInterface.selectOption("Select Track file", tracks)];
try { selectTrack(selectedTrack);
track = new Track(selectedTrack);
} catch (FileNotFoundException | PositionVectorNotValid e) {
e.printStackTrace();
}
List<String> moveStrategies = new ArrayList<>(); List<String> moveStrategies = new ArrayList<>();
moveStrategies.add("Do not move Strategy"); moveStrategies.add("Do not move Strategy");
moveStrategies.add("User Move Strategy"); moveStrategies.add("User Move Strategy");
moveStrategies.add("Move List Strategy"); moveStrategies.add("Move List Strategy");
moveStrategies.add("Path Follow Move Strategy"); moveStrategies.add("Path Follow Move Strategy");
for(int i = 0; i < track.getCarCount() ; i++ ) { for (int i = 0; i < track.getCarCount(); i++) {
int moveStrategie = userInterface.selectOption( Car car = track.getCar(i);
"Select Strategy for Car " + i + " (" + track.getCarId(i) + ")", moveStrategies); MoveStrategy moveStrategy = null;
switch (moveStrategie + 1) { //TODO: set Movestrategy with method in Track while (moveStrategy == null) {
case 1: String filePath;
track.getCar(i).setMoveStrategy(new DoNotMoveStrategy()); //TODO: add Arguments int moveStrategie = userInterface.selectOption(
break; "Select Strategy for Car " + i + " (" + track.getCarId(i) + ")", moveStrategies);
case 2: switch (moveStrategie + 1) {
track.getCar(i).setMoveStrategy(new UserMoveStrategy(userInterface, i, track.getCarId(i))); //TODO: add Arguments case 1:
break; moveStrategy = new DoNotMoveStrategy();
case 3: break;
track.getCar(i).setMoveStrategy(new MoveListStrategy()); //TODO: add Arguments case 2:
break; moveStrategy = new UserMoveStrategy(userInterface, i, track.getCarId(i));
case 4: break;
track.getCar(i).setMoveStrategy(new PathFollowerMoveStrategy()); //TODO: add Arguments case 3:
break; filePath = ".\\moves\\" + selectedTrack.getName().split("\\.")[0] + "-car-" + track.getCar(i).getID() + ".txt";
try {
moveStrategy = new MoveListStrategy(filePath);
} catch (FileNotFoundException e) {
userInterface.printInformation("There is no Move-List implemented. Choose another Strategy!");
}
//TODO: Backslash kompatibel für Linux
break;
case 4:
filePath = ".\\follower\\" + selectedTrack.getName().split("\\.")[0] + "_points.txt";
try {
moveStrategy = new PathFollowerMoveStrategy(filePath, track.getCarPos(i));
} catch (FileNotFoundException e) {
userInterface.printInformation("There is no Point-List implemented. Choose another Strategy!");
}
break;
}
} }
selectMoveStrategy(car, moveStrategy);
} }
return true; return true;
} } else {
else{
userInterface.printInformation("No Trackfile found!"); userInterface.printInformation("No Trackfile found!");
return false; return false;
} }
} }
/**
* The functionality was taken out of init to automate testing
*
* @param selectedTrack
*/
Track selectTrack(File selectedTrack) {
try {
track = new Track(selectedTrack);
return track;
} catch (FileNotFoundException | PositionVectorNotValid | InvalidTrackFormatException e) {
e.printStackTrace();
}
return null;
}
/**
* The functionality was taken out of init to automate testing
*
* @param car to set the MoveStrategy
* @param strategy The movestrategy to set
*/
void selectMoveStrategy(Car car, MoveStrategy strategy) {
car.setMoveStrategy(strategy);
}
/** /**
* Return the index of the current active car. * Return the index of the current active car.
* Car indexes are zero-based, so the first car is 0, and the last car is getCarCount() - 1. * Car indexes are zero-based, so the first car is 0, and the last car is getCarCount() - 1.
*
* @return The zero-based number of the current car * @return The zero-based number of the current car
*/ */
@Override @Override
@@ -87,6 +122,7 @@ public class Game implements GameSpecification {
/** /**
* Get the id of the specified car. * Get the id of the specified car.
*
* @param carIndex The zero-based carIndex number * @param carIndex The zero-based carIndex number
* @return A char containing the id of the car * @return A char containing the id of the car
*/ */
@@ -97,6 +133,7 @@ public class Game implements GameSpecification {
/** /**
* Get the position of the specified car. * Get the position of the specified car.
*
* @param carIndex The zero-based carIndex number * @param carIndex The zero-based carIndex number
* @return A PositionVector containing the car's current position * @return A PositionVector containing the car's current position
*/ */
@@ -107,6 +144,7 @@ public class Game implements GameSpecification {
/** /**
* Get the velocity of the specified car. * Get the velocity of the specified car.
*
* @param carIndex The zero-based carIndex number * @param carIndex The zero-based carIndex number
* @return A PositionVector containing the car's current velocity * @return A PositionVector containing the car's current velocity
*/ */
@@ -117,14 +155,17 @@ public class Game implements GameSpecification {
/** /**
* Return the winner of the game. If the game is still in progress, returns NO_WINNER. * Return the winner of the game. If the game is still in progress, returns NO_WINNER.
*
* @return The winning car's index (zero-based, see getCurrentCar()), or NO_WINNER if the game is still in progress * @return The winning car's index (zero-based, see getCurrentCar()), or NO_WINNER if the game is still in progress
*/ */
@Override @Override
public int getWinner() { public int getWinner() {
List<Car> cars = track.getCars(); if (onlyOneCarLeft()) {
for (Car car: cars) { return currentCarIndex;
if(car.getWinPoints() == 1){ }
return car.getID(); for (int i = 0; i < track.getCarCount(); i++) {
if (track.getCar(i).getWinPoints() == 1) {
return i;
} }
} }
return NO_WINNER; return NO_WINNER;
@@ -158,37 +199,47 @@ public class Game implements GameSpecification {
*/ */
@Override @Override
public void doCarTurn(Direction acceleration) throws PositionVectorNotValid { public void doCarTurn(Direction acceleration) throws PositionVectorNotValid {
// TODO: implementation
track.getCar(currentCarIndex).accelerate(acceleration); track.getCar(currentCarIndex).accelerate(acceleration);
PositionVector crashPosition = null; PositionVector crashPosition = null;
List<PositionVector> positionList = calculatePath(track.getCarPos(currentCarIndex),track.getCar(currentCarIndex).nextPosition()); List<PositionVector> positionList = calculatePath(track.getCarPos(currentCarIndex), track.getCar(currentCarIndex).nextPosition());
//TODO: check if Method calculatePath contains endposition for (int i = 0; i < positionList.size(); i++) {
for(PositionVector location : positionList) { //todo: check if order must be reversed if (willCarCrash(currentCarIndex, positionList.get(i))) {
if(willCarCrash(currentCarIndex, location)) { if (i == 0) {
crashPosition = location; crashPosition = track.getCarPos(currentCarIndex);
} else {
crashPosition = positionList.get(i - 1);
}
break;
} }
} }
if(crashPosition != null) { if (crashPosition != null) {
track.carDoesCrash(currentCarIndex, crashPosition); track.carDoesCrash(currentCarIndex, crashPosition);
} } else {
else {
track.moveCar(currentCarIndex);
calculateWinner(track.getCarPos(currentCarIndex), track.getCar(currentCarIndex).nextPosition(), currentCarIndex); calculateWinner(track.getCarPos(currentCarIndex), track.getCar(currentCarIndex).nextPosition(), currentCarIndex);
track.moveCar(currentCarIndex);
} }
} }
public int gamePhase() throws PositionVectorNotValid { public String gamePhase() throws PositionVectorNotValid {
while (getWinner() == NO_WINNER) { while (carsMoving() && getWinner() == NO_WINNER) {
userInterface.printTrack(track); userInterface.printTrack(track);
Direction direction = track.getCar(currentCarIndex).getMoveStrategy().nextMove(); Direction direction;
doCarTurn(direction); direction = track.getCar(currentCarIndex).getMoveStrategy().nextMove();
if(allCarsCrashed()) { if (direction == null) {
return NO_WINNER; track.getCar(currentCarIndex).setMoveStrategy(new DoNotMoveStrategy());
direction = track.getCar(currentCarIndex).getMoveStrategy().nextMove(); //TODO: Entfernen?
}else {
doCarTurn(direction);
} }
switchToNextActiveCar(); switchToNextActiveCar();
} }
return getWinner(); userInterface.printTrack(track);
int indexWinner = getWinner();
if (indexWinner == NO_WINNER) {
return null;
}
return String.valueOf(track.getCar(indexWinner).getID());
} }
/** /**
@@ -199,9 +250,8 @@ public class Game implements GameSpecification {
do { do {
if ((currentCarIndex + 1) == track.getCarCount()) { if ((currentCarIndex + 1) == track.getCarCount()) {
currentCarIndex = 0; currentCarIndex = 0;
} } else {
else { currentCarIndex++;
currentCarIndex ++;
} }
} while (track.getCar(currentCarIndex).isCrashed()); } while (track.getCar(currentCarIndex).isCrashed());
// TODO: evtl andere Kapselung // TODO: evtl andere Kapselung
@@ -215,8 +265,9 @@ public class Game implements GameSpecification {
* - Detect which axis of the distance vector is longer (faster movement) * - Detect which axis of the distance vector is longer (faster movement)
* - for each pixel on the 'faster' axis calculate the position on the 'slower' axis. * - for each pixel on the 'faster' axis calculate the position on the 'slower' axis.
* Direction of the movement has to correctly considered * Direction of the movement has to correctly considered
*
* @param startPosition Starting position as a PositionVector * @param startPosition Starting position as a PositionVector
* @param endPosition Ending position as a PositionVector * @param endPosition Ending position as a PositionVector
* @return Intervening grid positions as a List of PositionVector's, including the starting and ending positions. * @return Intervening grid positions as a List of PositionVector's, including the starting and ending positions.
*/ */
@Override @Override
@@ -244,20 +295,24 @@ public class Game implements GameSpecification {
int distanceSlowAxis, distanceFastAxis; int distanceSlowAxis, distanceFastAxis;
if (distX > distY) { if (distX > distY) {
// x axis is the 'fast' direction // x axis is the 'fast' direction
parallelStepX = dirX; parallelStepY = 0; // parallel step only moves in x direction parallelStepX = dirX;
diagonalStepX = dirX; diagonalStepY = dirY; // diagonal step moves in both directions parallelStepY = 0; // parallel step only moves in x direction
diagonalStepX = dirX;
diagonalStepY = dirY; // diagonal step moves in both directions
distanceSlowAxis = distY; distanceSlowAxis = distY;
distanceFastAxis = distX; distanceFastAxis = distX;
} else { } else {
// y axis is the 'fast' direction // y axis is the 'fast' direction
parallelStepX = 0; parallelStepY = dirY; // parallel step only moves in y direction parallelStepX = 0;
diagonalStepX = dirX; diagonalStepY = dirY; // diagonal step moves in both directions parallelStepY = dirY; // parallel step only moves in y direction
diagonalStepX = dirX;
diagonalStepY = dirY; // diagonal step moves in both directions
distanceSlowAxis = distX; distanceSlowAxis = distX;
distanceFastAxis = distY; distanceFastAxis = distY;
} }
int error = distanceFastAxis/2; int error = distanceFastAxis / 2;
for(int step = 0; step < distanceFastAxis; step ++) { for (int step = 0; step < distanceFastAxis; step++) {
error -= distanceSlowAxis; error -= distanceSlowAxis;
if (error < 0) { if (error < 0) {
error += distanceFastAxis; // correct error value to be positive again error += distanceFastAxis; // correct error value to be positive again
@@ -270,55 +325,54 @@ public class Game implements GameSpecification {
y += parallelStepY; y += parallelStepY;
} }
pathList.add(new PositionVector(x,y)); pathList.add(new PositionVector(x, y));
} }
return pathList; return pathList;
} }
private void calculateWinner(PositionVector start, PositionVector finish, int carIndex ) { private void calculateWinner(PositionVector start, PositionVector finish, int carIndex) {
List<PositionVector> path = calculatePath(start, finish); List<PositionVector> path = calculatePath(start, finish);
for (PositionVector point : path){ for (PositionVector point : path) {
switch (track.getSpaceType(point)) { if (track.getSpaceType(point) != null) {
case FINISH_UP: switch (track.getSpaceType(point)) {
if(start.getY() < finish.getY()) { case FINISH_UP:
track.getCar(carIndex).increaseWinPoints(); if (start.getY() < finish.getY()) {
} track.getCar(carIndex).increaseWinPoints();
else if(start.getY() > finish.getY()) { } else if (start.getY() > finish.getY()) {
track.getCar(carIndex).deductWinPoints(); track.getCar(carIndex).deductWinPoints();
} }
break; break;
case FINISH_DOWN: case FINISH_DOWN:
if(start.getY() > finish.getY()){ if (start.getY() > finish.getY()) {
track.getCar(carIndex).increaseWinPoints(); track.getCar(carIndex).increaseWinPoints();
} } else if (start.getY() < finish.getY()) {
else if (start.getY() < finish.getY()){ track.getCar(carIndex).deductWinPoints();
track.getCar(carIndex).deductWinPoints(); }
} break;
break; case FINISH_RIGHT:
case FINISH_RIGHT: if (start.getX() < finish.getX()) {
if(start.getX() < finish.getX()){ track.getCar(carIndex).increaseWinPoints();
track.getCar(carIndex).increaseWinPoints(); } else if (start.getX() > finish.getX()) {
} track.getCar(carIndex).deductWinPoints();
else if (start.getX() > finish.getX()){ }
track.getCar(carIndex).deductWinPoints(); break;
} case FINISH_LEFT:
break; if (start.getX() > finish.getX()) {
case FINISH_LEFT: track.getCar(carIndex).increaseWinPoints();
if(start.getX() > finish.getX()){ } else if (start.getX() < finish.getX()) {
track.getCar(carIndex).increaseWinPoints(); track.getCar(carIndex).increaseWinPoints();
} }
else if (start.getX() < finish.getX()){ break;
track.getCar(carIndex).increaseWinPoints();
}
break;
} }
}
}
}
} }
/** /**
* Does indicate if a car would have a crash with a WALL space or another car at the given position. * Does indicate if a car would have a crash with a WALL space or another car at the given position.
*
* @param carIndex The zero-based carIndex number * @param carIndex The zero-based carIndex number
* @param position A PositionVector of the possible crash position * @param position A PositionVector of the possible crash position
* @return A boolean indicator if the car would crash with a WALL or another car. * @return A boolean indicator if the car would crash with a WALL or another car.
@@ -328,12 +382,22 @@ public class Game implements GameSpecification {
return track.willCrashAtPosition(carIndex, position); return track.willCrashAtPosition(carIndex, position);
} }
public boolean allCarsCrashed() { public boolean onlyOneCarLeft() {
for(int carIndex = 0; carIndex < track.getCarCount(); carIndex ++) { int carsLeft = 0;
if(! track.getCar(carIndex).isCrashed()) { for (int carIndex = 0; carIndex < track.getCarCount(); carIndex++) {
return false; if (!track.getCar(carIndex).isCrashed()) {
carsLeft++;
} }
} }
return true; return !(carsLeft > 1);
}
public boolean carsMoving() {
for (int carIndex = 0; carIndex < track.getCarCount(); carIndex++) {
if (!(track.getCar(carIndex).isCrashed() || track.getCar(carIndex).getMoveStrategy().getClass() == DoNotMoveStrategy.class)) {
return true;
}
}
return false;
} }
} }
+23 -11
View File
@@ -6,23 +6,35 @@ import java.util.List;
public class Main { public class Main {
public static void main(String[] args) throws InvalidTrackFormatException, FileNotFoundException, PositionVectorNotValid { public static void main(String[] args) throws InvalidTrackFormatException, PositionVectorNotValid {
boolean exit = false; UserInterface userInterface = new UserInterface("Hello and Welcome to Racetrack by Team02-\"AngryNerds\"");
while (!exit) { while (true) {
UserInterface userInterface = new UserInterface("Hello and Welcome");
Game game = new Game(userInterface); Game game = new Game(userInterface);
int winner = 0; String winner;
if (game.initPhase()) { if (game.initPhase()) {
winner = game.gamePhase(); winner = game.gamePhase();
List<String> optionsNewGame = new ArrayList<>();
optionsNewGame.add("exit");
optionsNewGame.add("new game");
String winnerText;
if(winner == null){
winnerText = "There was no winner.";
}
else {
winnerText = "The Winner was Car " + winner;
}
int selectedOption = userInterface.selectOption(winnerText + "\nStart new Game?", optionsNewGame);
if(selectedOption == 0) {
userInterface.quit("Thank you and goodbye\npress enter to close the application.");
break;
}
} }
List<String> optionsNewGame = new ArrayList<>(); else {
optionsNewGame.add("exit"); userInterface.quit("The initialisation of the game failed. Press enter to close the application.");
optionsNewGame.add("new game"); break;
int selectedOption = userInterface.selectOption("The Winner was Car : " + winner + "\nStart new Game?", optionsNewGame);
if(selectedOption == 0) {
exit = true;
} }
} }
} }
} }
+27 -12
View File
@@ -60,6 +60,7 @@ public class Track implements TrackSpecification {
private List<String> track; private List<String> track;
private List<Car> cars; private List<Car> cars;
private final List<PositionVector> finishLine; private final List<PositionVector> finishLine;
private ConfigSpecification.SpaceType finishTyp;
/** /**
* Initialize a Track from the given track file. * Initialize a Track from the given track file.
@@ -132,7 +133,7 @@ public class Track implements TrackSpecification {
if (finishLine.size() == 0) { if (finishLine.size() == 0) {
throw new InvalidTrackFormatException(); throw new InvalidTrackFormatException();
} }
ConfigSpecification.SpaceType finishTyp = getSpaceType(finishLine.get(0)); finishTyp = getSpaceType(finishLine.get(0));
for (PositionVector positionVector : finishLine) { for (PositionVector positionVector : finishLine) {
if (getSpaceType(positionVector) != finishTyp) { if (getSpaceType(positionVector) != finishTyp) {
throw new InvalidTrackFormatException(); throw new InvalidTrackFormatException();
@@ -207,12 +208,20 @@ public class Track implements TrackSpecification {
* @param carIndex of the current car * @param carIndex of the current car
*/ */
private void makeCarMoveInTrack(int carIndex) { private void makeCarMoveInTrack(int carIndex) {
PositionVector positionVector = findChar(getCarId(carIndex)); PositionVector carPositionVector = findChar(getCarId(carIndex));
//Removes the Car at Current Pos //Removes the Car at Current Pos
drawCharOnTrackIndicator(positionVector, ConfigSpecification.SpaceType.TRACK.getValue()); drawCharOnTrackIndicator(carPositionVector, ConfigSpecification.SpaceType.TRACK.getValue());
//Redraw finishline if Car was on finish-line Position
for(PositionVector finishLinePositionVector : finishLine){
if(finishLinePositionVector.equals(carPositionVector)){
drawCharOnTrackIndicator(carPositionVector, finishTyp.getValue());
}
}
//Adds Car at new Position //Adds Car at new Position
positionVector = cars.get(carIndex).nextPosition(); carPositionVector = cars.get(carIndex).nextPosition();
drawCharOnTrackIndicator(positionVector, cars.get(carIndex).getID()); drawCharOnTrackIndicator(carPositionVector, cars.get(carIndex).getID());
} }
/** /**
@@ -222,24 +231,30 @@ public class Track implements TrackSpecification {
* @return true if car would crash. Else false. * @return true if car would crash. Else false.
*/ */
public boolean willCrashAtPosition(int carIndex, PositionVector positionVector) throws PositionVectorNotValid { public boolean willCrashAtPosition(int carIndex, PositionVector positionVector) throws PositionVectorNotValid {
isPositionVectorOnTrack(positionVector); isPositionVectorOnTrack(positionVector); //TODO: remove this line? Or Method?
char charAtPosition = track.get(positionVector.getY()).charAt(positionVector.getX()); char charAtPosition = track.get(positionVector.getY()).charAt(positionVector.getX());
if (getCarId(carIndex) == charAtPosition) return false; if (getCarId(carIndex) == charAtPosition) return false;
return (charAtPosition == ConfigSpecification.SpaceType.WALL.value); return !(charAtPosition == ConfigSpecification.SpaceType.TRACK.value ||
charAtPosition == ConfigSpecification.SpaceType.FINISH_RIGHT.value ||
charAtPosition == ConfigSpecification.SpaceType.FINISH_LEFT.value ||
charAtPosition == ConfigSpecification.SpaceType.FINISH_UP.value ||
charAtPosition == ConfigSpecification.SpaceType.FINISH_DOWN.value);
} }
/** /**
* This Method will make the Car Crash. In Track and in the Car Object * This Method will make the Car Crash. In Track and in the Car Object
* *
* @param carIndex representing current Car * @param carIndex representing current Car
* @param positionVector where the Crash did happen * @param crashPositionVector where the Crash did happen
*/ */
public void carDoesCrash(int carIndex, PositionVector positionVector) throws PositionVectorNotValid{ public void carDoesCrash(int carIndex, PositionVector crashPositionVector) throws PositionVectorNotValid{
isPositionVectorOnTrack(positionVector); isPositionVectorOnTrack(crashPositionVector); //TODO: remove this line? and Method?
PositionVector currentCarPosition = getCarPos(carIndex);
drawCharOnTrackIndicator(new PositionVector(currentCarPosition.getX(), currentCarPosition.getY()), ConfigSpecification.SpaceType.TRACK.getValue());
Car car = cars.get(carIndex); Car car = cars.get(carIndex);
car.crash(); car.crash();
car.setPosition(positionVector); car.setPosition(crashPositionVector);
drawCharOnTrackIndicator(new PositionVector(positionVector.getX(), positionVector.getY()), CRASH_INDICATOR); drawCharOnTrackIndicator(new PositionVector(crashPositionVector.getX(), crashPositionVector.getY()), CRASH_INDICATOR);
} }
/** /**
@@ -97,6 +97,15 @@ public class UserInterface {
textTerminal.println(track.toString()); textTerminal.println(track.toString());
} }
/**
* Method to dispose the Textterminal
* @param text OUtput Text
*/
public void quit(String text){
textIO.newStringInputReader().withMinLength(0).read(text);
textTerminal.dispose();
}
} }
@@ -2,11 +2,44 @@ package ch.zhaw.pm2.racetrack.strategy;
import ch.zhaw.pm2.racetrack.PositionVector.Direction; import ch.zhaw.pm2.racetrack.PositionVector.Direction;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MoveListStrategy implements MoveStrategy { public class MoveListStrategy implements MoveStrategy {
private List<Direction> moveList;
private int pointer;
public MoveListStrategy(String path) throws FileNotFoundException{
moveList = new ArrayList<>();
pointer = -1;
readFile(new File(path));
}
private void readFile(File trackFile) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileInputStream(trackFile), "UTF-8");
Direction[] directions = Direction.values();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
for (Direction direction : directions) {
if (direction.toString().equals(line)) {
moveList.add(direction);
break;
}
}
}
}
@Override @Override
public Direction nextMove() { public Direction nextMove() {
// TODO: implementation pointer += 1;
throw new UnsupportedOperationException(); if (pointer < moveList.size()) {
return moveList.get(pointer);
}
return null;
} }
} }
@@ -1,15 +1,126 @@
package ch.zhaw.pm2.racetrack.strategy; package ch.zhaw.pm2.racetrack.strategy;
import ch.zhaw.pm2.racetrack.PositionVector;
import ch.zhaw.pm2.racetrack.PositionVector.Direction; import ch.zhaw.pm2.racetrack.PositionVector.Direction;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/** /**
* The PathFollowerMoveStrategy class determines the next move based on a file containing points on a path. * The PathFollowerMoveStrategy class determines the next move based on a file containing points on a path.
*/ */
public class PathFollowerMoveStrategy implements MoveStrategy { public class PathFollowerMoveStrategy implements MoveStrategy {
/**
* The current Position of the car.
*/
private PositionVector currentPosition;
/**
* The current Velocity of the car.
*/
private PositionVector currentVelocity;
/**
* List of all points on the path.
*/
private ArrayList<PositionVector> pointList;
/**
* The index of the next point on the path.
*/
private int pointer;
/**
* Constructor to create a new PathFollowerMoveStrategy for a car.
* @param path The location where the file is saved
* @param startPosition The start position of the car
* @throws FileNotFoundException If the file with the given path does not exist.
*/
public PathFollowerMoveStrategy(String path, PositionVector startPosition) throws FileNotFoundException {
pointList = new ArrayList<>();
pointer = 0;
readFile(new File(path));
currentPosition = startPosition;
currentVelocity = new PositionVector(0, 0);
}
/**
* Method to read the given File and add the points to the pointList
* @param trackFile the File Object which should be read
* @throws FileNotFoundException If the file with the given path does not exist.
*/
public void readFile(File trackFile) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileInputStream(trackFile), "UTF-8");
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] coordinates = line.split("(\\(X:|, Y:|\\))");
pointList.add(new PositionVector(Integer.parseInt(coordinates[1]), Integer.parseInt(coordinates[2])));
}
}
/**
* Method to select the direction for the next move.
* @return The direction for the next move. null if there are no points left in the list.
*/
@Override @Override
public Direction nextMove() { public Direction nextMove() {
// TODO: implementation // if no more points in the list --> return null
throw new UnsupportedOperationException(); if (pointer >= pointList.size()) {
return null;
}
// increase pointer variable if the next point is reached.
if (pointList.get(pointer).equals(currentPosition)) {
pointer ++;
}
// calculate Vector from current Position to next Point
PositionVector movementVector = new PositionVector(pointList.get(pointer).getX() - currentPosition.getX(), pointList.get(pointer).getY() - currentPosition.getY());
// select acceleration for X
int accelerationX;
if((movementVector.getX() == 0 && currentVelocity.getX() > 0) || //reduce velocity to 0 if the destination coordinate is reached
(movementVector.getX() > 0 && movementVector.getX()/2.0 <= currentVelocity.getX()) || //increase velocity
(movementVector.getX() < 0 && movementVector.getX()/2.0 < currentVelocity.getX())){ //reduce velocity
accelerationX = -1;
} else if((movementVector.getX() == 0 && currentVelocity.getX() < 0) || //reduce velocity to 0 if the destination coordinate is reached
(movementVector.getX() > 0 && movementVector.getX()/2.0 > currentVelocity.getX()) || //increase velocity
(movementVector.getX() < 0 && movementVector.getX()/2.0 >= currentVelocity.getX())) { //reduce velocity
accelerationX = 1;
}
else { //no acceleration
accelerationX = 0;
}
// select acceleration for Y
int accelerationY;
if((movementVector.getY() == 0 && currentVelocity.getY() > 0) || //reduce velocity to 0 if the destination coordinate is reached
(movementVector.getY() > 0 && movementVector.getY()/2.0 <= currentVelocity.getY()) || //increase velocity
(movementVector.getY() < 0 && movementVector.getY()/2.0 < currentVelocity.getY())){ //reduce velocity
accelerationY = -1;
} else if((movementVector.getY() == 0 && currentVelocity.getY() < 0) || //reduce velocity to 0 if the destination coordinate is reached
(movementVector.getY() > 0 && movementVector.getY()/2.0 > currentVelocity.getY()) || //increase velocity
(movementVector.getY() < 0 && movementVector.getY()/2.0 >= currentVelocity.getY())) { //reduce velocity
accelerationY = 1;
}
else { //no acceleration
accelerationY = 0;
}
//update current Velocity and current Position with the selected acceleration
currentVelocity = new PositionVector(currentVelocity.getX() + accelerationX, currentVelocity.getY() + accelerationY);
currentPosition = new PositionVector(currentPosition.getX() + currentVelocity.getX(), currentPosition.getY() + currentVelocity.getY());
//Find Direction for acceleration
PositionVector acceleration = new PositionVector(accelerationX, accelerationY);
Direction[] directions = Direction.values();
for (Direction direction : directions) {
if (direction.vector.equals(acceleration)) {
return direction;
}
}
return null;
} }
} }
@@ -0,0 +1,104 @@
package ch.zhaw.pm2.racetrack;
import ch.zhaw.pm2.racetrack.strategy.UserMoveStrategy;
import org.junit.jupiter.api.*;
import java.io.File;
import static ch.zhaw.pm2.racetrack.Game.NO_WINNER;
class GameTest {
private UserInterface userInterface;
private Game game;
private Track track;
@Nested
@DisplayName("Test correct Setup")
class Setup {
@BeforeEach
void setup() {
userInterface = new UserInterface("Test");
game = new Game(userInterface);
track = game.selectTrack(new File(".\\tracks\\challenge.txt"));
game.selectMoveStrategy(track.getCar(0),new UserMoveStrategy(new UserInterface("Testing"),0, track.getCarId(0)));
game.selectMoveStrategy(track.getCar(1),new UserMoveStrategy(new UserInterface("Testing"),1, track.getCarId(1)));
}
@Test
void getCurrentCarIndex() {
Assertions.assertEquals(0,game.getCurrentCarIndex());
game.switchToNextActiveCar();
Assertions.assertEquals(1,game.getCurrentCarIndex());
}
@Test
void getCarId() {
Assertions.assertEquals('a',game.getCarId(0));
Assertions.assertEquals('b',game.getCarId(1));
}
@Test
void getCarPosition() {
Assertions.assertEquals(new PositionVector(24,22),game.getCarPosition(0));
Assertions.assertEquals(new PositionVector(24,24),game.getCarPosition(1));
}
@Test
void getCarVelocity() {
Assertions.assertEquals(new PositionVector(0,0),game.getCarVelocity(0));
Assertions.assertEquals(new PositionVector(0,0),game.getCarVelocity(1));
}
@Test
void getWinner() {
Assertions.assertEquals(NO_WINNER,game.getWinner());
}
@Test
void onlyOneCarLeft() {
Assertions.assertFalse(game.onlyOneCarLeft());
}
@Test
void carsMoving() {
Assertions.assertTrue(game.carsMoving());
}
}
@Nested
@DisplayName("Basic manipulation")
class manipulation {
@BeforeEach
void setup() {
userInterface = new UserInterface("Test");
game = new Game(userInterface);
track = game.selectTrack(new File(".\\tracks\\challenge.txt"));
game.selectMoveStrategy(track.getCar(0),new UserMoveStrategy(new UserInterface("Testing"),0, track.getCarId(0)));
game.selectMoveStrategy(track.getCar(1),new UserMoveStrategy(new UserInterface("Testing"),1, track.getCarId(1)));
}
@Test
void carTurnCorrect() {
try {
game.doCarTurn(PositionVector.Direction.RIGHT);
Assertions.assertEquals(new PositionVector(1,0),game.getCarVelocity(0));
} catch (PositionVectorNotValid positionVectorNotValid) {
positionVectorNotValid.printStackTrace();
}
}
@Test
void carCrash() {
try {
game.doCarTurn(PositionVector.Direction.UP);
Assertions.assertTrue(game.onlyOneCarLeft());
} catch (PositionVectorNotValid positionVectorNotValid) {
positionVectorNotValid.printStackTrace();
}
}
}
}
@@ -0,0 +1,40 @@
package ch.zhaw.pm2.racetrack;
import ch.zhaw.pm2.racetrack.strategy.MoveListStrategy;
import ch.zhaw.pm2.racetrack.strategy.MoveStrategy;
import org.junit.jupiter.api.*;
import java.io.FileNotFoundException;
public class MoveStrategyTest {
private MoveStrategy moveList;
@Nested
@DisplayName("MoveListStrategy")
class MoveList {
@BeforeEach
void setup() {
try {
moveList = new MoveListStrategy(".\\moves\\challenge-car-a.txt");
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@Test
void checkMove() {
Assertions.assertEquals(PositionVector.Direction.RIGHT,moveList.nextMove());
for (int i = 0; i < 3; i++) {
moveList.nextMove();
}
Assertions.assertEquals(PositionVector.Direction.NONE,moveList.nextMove());
for (int i = 0; i < 40; i++) {
moveList.nextMove();
}
Assertions.assertNull(moveList.nextMove());
}
}
}