From 65d7ea6e7eb55485e0906c766feb9d4327fc0752 Mon Sep 17 00:00:00 2001 From: Andrin Fassbind Date: Fri, 25 Mar 2022 21:48:12 +0100 Subject: [PATCH] code cleanup --- Klassendiagramm.svg | 5 +- moves/challenge-car-b.txt | 3 - src/main/java/ch/zhaw/pm2/racetrack/Game.java | 37 +++++++----- .../java/ch/zhaw/pm2/racetrack/Track.java | 8 +-- .../racetrack/strategy/MoveListStrategy.java | 13 ++++- .../strategy/PathFollowerMoveStrategy.java | 58 ++++++++++--------- .../java/ch/zhaw/pm2/racetrack/CarTest.java | 13 ++--- .../zhaw/pm2/racetrack/MoveStrategyTest.java | 2 +- 8 files changed, 78 insertions(+), 61 deletions(-) diff --git a/Klassendiagramm.svg b/Klassendiagramm.svg index d8cd095..ba81636 100644 --- a/Klassendiagramm.svg +++ b/Klassendiagramm.svg @@ -1,4 +1 @@ - - - -Game
+Game(userInterface:UserInterface)
+Game(userInterface:UserInterface)
+initPhase();boolean
+initPhase();boolean
#selectTrack(selectedTrack:File):Track
#selectTrack(selectedTrack:File):Track
#selectMoveStrategy(car:Car,strategy:MoveStrategy);
#selectMoveStrategy(car:Car,strategy:MoveStrategy);
+gamePhase();
+gamePhase();
+onlyOneCarLeft();boolean
+onlyOneCarLeft();boolean
+carsMoving();boolean
+carsMoving();boolean
Track
-track:List<String>
-track:List<String>
+CRASH_INDICATOR:char{final}
+CRASH_INDICATOR:char{final}
-finishLine:List<PositionVector>{final}
-finishLine:List<PositionVector>{final}
-finishTyp:ConfigSpecification.SpaceType
-finishTyp:ConfigSpecification.SpaceType
-cars:List<Car>
-cars:List<Car>
+Track(trackFile:File)
+Track(trackFile:File)
-readFile(trackFile:File)
-readFile(trackFile:File)
-addCars()
-addCars()
-findFinish()
-findFinish()
-findChar(symbol:char);PositionVector
-findChar(symbol:char);PositionVector
-drawCharOnTrackIndicator(positionVector:PositionVector,symbol:char)
-drawCharOnTrackIndicator(positionVector:PositionVector,symbol:char)
+getFinishLine();List<PositionVector>
+getFinishLine();List<PositionVector>
+getTrack()
+getTrack()
+moveCar(carIndex:int)
+moveCar(carIndex:int)
-makeCarMoveInTrack(carIndex:int)
-makeCarMoveInTrack(carIndex:int)
+willCrashAtPosition(carIndex:int,positionVector:PositionVector);boolean
+willCrashAtPosition(carIndex:int,positionVector:PositionVector);boolean
+carDoesCrash(carIndex:int,crashPositionVector:PositionVector)
+carDoesCrash(carIndex:int,crashPositionVector:PositionVector)
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<PositionVector>
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<Positi...
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<PositionVector>
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<Positi...
PositionVectorConfig<<enumeration>>Strategy Type<<enumeration>>DirectionCar
-id:char{final,readOnly}
-id:char{final,readOnly}
-position:PositionVector
-position:PositionVector
-velocity:PositionVector{readOnly}
-velocity:PositionVector{readOnly}
-crashed:boolean{readOnly}
-crashed:boolean{readOnly}
-winPoints:int
-winPoints:int
-moveStrategy:MoveStrategy
-moveStrategy:MoveStrategy
+Car(id:char,position:PositionVector)
+Car(id:char,position:PositionVector)
+nextPosition();PositionVector
+nextPosition();PositionVector
+accelerate(aceleration:Direction)
+accelerate(aceleration:Direction)
+move()
+move()
+crash()
+crash()
+getID()
+getID()
+increaseWinPoints()
+increaseWinPoints()
+deductWinPoints()
+deductWinPoints()
+getWinPoints():int
+getWinPoints():int
+getVelocity():PositionVector
+getVelocity():PositionVector
+setPosition(position:PositionVector{final})
+setPosition(position:PositionVector{final})
+nextPosition():PositionVector
+nextPosition():PositionVector
+accelerate(acceleration:PositionVector.Direction)
+accelerate(acceleration:PositionVector.Direc...
+move()
+move()
+crash()
+crash()
+isCrashed();boolean
+isCrashed();boolean
+setMoveStrategy(moveStrategy:MoveStrategy)
+setMoveStrategy(moveStrategy:MoveStrategy)
+gettMoveStrategy();MoveStrategy
+gettMoveStrategy();MoveStrategy
<<enumeration>>Space Type
Strategy
Strategy
MoveListStrategy
-moveList:List<Direction>
-moveList:List<Direction>
-pointer:int
-pointer:int
+MoveListStrategy(path:String)
+MoveListStrategy(path:String)
+nextMove();Direction
+nextMove();Direction
-readFile(trackFile:File)
-readFile(trackFile:File)
DoNotMoveStrategy
+nextMove();Direction
+nextMove();Direction
PathFollowerMoveStrategy
-currentPosition:PositionVector
-currentPosition:PositionVector
-currentVelocity:PositionVector
-currentVelocity:PositionVector
-pointList:ArrayList<PositionVector>
-pointList:ArrayList<PositionVector>
-pointer:int
-pointer:int
+PathFollowerMoveStrategy(path:String,startPosition:PositionVector)
+PathFollowerMoveStrategy(path:String,startPosition:PositionVector)
+readFile(trackFile:File)
+readFile(trackFile:File)
+nextMove();Direction
+nextMove();Direction
UserMoveStrategy
-userInterface:UserInterface
-userInterface:UserInterface
-carIndex :int
-carIndex :int
-carID:char
-carID:char
+UserMoveStrategy(userInterface:UserInterface,carIndex:int,carID:char)
+UserMoveStrategy(userInterface:UserInterface,carIndex:int,carID:...
+nextMove();Direction
+nextMove();Direction
InvalidFileFormatExceptionInvalidTrackFormatExceptionMainUserInterface
-textIO:TextIO{final}
-textIO:TextIO{final}
-textTerminal:TextTerminal{final}
-textTerminal:TextTerminal{final}
+UserInterface(welcomeText:String)
+UserInterface(welcomeText:String)
+printInformation(text:String)
+printInformation(text:String)
+selectOption(text:String,options:List<String>):int
+selectOption(text:String,options:List<String>):int
+selectDirection(playingCarIndex:int,playingCarID:char):PositionVector.Direction
+selectDirection(playingCarIndex:int,playingCarID:char):PositionVector.Dire...
-getDirection(number:int):PositionVector.Direction
-getDirection(number:int):PositionVector.Direction
+printTrack(track:Track)
+printTrack(track:Track)
+quit(text:String)
+quit(text:String)
PathFinderMoveStrategy
-track:Track
-track:Track
-carIndex:int
-carIndex:int
-moveList:List<PositionVector.Direction>
-moveList:List<PositionVector.Direction>
-allDirections:List<PositionVector.Direction>
-allDirections:List<PositionVector.Direction>
-calculatedStates:List<State>
-calculatedStates:List<State>
+PathFinderMoveStrategy(track:Track,carIndex)
+PathFinderMoveStrategy(track:Track,carIndex)
-createMoveList()
-createMoveList()
-alreadyCalculated(state:State);boolean
-alreadyCalculated(state:State);boolean
+nextMove();Direction
+nextMove();Direction
State
#position:PositionVector
#position:PositionVector
#velocity:PositionVector
#velocity:PositionVector
+State(position:PositionVector,velocity:PositionVector)
+State(position:PositionVector,velocity:PositionVe...
equals(compareState:State);boolean
equals(compareState:State);boolean
PossibleMove
#directions:List<PositionVector.Direction>
#directions:List<PositionVector.Direction>
#startPosition:PositionVector
#startPosition:PositionVector
#endPosition:PositionVector
#endPosition:PositionVector
#endVelocity:PositionVector
#endVelocity:PositionVector
+PossibleMove(previousMove:PossibleMove, nextDirection:PositionVector.Direction)
+PossibleMove(previousMove:PossibleMove, nextDirection:PositionVector.Direct...
+finished();boolean
+finished();boolean
+crashed();boolean
+crashed();boolean
Text is not SVG - cannot display
\ No newline at end of file +Game
+Game(userInterface:UserInterface)
+Game(userInterface:UserInterface)
+initPhase();boolean
+initPhase();boolean
#selectTrack(selectedTrack:File):Track
#selectTrack(selectedTrack:File):Track
#selectMoveStrategy(car:Car,strategy:MoveStrategy);
#selectMoveStrategy(car:Car,strategy:MoveStrategy);
+gamePhase();
+gamePhase();
+onlyOneCarLeft();boolean
+onlyOneCarLeft();boolean
+carsMoving();boolean
+carsMoving();boolean
Track
-track:List<String>
-track:List<String>
+CRASH_INDICATOR:char{final}
+CRASH_INDICATOR:char{final}
-finishLine:List<PositionVector>{final}
-finishLine:List<PositionVector>{final}
-finishTyp:ConfigSpecification.SpaceType
-finishTyp:ConfigSpecification.SpaceType
-cars:List<Car>
-cars:List<Car>
+Track(trackFile:File)
+Track(trackFile:File)
-readFile(trackFile:File)
-readFile(trackFile:File)
-addCars()
-addCars()
-findFinish()
-findFinish()
-findChar(symbol:char);PositionVector
-findChar(symbol:char);PositionVector
-drawCharOnTrackIndicator(positionVector:PositionVector,symbol:char)
-drawCharOnTrackIndicator(positionVector:PositionVector,symbol:char)
+getFinishLine();List<PositionVector>
+getFinishLine();List<PositionVector>
+getTrack()
+getTrack()
+moveCar(carIndex:int)
+moveCar(carIndex:int)
-makeCarMoveInTrack(carIndex:int)
-makeCarMoveInTrack(carIndex:int)
+willCrashAtPosition(carIndex:int,positionVector:PositionVector);boolean
+willCrashAtPosition(carIndex:int,positionVector:PositionVector);boolean
+carDoesCrash(carIndex:int,crashPositionVector:PositionVector)
+carDoesCrash(carIndex:int,crashPositionVector:PositionVector)
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<PositionVector>
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<Positi...
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<PositionVector>
+calculatePointsOnPath(startPosition:PositionVector,endPosition:PositionVector):ArrayList<Positi...
PositionVectorConfig<<enumeration>>Space Type<<enumeration>>DirectionCar
-id:char{final,readOnly}
-id:char{final,readOnly}
-position:PositionVector
-position:PositionVector
-velocity:PositionVector{readOnly}
-velocity:PositionVector{readOnly}
-crashed:boolean{readOnly}
-crashed:boolean{readOnly}
-winPoints:int
-winPoints:int
-moveStrategy:MoveStrategy
-moveStrategy:MoveStrategy
+Car(id:char,position:PositionVector)
+Car(id:char,position:PositionVector)
+nextPosition();PositionVector
+nextPosition();PositionVector
+accelerate(aceleration:Direction)
+accelerate(aceleration:Direction)
+move()
+move()
+crash()
+crash()
+getID()
+getID()
+increaseWinPoints()
+increaseWinPoints()
+deductWinPoints()
+deductWinPoints()
+getWinPoints():int
+getWinPoints():int
+getVelocity():PositionVector
+getVelocity():PositionVector
+setPosition(position:PositionVector{final})
+setPosition(position:PositionVector{final})
+nextPosition():PositionVector
+nextPosition():PositionVector
+accelerate(acceleration:PositionVector.Direction)
+accelerate(acceleration:PositionVector.Direc...
+move()
+move()
+crash()
+crash()
+isCrashed();boolean
+isCrashed();boolean
+setMoveStrategy(moveStrategy:MoveStrategy)
+setMoveStrategy(moveStrategy:MoveStrategy)
+gettMoveStrategy();MoveStrategy
+gettMoveStrategy();MoveStrategy
<<enumeration>>Strategy Type
Strategy
Strategy
MoveListStrategy
-moveList:List<Direction>
-moveList:List<Direction>
-pointer:int
-pointer:int
+MoveListStrategy(path:String)
+MoveListStrategy(path:String)
+nextMove();Direction
+nextMove();Direction
-readFile(trackFile:File)
-readFile(trackFile:File)
DoNotMoveStrategy
+nextMove();Direction
+nextMove();Direction
PathFollowerMoveStrategy
-currentPosition:PositionVector
-currentPosition:PositionVector
-currentVelocity:PositionVector
-currentVelocity:PositionVector
-pointList:ArrayList<PositionVector>
-pointList:ArrayList<PositionVector>
-pointer:int
-pointer:int
+PathFollowerMoveStrategy(path:String,startPosition:PositionVector)
+PathFollowerMoveStrategy(path:String,startPosition:PositionVector)
+readFile(trackFile:File)
+readFile(trackFile:File)
+nextMove();Direction
+nextMove();Direction
UserMoveStrategy
-userInterface:UserInterface
-userInterface:UserInterface
-carIndex :int
-carIndex :int
-carID:char
-carID:char
+UserMoveStrategy(userInterface:UserInterface,carIndex:int,carID:char)
+UserMoveStrategy(userInterface:UserInterface,carIndex:int,carID:...
+nextMove();Direction
+nextMove();Direction
InvalidFileFormatExceptionInvalidTrackFormatExceptionMainUserInterface
-textIO:TextIO{final}
-textIO:TextIO{final}
-textTerminal:TextTerminal{final}
-textTerminal:TextTerminal{final}
+UserInterface(welcomeText:String)
+UserInterface(welcomeText:String)
+printInformation(text:String)
+printInformation(text:String)
+selectOption(text:String,options:List<String>):int
+selectOption(text:String,options:List<String>):int
+selectDirection(playingCarIndex:int,playingCarID:char):PositionVector.Direction
+selectDirection(playingCarIndex:int,playingCarID:char):PositionVector.Dire...
-getDirection(number:int):PositionVector.Direction
-getDirection(number:int):PositionVector.Direction
+printTrack(track:Track)
+printTrack(track:Track)
+quit(text:String)
+quit(text:String)
PathFinderMoveStrategy
-track:Track
-track:Track
-carIndex:int
-carIndex:int
-moveList:List<PositionVector.Direction>
-moveList:List<PositionVector.Direction>
-allDirections:List<PositionVector.Direction>
-allDirections:List<PositionVector.Direction>
-calculatedStates:List<State>
-calculatedStates:List<State>
+PathFinderMoveStrategy(track:Track,carIndex)
+PathFinderMoveStrategy(track:Track,carIndex)
-createMoveList()
-createMoveList()
-alreadyCalculated(state:State);boolean
-alreadyCalculated(state:State);boolean
+nextMove();Direction
+nextMove();Direction
State
#position:PositionVector
#position:PositionVector
#velocity:PositionVector
#velocity:PositionVector
+State(position:PositionVector,velocity:PositionVector)
+State(position:PositionVector,velocity:PositionVe...
equals(compareState:State);boolean
equals(compareState:State);boolean
PossibleMove
#directions:List<PositionVector.Direction>
#directions:List<PositionVector.Direction>
#startPosition:PositionVector
#startPosition:PositionVector
#endPosition:PositionVector
#endPosition:PositionVector
#endVelocity:PositionVector
#endVelocity:PositionVector
+PossibleMove(previousMove:PossibleMove, nextDirection:PositionVector.Direction)
+PossibleMove(previousMove:PossibleMove, nextDirection:PositionVector.Direct...
+finished();boolean
+finished();boolean
+crashed();boolean
+crashed();boolean
Viewer does not support full SVG 1.1
\ No newline at end of file diff --git a/moves/challenge-car-b.txt b/moves/challenge-car-b.txt index e5bdf18..3933571 100644 --- a/moves/challenge-car-b.txt +++ b/moves/challenge-car-b.txt @@ -35,6 +35,3 @@ UP_RIGHT UP_RIGHT RIGHT RIGHT - - - diff --git a/src/main/java/ch/zhaw/pm2/racetrack/Game.java b/src/main/java/ch/zhaw/pm2/racetrack/Game.java index 4203a3e..9c18c24 100644 --- a/src/main/java/ch/zhaw/pm2/racetrack/Game.java +++ b/src/main/java/ch/zhaw/pm2/racetrack/Game.java @@ -30,6 +30,7 @@ public class Game implements GameSpecification { /** * 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. */ public boolean initPhase() { @@ -70,35 +71,43 @@ public class Game implements GameSpecification { moveStrategy = new UserMoveStrategy(userInterface, i, track.getCarId(i)); break; case 2: - for(File file : config.getMoveDirectory().listFiles()){ - if(file.toString().equals(config.getMoveDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "-car-" + track.getCar(i).getID() + ".txt")){ + for (File file : config.getMoveDirectory().listFiles()) { + if (file.toString().equals(config.getMoveDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "-car-" + track.getCar(i).getID() + ".txt")) { selectedFile = file; } } - if(selectedFile != null){ + if (selectedFile != null) { try { moveStrategy = new MoveListStrategy(selectedFile); } catch (FileNotFoundException e) { 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!"); } break; case 3: - for(File file : config.getFollowerDirectory().listFiles()){ - if(file.toString().equals(config.getFollowerDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "_points.txt")){ + for (File file : config.getFollowerDirectory().listFiles()) { + if (file.toString().equals(config.getFollowerDirectory().toString() + "\\" + selectedTrack.getName().split("\\.")[0] + "_points.txt")) { selectedFile = file; } } - if(selectedFile != null){ + if (selectedFile != null) { try { moveStrategy = new PathFollowerMoveStrategy(selectedFile, track.getCarPos(currentCarIndex)); } catch (FileNotFoundException e) { + e.printStackTrace(); 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!"); } @@ -119,9 +128,10 @@ public class Game implements GameSpecification { /** * The functionality was taken out of init to automate testing + * * @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); return track; } @@ -240,9 +250,9 @@ public class Game implements GameSpecification { } } int newWinPoints = track.calculateNewWinPoints(track.getCarPos(currentCarIndex), track.getCar(currentCarIndex).nextPosition()); - if(newWinPoints == 1){ + if (newWinPoints == 1) { track.getCar(currentCarIndex).increaseWinPoints(); - }else if(newWinPoints == -1){ + } else if (newWinPoints == -1) { track.getCar(currentCarIndex).deductWinPoints(); } if (crashPosition != null) { @@ -265,7 +275,7 @@ public class Game implements GameSpecification { Direction direction; direction = track.getCar(currentCarIndex).getMoveStrategy().nextMove(); if (direction == null) { - if(track.getCar(currentCarIndex).getMoveStrategy() instanceof UserMoveStrategy){ + if (track.getCar(currentCarIndex).getMoveStrategy() instanceof UserMoveStrategy) { quit = true; direction = Direction.NONE; } else { @@ -322,7 +332,8 @@ public class Game implements GameSpecification { * 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 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 */ private void calculateWinner(PositionVector start, PositionVector finish, int carIndex) { diff --git a/src/main/java/ch/zhaw/pm2/racetrack/Track.java b/src/main/java/ch/zhaw/pm2/racetrack/Track.java index bac8f92..38c2a37 100644 --- a/src/main/java/ch/zhaw/pm2/racetrack/Track.java +++ b/src/main/java/ch/zhaw/pm2/racetrack/Track.java @@ -126,7 +126,7 @@ public class Track implements TrackSpecification { } /** - * Determines the finish line and saves it in a list, throws an Exception if none is found. + * Determines the finish line and saves it in a list, throws an Exception if none is found. * * @throws InvalidTrackFormatException thrown if no finish line is found */ @@ -256,7 +256,7 @@ public class Track implements TrackSpecification { /** * This Method will mark the Car as crashed inside the track and the car Object. * - * @param carIndex of car that will be marked as crashed + * @param carIndex of car that will be marked as crashed * @param crashPositionVector of the location of the crash */ public void carDoesCrash(int carIndex, PositionVector crashPositionVector) { @@ -369,7 +369,7 @@ public class Track implements TrackSpecification { * Determines all points that lie between the two position vectors including the endpoint VectorPosition using the Bresenham algorithm. * * @param startPosition PositionVector of the finish coordinate - * @param endPosition PositionVector of the start coordinate + * @param endPosition PositionVector of the start coordinate * @return ArrayList containing PositionVectors of all position that are between the start and finish including the finish position. */ public ArrayList calculatePointsOnPath(PositionVector startPosition, PositionVector endPosition) { @@ -436,7 +436,7 @@ public class Track implements TrackSpecification { * If the car is passing the finish line in the wrong direction, the car will lose a winpoint. * If the car is passing the finish line in the correct direction, the car will gain a winpoint. * - * @param start the start position of the car + * @param start the start position of the car * @param finish the expected finish position of the car after the move * @return Number of new winpoints for the current player. */ diff --git a/src/main/java/ch/zhaw/pm2/racetrack/strategy/MoveListStrategy.java b/src/main/java/ch/zhaw/pm2/racetrack/strategy/MoveListStrategy.java index 2953ef7..f65a7b8 100644 --- a/src/main/java/ch/zhaw/pm2/racetrack/strategy/MoveListStrategy.java +++ b/src/main/java/ch/zhaw/pm2/racetrack/strategy/MoveListStrategy.java @@ -1,5 +1,6 @@ package ch.zhaw.pm2.racetrack.strategy; +import ch.zhaw.pm2.racetrack.InvalidFileFormatException; import ch.zhaw.pm2.racetrack.PositionVector.Direction; import java.io.File; @@ -13,14 +14,13 @@ import java.util.Scanner; /** * This Class represent the MoveListStrategy. The Directions returned by the * nextMove() are written down in a List. - * */ public class MoveListStrategy implements MoveStrategy { private final List moveList; private int pointer; - public MoveListStrategy(File moveListFile) throws FileNotFoundException{ + public MoveListStrategy(File moveListFile) throws FileNotFoundException, InvalidFileFormatException { moveList = new ArrayList<>(); pointer = -1; 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. * If so the direction will be added to the moveList. + * * @param trackFile the file to read in the directions * @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); Direction[] directions = Direction.values(); while (scanner.hasNextLine()) { + boolean validLine = false; String line = scanner.nextLine(); for (Direction direction : directions) { if (direction.toString().equals(line)) { moveList.add(direction); + validLine = true; 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. + * * @return the next direction from the list. Returns null if the list is empty. */ @Override diff --git a/src/main/java/ch/zhaw/pm2/racetrack/strategy/PathFollowerMoveStrategy.java b/src/main/java/ch/zhaw/pm2/racetrack/strategy/PathFollowerMoveStrategy.java index 0cdfae4..7017b32 100644 --- a/src/main/java/ch/zhaw/pm2/racetrack/strategy/PathFollowerMoveStrategy.java +++ b/src/main/java/ch/zhaw/pm2/racetrack/strategy/PathFollowerMoveStrategy.java @@ -1,5 +1,6 @@ package ch.zhaw.pm2.racetrack.strategy; +import ch.zhaw.pm2.racetrack.InvalidFileFormatException; import ch.zhaw.pm2.racetrack.PositionVector; 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. - * @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 * @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<>(); pointer = 0; readFile(trackFile); @@ -48,20 +50,26 @@ public class PathFollowerMoveStrategy implements MoveStrategy { /** * 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 { + public void readFile(File trackFile) throws FileNotFoundException, InvalidFileFormatException { Scanner scanner = new Scanner(new FileInputStream(trackFile), StandardCharsets.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]))); + try { + 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. + * * @return The direction for the next move. null if there are no points left in the list. */ @Override @@ -73,7 +81,7 @@ public class PathFollowerMoveStrategy implements MoveStrategy { // increase pointer variable if the next point is reached. if (pointList.get(pointer).equals(currentPosition)) { - pointer ++; + pointer++; } // calculate Vector from current Position to next Point @@ -81,31 +89,29 @@ public class PathFollowerMoveStrategy implements MoveStrategy { // 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 + 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 + 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; } @@ -121,7 +127,7 @@ public class PathFollowerMoveStrategy implements MoveStrategy { return direction; } } - return null; + return null; } } diff --git a/src/test/java/ch/zhaw/pm2/racetrack/CarTest.java b/src/test/java/ch/zhaw/pm2/racetrack/CarTest.java index 598eb17..2cd6d41 100644 --- a/src/test/java/ch/zhaw/pm2/racetrack/CarTest.java +++ b/src/test/java/ch/zhaw/pm2/racetrack/CarTest.java @@ -108,7 +108,6 @@ class CarTest { checkNextPosition(DEFAULT_X, DEFAULT_Y); - for (PositionVector.Direction direction1 : directions) { for (PositionVector.Direction direction2 : directions) { @@ -180,7 +179,7 @@ class CarTest { try { moveStrategy = new MoveListStrategy(new File(".\\moves\\challenge-car-a.txt")); - } catch (FileNotFoundException e) { + } catch (FileNotFoundException | InvalidFileFormatException e) { Assertions.fail(); } car.setMoveStrategy(moveStrategy); @@ -188,13 +187,13 @@ class CarTest { try { moveStrategy = new PathFollowerMoveStrategy(new File(".\\follower\\challenge_points.txt"), new PositionVector(0, 0)); - } catch (FileNotFoundException e) { + } catch (FileNotFoundException | InvalidFileFormatException e) { e.printStackTrace(); } car.setMoveStrategy(moveStrategy); assertEquals(moveStrategy, car.getMoveStrategy()); - moveStrategy = new UserMoveStrategy(new UserInterface("Hello"),0,'a'); + moveStrategy = new UserMoveStrategy(new UserInterface("Hello"), 0, 'a'); car.setMoveStrategy(moveStrategy); assertEquals(moveStrategy, car.getMoveStrategy()); } @@ -204,7 +203,7 @@ class CarTest { */ @Test void getWinPoints() { - assertEquals(0,car.getWinPoints()); + assertEquals(0, car.getWinPoints()); } /** @@ -213,7 +212,7 @@ class CarTest { @Test void increaseWinPoints() { car.increaseWinPoints(); - assertEquals(1,car.getWinPoints()); + assertEquals(1, car.getWinPoints()); } /** @@ -222,7 +221,7 @@ class CarTest { @Test void deductWinPoints() { car.deductWinPoints(); - assertEquals(-1,car.getWinPoints()); + assertEquals(-1, car.getWinPoints()); } } diff --git a/src/test/java/ch/zhaw/pm2/racetrack/MoveStrategyTest.java b/src/test/java/ch/zhaw/pm2/racetrack/MoveStrategyTest.java index d5fce9a..4229343 100644 --- a/src/test/java/ch/zhaw/pm2/racetrack/MoveStrategyTest.java +++ b/src/test/java/ch/zhaw/pm2/racetrack/MoveStrategyTest.java @@ -20,7 +20,7 @@ public class MoveStrategyTest { void setup() { try { moveList = new MoveListStrategy(new File(".\\moves\\challenge-car-a.txt")); - }catch (FileNotFoundException e) { + }catch (FileNotFoundException | InvalidFileFormatException e) { e.printStackTrace(); } }