refactoring several classes

This commit is contained in:
Andrin Fassbind 2022-03-24 16:50:18 +01:00
parent bc0dd52360
commit a143a9c7d7
10 changed files with 123 additions and 103 deletions

File diff suppressed because one or more lines are too long

View File

@ -26,8 +26,11 @@ public class Game implements GameSpecification {
this.userInterface = userInterface;
}
public boolean initPhase() throws InvalidTrackFormatException {
/**
* 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() {
File folder = new File("tracks");
File[] listOfFiles = folder.listFiles();
if (listOfFiles.length > 0) {
@ -35,8 +38,17 @@ public class Game implements GameSpecification {
for (File file : listOfFiles) {
tracks.add(file.getName());
}
File selectedTrack = listOfFiles[userInterface.selectOption("Select Track file", tracks)];
try {
selectTrack(selectedTrack);
} catch (FileNotFoundException e) {
userInterface.printInformation("There is an unexpected Error with the trackfile Path. Add trackfiles only to tracks path. Exit the Game and Fix the Problem");
return false;
} catch (InvalidTrackFormatException e) {
userInterface.printInformation("There is an unexpected Error with the trackfile. Format does not match specifications! Exit the Game and Fix the Problem");
return false;
}
List<String> moveStrategies = new ArrayList<>();
moveStrategies.add("Do not move Strategy");
moveStrategies.add("User Move Strategy");
@ -63,7 +75,6 @@ public class Game implements GameSpecification {
} 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";
@ -86,17 +97,11 @@ public class Game implements GameSpecification {
/**
* The functionality was taken out of init to automate testing
*
* @param selectedTrack
*/
Track selectTrack(File selectedTrack) {
try {
Track selectTrack(File selectedTrack) throws InvalidTrackFormatException,FileNotFoundException {
track = new Track(selectedTrack);
return track;
} catch (FileNotFoundException | PositionVectorNotValid | InvalidTrackFormatException e) {
e.printStackTrace();
}
return null;
}
/**
@ -198,9 +203,8 @@ public class Game implements GameSpecification {
* for this turn
*/
@Override
public void doCarTurn(Direction acceleration) throws PositionVectorNotValid {
public void doCarTurn(Direction acceleration) throws PositionVectorNotValidException {
track.getCar(currentCarIndex).accelerate(acceleration);
PositionVector crashPosition = null;
List<PositionVector> positionList = calculatePath(track.getCarPos(currentCarIndex), track.getCar(currentCarIndex).nextPosition());
for (int i = 0; i < positionList.size(); i++) {
@ -221,7 +225,12 @@ public class Game implements GameSpecification {
}
}
public String gamePhase() throws PositionVectorNotValid {
/**
* This method implements the gameflow in a while loop. If there is a winner. The method will return its carid.
*
* @return the ID of the winning car return null if there is no winner.
*/
public String gamePhase() {
while (carsMoving() && getWinner() == NO_WINNER) {
userInterface.printTrack(track);
Direction direction;
@ -230,7 +239,12 @@ public class Game implements GameSpecification {
track.getCar(currentCarIndex).setMoveStrategy(new DoNotMoveStrategy());
direction = track.getCar(currentCarIndex).getMoveStrategy().nextMove();
}
try {
doCarTurn(direction);
} catch (PositionVectorNotValidException e) {
e.printStackTrace();
userInterface.printInformation("There has been an unexpected Error. It seems that the trackfile is not Valid. Please do only use the given trackfiles. Otherwise please check that your selfmade tracks have borders arround the track.");
}
switchToNextActiveCar();
}
userInterface.printTrack(track);
@ -275,11 +289,17 @@ 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 finish the expected finishpositon of the car after the move
* @param carIndex of the current player.
*/
private void calculateWinner(PositionVector start, PositionVector finish, int carIndex) {
List<PositionVector> path = calculatePath(start, finish);
for (PositionVector point : path) {
if (track.getSpaceType(point) != null) {
switch (track.getSpaceType(point)) {
case FINISH_UP:
if (start.getY() < finish.getY()) {
@ -310,8 +330,6 @@ public class Game implements GameSpecification {
}
break;
}
}
}
}
@ -324,7 +342,7 @@ public class Game implements GameSpecification {
* @return A boolean indicator if the car would crash with a WALL or another car.
*/
@Override
public boolean willCarCrash(int carIndex, PositionVector position) throws PositionVectorNotValid {
public boolean willCarCrash(int carIndex, PositionVector position) throws PositionVectorNotValidException {
return track.willCrashAtPosition(carIndex, position);
}

View File

@ -4,6 +4,7 @@ package ch.zhaw.pm2.racetrack;
* Class for Exception when invalid Fileformat is used.
*/
public class InvalidFileFormatException extends Exception {
public InvalidFileFormatException(){super();}
public InvalidFileFormatException(String errorMessage) {
super(errorMessage);
}

View File

@ -1,12 +1,11 @@
package ch.zhaw.pm2.racetrack;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws InvalidTrackFormatException, PositionVectorNotValid {
public static void main(String[] args) {
UserInterface userInterface = new UserInterface("Hello and Welcome to Racetrack by Team02-\"AngryNerds\"");
while (true) {
Game game = new Game(userInterface);

View File

@ -1,9 +0,0 @@
package ch.zhaw.pm2.racetrack;
public class PositionVectorNotValid extends Throwable {
public PositionVectorNotValid(String message) {
super(message);
}
public PositionVectorNotValid() {}
}

View File

@ -0,0 +1,9 @@
package ch.zhaw.pm2.racetrack;
public class PositionVectorNotValidException extends Throwable {
public PositionVectorNotValidException(String message) {
super(message);
}
public PositionVectorNotValidException() {}
}

View File

@ -69,7 +69,7 @@ public class Track implements TrackSpecification {
* @throws FileNotFoundException if the given track file could not be found
* @throws InvalidTrackFormatException if the track file contains invalid data (no tracklines, ...)
*/
public Track(File trackFile) throws FileNotFoundException, InvalidTrackFormatException, PositionVectorNotValid {
public Track(File trackFile) throws FileNotFoundException, InvalidTrackFormatException {
track = new ArrayList<>();
cars = new ArrayList<>();
finishLine = new ArrayList<>();
@ -161,11 +161,11 @@ public class Track implements TrackSpecification {
track.add(positionVector.getY(), line);
}
private void isPositionVectorOnTrack(PositionVector positionVector) throws PositionVectorNotValid {
private void isPositionVectorOnTrack(PositionVector positionVector) throws PositionVectorNotValidException {
try{
track.get(positionVector.getY()).charAt(positionVector.getX());
}catch (IndexOutOfBoundsException e) {
throw new PositionVectorNotValid();
throw new PositionVectorNotValidException();
}
}
@ -230,7 +230,7 @@ public class Track implements TrackSpecification {
* @param positionVector the position to check if the car could crash
* @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 PositionVectorNotValidException {
isPositionVectorOnTrack(positionVector); //TODO: remove this line? Or Method?
char charAtPosition = track.get(positionVector.getY()).charAt(positionVector.getX());
if (getCarId(carIndex) == charAtPosition) return false;
@ -247,7 +247,7 @@ public class Track implements TrackSpecification {
* @param carIndex representing current Car
* @param crashPositionVector where the Crash did happen
*/
public void carDoesCrash(int carIndex, PositionVector crashPositionVector) throws PositionVectorNotValid{
public void carDoesCrash(int carIndex, PositionVector crashPositionVector) throws PositionVectorNotValidException {
isPositionVectorOnTrack(crashPositionVector); //TODO: remove this line? and Method?
PositionVector currentCarPosition = getCarPos(carIndex);
drawCharOnTrackIndicator(new PositionVector(currentCarPosition.getX(), currentCarPosition.getY()), ConfigSpecification.SpaceType.TRACK.getValue());
@ -266,7 +266,6 @@ public class Track implements TrackSpecification {
*/
@Override
public Config.SpaceType getSpaceType(PositionVector position) {
//isPositionVectorOnTrack(position); Should be used but we are not allowed to change method head. We don't use function anyway
char charAtPosition = track.get(position.getY()).charAt(position.getX());
ConfigSpecification.SpaceType[] spaceTypes = ConfigSpecification.SpaceType.values();
for (ConfigSpecification.SpaceType spaceType : spaceTypes) {
@ -274,8 +273,7 @@ public class Track implements TrackSpecification {
return spaceType;
}
}
return null;
return ConfigSpecification.SpaceType.WALL;
}
/**

View File

@ -1,7 +1,7 @@
package ch.zhaw.pm2.racetrack.given;
import ch.zhaw.pm2.racetrack.PositionVector;
import ch.zhaw.pm2.racetrack.PositionVectorNotValid;
import ch.zhaw.pm2.racetrack.PositionVectorNotValidException;
import java.util.List;
@ -19,11 +19,11 @@ public interface GameSpecification {
int getWinner();
void doCarTurn(PositionVector.Direction acceleration) throws PositionVectorNotValid;
void doCarTurn(PositionVector.Direction acceleration) throws PositionVectorNotValidException;
void switchToNextActiveCar();
List<PositionVector> calculatePath(PositionVector startPosition, PositionVector endPosition);
boolean willCarCrash(int carIndex, PositionVector position) throws PositionVectorNotValid;
boolean willCarCrash(int carIndex, PositionVector position) throws PositionVectorNotValidException;
}

View File

@ -7,6 +7,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import static ch.zhaw.pm2.racetrack.Game.NO_WINNER;
import static ch.zhaw.pm2.racetrack.PositionVector.Direction.*;
@ -35,7 +36,12 @@ class GameTest {
void setup() {
userInterface = new UserInterface("Test");
game = new Game(userInterface);
try {
track = game.selectTrack(new File(TRACK_FILE_PATH));
} catch (InvalidTrackFormatException | FileNotFoundException e) {
e.printStackTrace();
Assertions.fail();
}
game.selectMoveStrategy(track.getCar(CAR_INDEX_ONE), new UserMoveStrategy(new UserInterface("Testing"), CAR_INDEX_ONE, track.getCarId(CAR_INDEX_ONE)));
game.selectMoveStrategy(track.getCar(CAR_INDEX_TWO), new UserMoveStrategy(new UserInterface("Testing"), CAR_INDEX_TWO, track.getCarId(CAR_INDEX_TWO)));
@ -93,7 +99,12 @@ class GameTest {
void setup() {
userInterface = new UserInterface("Test");
game = new Game(userInterface);
try {
track = game.selectTrack(new File(TRACK_FILE_PATH));
} catch (InvalidTrackFormatException | FileNotFoundException e) {
e.printStackTrace();
Assertions.fail();
}
game.selectMoveStrategy(track.getCar(CAR_INDEX_ONE), new UserMoveStrategy(new UserInterface("Testing"), CAR_INDEX_ONE, track.getCarId(CAR_INDEX_ONE)));
game.selectMoveStrategy(track.getCar(CAR_INDEX_TWO), new UserMoveStrategy(new UserInterface("Testing"), CAR_INDEX_TWO, track.getCarId(CAR_INDEX_TWO)));
@ -104,8 +115,8 @@ class GameTest {
try {
game.doCarTurn(RIGHT);
Assertions.assertEquals(new PositionVector(1, 0), game.getCarVelocity(0));
} catch (PositionVectorNotValid positionVectorNotValid) {
positionVectorNotValid.printStackTrace();
} catch (PositionVectorNotValidException positionVectorNotValidException) {
positionVectorNotValidException.printStackTrace();
}
}
@ -114,8 +125,8 @@ class GameTest {
try {
game.doCarTurn(PositionVector.Direction.UP);
Assertions.assertTrue(game.onlyOneCarLeft());
} catch (PositionVectorNotValid positionVectorNotValid) {
positionVectorNotValid.printStackTrace();
} catch (PositionVectorNotValidException positionVectorNotValidException) {
positionVectorNotValidException.printStackTrace();
}
}
}
@ -169,23 +180,15 @@ class GameTest {
UP_RIGHT,
RIGHT,
RIGHT}));
try {
game.initPhase();
Assertions.assertEquals("a",game.gamePhase());
} catch (InvalidTrackFormatException | PositionVectorNotValid e) {
e.printStackTrace();
}
}
@Test
void crashA() {
game = new Game(new interFace("Test",new Integer[]{0,2,2},new PositionVector.Direction[]{UP}));
try {
game.initPhase();
Assertions.assertEquals("b",game.gamePhase());
} catch (InvalidTrackFormatException | PositionVectorNotValid e) {
e.printStackTrace();
}
}
}

View File

@ -21,10 +21,11 @@ public class TrackTest {
File file = new File(".\\tracks\\challenge.txt");
try {
trackObj = new Track(file);
} catch (Exception | PositionVectorNotValid e) {
System.err.println("Error in Test compareTrack" + e.getMessage());
} catch (FileNotFoundException | InvalidTrackFormatException e) {
e.printStackTrace();
Assertions.fail();
}
}
@Test
@ -79,7 +80,7 @@ public class TrackTest {
track.add("##################################################");
track.add("##################################################");
Assertions.assertLinesMatch(track, trackObj.getTrack());
} catch (FileNotFoundException | InvalidTrackFormatException | PositionVectorNotValid e) {
} catch (FileNotFoundException | InvalidTrackFormatException e) {
e.printStackTrace();
}
}
@ -115,8 +116,8 @@ public class TrackTest {
Assertions.assertFalse(trackObj.willCrashAtPosition(0, new PositionVector(7, 22)));
//Car will not Crash and is on finishLine
Assertions.assertFalse(trackObj.willCrashAtPosition(0, trackObj.getFinishLine().get(0)));
} catch (PositionVectorNotValid positionVectorNotValid) {
positionVectorNotValid.printStackTrace();
} catch (PositionVectorNotValidException positionVectorNotValidException) {
positionVectorNotValidException.printStackTrace();
Assertions.fail("Test should not throw error");
}
}
@ -126,8 +127,8 @@ public class TrackTest {
void makeCarCrash() {
try {
trackObj.carDoesCrash(0, new PositionVector(6, 22));
} catch (PositionVectorNotValid positionVectorNotValid) {
positionVectorNotValid.printStackTrace();
} catch (PositionVectorNotValidException positionVectorNotValidException) {
positionVectorNotValidException.printStackTrace();
Assertions.fail("Test should not throw exception");
}
Assertions.assertEquals(Track.CRASH_INDICATOR, trackObj.getTrack().get(22).charAt(6));
@ -146,7 +147,7 @@ public class TrackTest {
try {
trackObj = new Track(file);
} catch (Exception | PositionVectorNotValid e) {
} catch (InvalidTrackFormatException | FileNotFoundException e) {
System.err.println("Error in Test compareTrack" + e.getMessage());
}
}
@ -168,8 +169,8 @@ public class TrackTest {
@Test
@DisplayName("Invalid Position Vector used")
void invalidPositionVector() {
Assertions.assertThrows(PositionVectorNotValid.class, () -> trackObj.willCrashAtPosition(0, new PositionVector(100, 200)));
Assertions.assertThrows(PositionVectorNotValid.class, () -> trackObj.carDoesCrash(1,new PositionVector(200,100)));
Assertions.assertThrows(PositionVectorNotValidException.class, () -> trackObj.willCrashAtPosition(0, new PositionVector(100, 200)));
Assertions.assertThrows(PositionVectorNotValidException.class, () -> trackObj.carDoesCrash(1,new PositionVector(200,100)));
}
}