code cleanup

This commit is contained in:
Andrin Fassbind 2022-03-25 21:48:12 +01:00
parent e2c6b5cb49
commit 65d7ea6e7e
8 changed files with 78 additions and 61 deletions

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 120 KiB

After

Width:  |  Height:  |  Size: 113 KiB

View File

@ -35,6 +35,3 @@ UP_RIGHT
UP_RIGHT UP_RIGHT
RIGHT RIGHT
RIGHT RIGHT

View File

@ -30,6 +30,7 @@ public class Game implements GameSpecification {
/** /**
* This method will initialize the game. Therefore it interacts with the user via UserInterface * This method will initialize the game. Therefore it interacts with the user via UserInterface
*
* @return true if the initialization is completed. Returns false if there is an error. * @return true if the initialization is completed. Returns false if there is an error.
*/ */
public boolean initPhase() { public boolean initPhase() {
@ -70,35 +71,43 @@ public class Game implements GameSpecification {
moveStrategy = new UserMoveStrategy(userInterface, i, track.getCarId(i)); moveStrategy = new UserMoveStrategy(userInterface, i, track.getCarId(i));
break; break;
case 2: case 2:
for(File file : config.getMoveDirectory().listFiles()){ for (File file : config.getMoveDirectory().listFiles()) {
if(file.toString().equals(config.getMoveDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "-car-" + track.getCar(i).getID() + ".txt")){ if (file.toString().equals(config.getMoveDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "-car-" + track.getCar(i).getID() + ".txt")) {
selectedFile = file; selectedFile = file;
} }
} }
if(selectedFile != null){ if (selectedFile != null) {
try { try {
moveStrategy = new MoveListStrategy(selectedFile); moveStrategy = new MoveListStrategy(selectedFile);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
userInterface.printInformation("There is no Move-List implemented. Choose another Strategy!"); userInterface.printInformation("There is no Move-List implemented. Choose another Strategy!");
e.printStackTrace();
} catch (InvalidFileFormatException e) {
userInterface.printInformation("Invalid Data in Move-List. Choose another Strategy and clean the File");
e.printStackTrace();
} }
} else{ } else {
userInterface.printInformation("There is no Move-List implemented. Choose another Strategy!"); userInterface.printInformation("There is no Move-List implemented. Choose another Strategy!");
} }
break; break;
case 3: case 3:
for(File file : config.getFollowerDirectory().listFiles()){ for (File file : config.getFollowerDirectory().listFiles()) {
if(file.toString().equals(config.getFollowerDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "_points.txt")){ if (file.toString().equals(config.getFollowerDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "_points.txt")) {
selectedFile = file; selectedFile = file;
} }
} }
if(selectedFile != null){ if (selectedFile != null) {
try { try {
moveStrategy = new PathFollowerMoveStrategy(selectedFile, track.getCarPos(currentCarIndex)); moveStrategy = new PathFollowerMoveStrategy(selectedFile, track.getCarPos(currentCarIndex));
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace();
userInterface.printInformation("There is no Point-List implemented. Choose another Strategy!"); userInterface.printInformation("There is no Point-List implemented. Choose another Strategy!");
} catch (InvalidFileFormatException e) {
e.printStackTrace();
userInterface.printInformation("Invalid Point-List format. Change Strategy and clean Point-List");
} }
} else{ } else {
userInterface.printInformation("There is no Point-List implemented. Choose another Strategy!"); userInterface.printInformation("There is no Point-List implemented. Choose another Strategy!");
} }
@ -119,9 +128,10 @@ public class Game implements GameSpecification {
/** /**
* The functionality was taken out of init to automate testing * The functionality was taken out of init to automate testing
*
* @param selectedTrack the Track which was selected by user * @param selectedTrack the Track which was selected by user
*/ */
Track selectTrack(File selectedTrack) throws InvalidTrackFormatException,FileNotFoundException { Track selectTrack(File selectedTrack) throws InvalidTrackFormatException, FileNotFoundException {
track = new Track(selectedTrack); track = new Track(selectedTrack);
return track; return track;
} }
@ -240,9 +250,9 @@ public class Game implements GameSpecification {
} }
} }
int newWinPoints = track.calculateNewWinPoints(track.getCarPos(currentCarIndex), track.getCar(currentCarIndex).nextPosition()); int newWinPoints = track.calculateNewWinPoints(track.getCarPos(currentCarIndex), track.getCar(currentCarIndex).nextPosition());
if(newWinPoints == 1){ if (newWinPoints == 1) {
track.getCar(currentCarIndex).increaseWinPoints(); track.getCar(currentCarIndex).increaseWinPoints();
}else if(newWinPoints == -1){ } else if (newWinPoints == -1) {
track.getCar(currentCarIndex).deductWinPoints(); track.getCar(currentCarIndex).deductWinPoints();
} }
if (crashPosition != null) { if (crashPosition != null) {
@ -265,7 +275,7 @@ public class Game implements GameSpecification {
Direction direction; Direction direction;
direction = track.getCar(currentCarIndex).getMoveStrategy().nextMove(); direction = track.getCar(currentCarIndex).getMoveStrategy().nextMove();
if (direction == null) { if (direction == null) {
if(track.getCar(currentCarIndex).getMoveStrategy() instanceof UserMoveStrategy){ if (track.getCar(currentCarIndex).getMoveStrategy() instanceof UserMoveStrategy) {
quit = true; quit = true;
direction = Direction.NONE; direction = Direction.NONE;
} else { } else {
@ -322,6 +332,7 @@ public class Game implements GameSpecification {
* This method will check if a car is passing the finishline. * This method will check if a car is passing the finishline.
* If the car is passing the finishline in the wrong direction, the car will lose a winpoint. * If the car is passing the finishline in the wrong direction, the car will lose a winpoint.
* If the car is passing the finishline in the correct direction, the car will gain a winpoint. * If the car is passing the finishline in the correct direction, the car will gain a winpoint.
*
* @param start the startposition of the car * @param start the startposition of the car
* @param finish the expected finishpositon of the car after the move * @param finish the expected finishpositon of the car after the move
*/ */

View File

@ -1,5 +1,6 @@
package ch.zhaw.pm2.racetrack.strategy; package ch.zhaw.pm2.racetrack.strategy;
import ch.zhaw.pm2.racetrack.InvalidFileFormatException;
import ch.zhaw.pm2.racetrack.PositionVector.Direction; import ch.zhaw.pm2.racetrack.PositionVector.Direction;
import java.io.File; import java.io.File;
@ -13,14 +14,13 @@ import java.util.Scanner;
/** /**
* This Class represent the MoveListStrategy. The Directions returned by the * This Class represent the MoveListStrategy. The Directions returned by the
* nextMove() are written down in a List. * nextMove() are written down in a List.
*
*/ */
public class MoveListStrategy implements MoveStrategy { public class MoveListStrategy implements MoveStrategy {
private final List<Direction> moveList; private final List<Direction> moveList;
private int pointer; private int pointer;
public MoveListStrategy(File moveListFile) throws FileNotFoundException{ public MoveListStrategy(File moveListFile) throws FileNotFoundException, InvalidFileFormatException {
moveList = new ArrayList<>(); moveList = new ArrayList<>();
pointer = -1; pointer = -1;
readFile(moveListFile); readFile(moveListFile);
@ -29,25 +29,32 @@ public class MoveListStrategy implements MoveStrategy {
/** /**
* This Method will read in a File and checks line by line if the file contains a valid direction. * This Method will read in a File and checks line by line if the file contains a valid direction.
* If so the direction will be added to the moveList. * If so the direction will be added to the moveList.
*
* @param trackFile the file to read in the directions * @param trackFile the file to read in the directions
* @throws FileNotFoundException if the file does not exist. * @throws FileNotFoundException if the file does not exist.
*/ */
private void readFile(File trackFile) throws FileNotFoundException { private void readFile(File trackFile) throws FileNotFoundException, InvalidFileFormatException {
Scanner scanner = new Scanner(new FileInputStream(trackFile), StandardCharsets.UTF_8); Scanner scanner = new Scanner(new FileInputStream(trackFile), StandardCharsets.UTF_8);
Direction[] directions = Direction.values(); Direction[] directions = Direction.values();
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
boolean validLine = false;
String line = scanner.nextLine(); String line = scanner.nextLine();
for (Direction direction : directions) { for (Direction direction : directions) {
if (direction.toString().equals(line)) { if (direction.toString().equals(line)) {
moveList.add(direction); moveList.add(direction);
validLine = true;
break; break;
} }
} }
if (!(validLine || line == "")) {
throw new InvalidFileFormatException("The File contains invalid data! Please ");
}
} }
} }
/** /**
* This method will be used to return the next Direction for the car. * This method will be used to return the next Direction for the car.
*
* @return the next direction from the list. Returns null if the list is empty. * @return the next direction from the list. Returns null if the list is empty.
*/ */
@Override @Override

View File

@ -1,5 +1,6 @@
package ch.zhaw.pm2.racetrack.strategy; package ch.zhaw.pm2.racetrack.strategy;
import ch.zhaw.pm2.racetrack.InvalidFileFormatException;
import ch.zhaw.pm2.racetrack.PositionVector; import ch.zhaw.pm2.racetrack.PositionVector;
import ch.zhaw.pm2.racetrack.PositionVector.Direction; import ch.zhaw.pm2.racetrack.PositionVector.Direction;
@ -34,11 +35,12 @@ public class PathFollowerMoveStrategy implements MoveStrategy {
/** /**
* Constructor to create a new PathFollowerMoveStrategy for a car. * Constructor to create a new PathFollowerMoveStrategy for a car.
*
* @param trackFile The location where the file is saved * @param trackFile The location where the file is saved
* @param startPosition The start position of the car * @param startPosition The start position of the car
* @throws FileNotFoundException If the file with the given path does not exist. * @throws FileNotFoundException If the file with the given path does not exist.
*/ */
public PathFollowerMoveStrategy(File trackFile, PositionVector startPosition) throws FileNotFoundException { public PathFollowerMoveStrategy(File trackFile, PositionVector startPosition) throws FileNotFoundException, InvalidFileFormatException {
pointList = new ArrayList<>(); pointList = new ArrayList<>();
pointer = 0; pointer = 0;
readFile(trackFile); readFile(trackFile);
@ -48,20 +50,26 @@ public class PathFollowerMoveStrategy implements MoveStrategy {
/** /**
* Method to read the given File and add the points to the pointList * Method to read the given File and add the points to the pointList
*
* @param trackFile the File Object which should be read * @param trackFile the File Object which should be read
* @throws FileNotFoundException If the file with the given path does not exist. * @throws FileNotFoundException If the file with the given path does not exist.
*/ */
public void readFile(File trackFile) throws FileNotFoundException { public void readFile(File trackFile) throws FileNotFoundException, InvalidFileFormatException {
Scanner scanner = new Scanner(new FileInputStream(trackFile), StandardCharsets.UTF_8); Scanner scanner = new Scanner(new FileInputStream(trackFile), StandardCharsets.UTF_8);
while (scanner.hasNextLine()) { while (scanner.hasNextLine()) {
String line = scanner.nextLine(); String line = scanner.nextLine();
String[] coordinates = line.split("(\\(X:|, Y:|\\))"); String[] coordinates = line.split("(\\(X:|, Y:|\\))");
try {
pointList.add(new PositionVector(Integer.parseInt(coordinates[1]), Integer.parseInt(coordinates[2]))); pointList.add(new PositionVector(Integer.parseInt(coordinates[1]), Integer.parseInt(coordinates[2])));
} catch (NumberFormatException e) {
throw new InvalidFileFormatException("Invalid File Format");
}
} }
} }
/** /**
* Method to select the direction for the next move. * 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. * @return The direction for the next move. null if there are no points left in the list.
*/ */
@Override @Override
@ -73,7 +81,7 @@ public class PathFollowerMoveStrategy implements MoveStrategy {
// increase pointer variable if the next point is reached. // increase pointer variable if the next point is reached.
if (pointList.get(pointer).equals(currentPosition)) { if (pointList.get(pointer).equals(currentPosition)) {
pointer ++; pointer++;
} }
// calculate Vector from current Position to next Point // calculate Vector from current Position to next Point
@ -81,31 +89,29 @@ public class PathFollowerMoveStrategy implements MoveStrategy {
// select acceleration for X // select acceleration for X
int accelerationX; int accelerationX;
if((movementVector.getX() == 0 && currentVelocity.getX() > 0) || //reduce velocity to 0 if the destination coordinate is reached 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()) || //increase velocity
(movementVector.getX() < 0 && movementVector.getX()/2.0 < currentVelocity.getX())){ //reduce velocity (movementVector.getX() < 0 && movementVector.getX() / 2.0 < currentVelocity.getX())) { //reduce velocity
accelerationX = -1; accelerationX = -1;
} else if((movementVector.getX() == 0 && currentVelocity.getX() < 0) || //reduce velocity to 0 if the destination coordinate is reached } 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()) || //increase velocity
(movementVector.getX() < 0 && movementVector.getX()/2.0 >= currentVelocity.getX())) { //reduce velocity (movementVector.getX() < 0 && movementVector.getX() / 2.0 >= currentVelocity.getX())) { //reduce velocity
accelerationX = 1; accelerationX = 1;
} } else { //no acceleration
else { //no acceleration
accelerationX = 0; accelerationX = 0;
} }
// select acceleration for Y // select acceleration for Y
int accelerationY; int accelerationY;
if((movementVector.getY() == 0 && currentVelocity.getY() > 0) || //reduce velocity to 0 if the destination coordinate is reached 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()) || //increase velocity
(movementVector.getY() < 0 && movementVector.getY()/2.0 < currentVelocity.getY())){ //reduce velocity (movementVector.getY() < 0 && movementVector.getY() / 2.0 < currentVelocity.getY())) { //reduce velocity
accelerationY = -1; accelerationY = -1;
} else if((movementVector.getY() == 0 && currentVelocity.getY() < 0) || //reduce velocity to 0 if the destination coordinate is reached } 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()) || //increase velocity
(movementVector.getY() < 0 && movementVector.getY()/2.0 >= currentVelocity.getY())) { //reduce velocity (movementVector.getY() < 0 && movementVector.getY() / 2.0 >= currentVelocity.getY())) { //reduce velocity
accelerationY = 1; accelerationY = 1;
} } else { //no acceleration
else { //no acceleration
accelerationY = 0; accelerationY = 0;
} }

View File

@ -108,7 +108,6 @@ class CarTest {
checkNextPosition(DEFAULT_X, DEFAULT_Y); checkNextPosition(DEFAULT_X, DEFAULT_Y);
for (PositionVector.Direction direction1 : directions) { for (PositionVector.Direction direction1 : directions) {
for (PositionVector.Direction direction2 : directions) { for (PositionVector.Direction direction2 : directions) {
@ -180,7 +179,7 @@ class CarTest {
try { try {
moveStrategy = new MoveListStrategy(new File(".\\moves\\challenge-car-a.txt")); moveStrategy = new MoveListStrategy(new File(".\\moves\\challenge-car-a.txt"));
} catch (FileNotFoundException e) { } catch (FileNotFoundException | InvalidFileFormatException e) {
Assertions.fail(); Assertions.fail();
} }
car.setMoveStrategy(moveStrategy); car.setMoveStrategy(moveStrategy);
@ -188,13 +187,13 @@ class CarTest {
try { try {
moveStrategy = new PathFollowerMoveStrategy(new File(".\\follower\\challenge_points.txt"), new PositionVector(0, 0)); moveStrategy = new PathFollowerMoveStrategy(new File(".\\follower\\challenge_points.txt"), new PositionVector(0, 0));
} catch (FileNotFoundException e) { } catch (FileNotFoundException | InvalidFileFormatException e) {
e.printStackTrace(); e.printStackTrace();
} }
car.setMoveStrategy(moveStrategy); car.setMoveStrategy(moveStrategy);
assertEquals(moveStrategy, car.getMoveStrategy()); assertEquals(moveStrategy, car.getMoveStrategy());
moveStrategy = new UserMoveStrategy(new UserInterface("Hello"),0,'a'); moveStrategy = new UserMoveStrategy(new UserInterface("Hello"), 0, 'a');
car.setMoveStrategy(moveStrategy); car.setMoveStrategy(moveStrategy);
assertEquals(moveStrategy, car.getMoveStrategy()); assertEquals(moveStrategy, car.getMoveStrategy());
} }
@ -204,7 +203,7 @@ class CarTest {
*/ */
@Test @Test
void getWinPoints() { void getWinPoints() {
assertEquals(0,car.getWinPoints()); assertEquals(0, car.getWinPoints());
} }
/** /**
@ -213,7 +212,7 @@ class CarTest {
@Test @Test
void increaseWinPoints() { void increaseWinPoints() {
car.increaseWinPoints(); car.increaseWinPoints();
assertEquals(1,car.getWinPoints()); assertEquals(1, car.getWinPoints());
} }
/** /**
@ -222,7 +221,7 @@ class CarTest {
@Test @Test
void deductWinPoints() { void deductWinPoints() {
car.deductWinPoints(); car.deductWinPoints();
assertEquals(-1,car.getWinPoints()); assertEquals(-1, car.getWinPoints());
} }
} }

View File

@ -20,7 +20,7 @@ public class MoveStrategyTest {
void setup() { void setup() {
try { try {
moveList = new MoveListStrategy(new File(".\\moves\\challenge-car-a.txt")); moveList = new MoveListStrategy(new File(".\\moves\\challenge-car-a.txt"));
}catch (FileNotFoundException e) { }catch (FileNotFoundException | InvalidFileFormatException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }