Initial commit

This commit is contained in:
romanschenk37
2022-03-04 09:04:12 +01:00
parent 19b297fb03
commit 16d287e273
35 changed files with 1505 additions and 19 deletions
@@ -0,0 +1,134 @@
package ch.zhaw.pm2.racetrack;
import ch.zhaw.pm2.racetrack.given.CarSpecification;
import ch.zhaw.pm2.racetrack.strategy.MoveStrategy;
/**
* Class representing a car on the racetrack.
* Uses {@link PositionVector} to store current position on the track grid and current velocity vector.
* Each car has an identifier character which represents the car on the race track board.
* Also keeps the state, if the car is crashed (not active anymore). The state can not be changed back to uncrashed.
* The velocity is changed by providing an acelleration vector.
* The car is able to calculate the endpoint of its next position and on request moves to it.
*/
public class Car implements CarSpecification {
/**
* Car identifier used to represent the car on the track
*/
private final char id;
/**
* Current position of the car on the track grid using a {@link PositionVector}
*/
private PositionVector position;
/**
* Current velocity of the car using a {@link PositionVector}
*/
private PositionVector velocity = new PositionVector(0, 0);
/**
* Indicator if the car has crashed
*/
private boolean crashed = false;
/**
* Current move strategy
*/
private MoveStrategy moveStrategy;
/**
* Constructor for class Car
* @param id unique Car identification
* @param position initial position of the Car
*/
public Car(char id, PositionVector position) {
this.id = id;
setPosition(position);
}
/**
* Set this Car position directly, regardless of current position and velocity.
* This should only be used by the game controller in rare cases to set the crash or winning position.
* The next position is normaly automatically calculated and set in the {@link #move()} method.
*
* @param position The new position to set the car directly to.
*/
@Override
public void setPosition(final PositionVector position) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Return the position that will apply after the next move at the current velocity.
* Does not complete the move, so the current position remains unchanged.
*
* @return Expected position after the next move
*/
@Override
public PositionVector nextPosition() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Add the specified amounts to this cars's velocity.
* The only acceleration values allowed are -1, 0 or 1 in both axis
* There are 9 possible acceleration vectors, which are defined in {@link PositionVector.Direction}.
* Changes only velocity, not position.
*
* @param acceleration A Direction vector containing the amounts to add to the velocity in x and y dimension
*/
@Override
public void accelerate(PositionVector.Direction acceleration) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Update this Car's position based on its current velocity.
*/
@Override
public void move() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Mark this Car as being crashed.
*/
@Override
public void crash() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Returns whether this Car has been marked as crashed.
*
* @return Returns true if crash() has been called on this Car, false otherwise.
*/
@Override
public boolean isCrashed() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Set move strategy
* @param moveStrategy
*/
public void setMoveStrategy(MoveStrategy moveStrategy) {
this.moveStrategy = moveStrategy;
}
/**
* Get current move strategy
* @return MoveStrategy
*/
public MoveStrategy getMoveStrategy() {
return this.moveStrategy;
}
}
@@ -0,0 +1,47 @@
package ch.zhaw.pm2.racetrack;
import ch.zhaw.pm2.racetrack.given.ConfigSpecification;
import java.io.File;
import java.util.Objects;
public class Config implements ConfigSpecification {
// Directory containing the track files
private File trackDirectory = new File("tracks");
// Directory containing the track files
private File moveDirectory = new File("moves");
// Directory containing the follower files
private File followerDirectory = new File("follower");
public File getMoveDirectory() {
return moveDirectory;
}
public void setMoveDirectory(File moveDirectory) {
Objects.requireNonNull(moveDirectory);
this.moveDirectory = moveDirectory;
}
public File getFollowerDirectory() {
return followerDirectory;
}
public void setFollowerDirectory(File followerDirectory) {
Objects.requireNonNull(followerDirectory);
this.followerDirectory = followerDirectory;
}
public File getTrackDirectory() {
return trackDirectory;
}
public void setTrackDirectory(File trackDirectory) {
Objects.requireNonNull(trackDirectory);
this.trackDirectory = trackDirectory;
}
}
@@ -0,0 +1,141 @@
package ch.zhaw.pm2.racetrack;
import ch.zhaw.pm2.racetrack.given.GameSpecification;
import java.util.List;
import static ch.zhaw.pm2.racetrack.PositionVector.Direction;
/**
* Game controller class, performing all actions to modify the game state.
* It contains the logic to move the cars, detect if they are crashed
* and if we have a winner.
*/
public class Game implements GameSpecification {
public static final int NO_WINNER = -1;
/**
* 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.
* @return The zero-based number of the current car
*/
@Override
public int getCurrentCarIndex() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Get the id of the specified car.
* @param carIndex The zero-based carIndex number
* @return A char containing the id of the car
*/
@Override
public char getCarId(int carIndex) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Get the position of the specified car.
* @param carIndex The zero-based carIndex number
* @return A PositionVector containing the car's current position
*/
@Override
public PositionVector getCarPosition(int carIndex) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Get the velocity of the specified car.
* @param carIndex The zero-based carIndex number
* @return A PositionVector containing the car's current velocity
*/
@Override
public PositionVector getCarVelocity(int carIndex) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* 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
*/
@Override
public int getWinner() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Execute the next turn for the current active car.
* <p>This method changes the current car's velocity and checks on the path to the next position,
* if it crashes (car state to crashed) or passes the finish line in the right direction (set winner state).</p>
* <p>The steps are as follows</p>
* <ol>
* <li>Accelerate the current car</li>
* <li>Calculate the path from current (start) to next (end) position
* (see {@link Game#calculatePath(PositionVector, PositionVector)})</li>
* <li>Verify for each step what space type it hits:
* <ul>
* <li>TRACK: check for collision with other car (crashed &amp; don't continue), otherwise do nothing</li>
* <li>WALL: car did collide with the wall - crashed &amp; don't continue</li>
* <li>FINISH_*: car hits the finish line - wins only if it crosses the line in the correct direction</li>
* </ul>
* </li>
* <li>If the car crashed or wins, set its position to the crash/win coordinates</li>
* <li>If the car crashed, also detect if there is only one car remaining, remaining car is the winner</li>
* <li>Otherwise move the car to the end position</li>
* </ol>
* <p>The calling method must check the winner state and decide how to go on. If the winner is different
* than {@link Game#NO_WINNER}, or the current car is already marked as crashed the method returns immediately.</p>
*
* @param acceleration A Direction containing the current cars acceleration vector (-1,0,1) in x and y direction
* for this turn
*/
@Override
public void doCarTurn(Direction acceleration) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Switches to the next car who is still in the game. Skips crashed cars.
*/
@Override
public void switchToNextActiveCar() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Returns all of the grid positions in the path between two positions, for use in determining line of sight.
* Determine the 'pixels/positions' on a raster/grid using Bresenham's line algorithm.
* (https://de.wikipedia.org/wiki/Bresenham-Algorithmus)
* Basic steps are
* - 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.
* Direction of the movement has to correctly considered
* @param startPosition Starting 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.
*/
@Override
public List<PositionVector> calculatePath(PositionVector startPosition, PositionVector endPosition) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* 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 position A PositionVector of the possible crash position
* @return A boolean indicator if the car would crash with a WALL or another car.
*/
@Override
public boolean willCarCrash(int carIndex, PositionVector position) {
// TODO: implementation
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,5 @@
package ch.zhaw.pm2.racetrack;
public class InvalidFileFormatException extends Exception {
// TODO: implementation
}
@@ -0,0 +1,5 @@
package ch.zhaw.pm2.racetrack;
public class InvalidTrackFormatException extends Exception {
// TODO: implementation
}
@@ -0,0 +1,114 @@
package ch.zhaw.pm2.racetrack;
/**
* Holds a position (vector to x,y-position of the car on the track grid)
* or a velocity vector (x,y-components of the velocity vector of a car).
*
* Created by mach 21.01.2020
*/
public final class PositionVector {
private int x; // horizontal component (position / velocity)
private int y; // vertical component (position / velocity)
/**
* Enum representing a direction on the track grid.
* Also representing the possible acceleration values.
*/
public enum Direction {
DOWN_LEFT(new PositionVector(-1, 1)),
DOWN(new PositionVector(0, 1)),
DOWN_RIGHT(new PositionVector(1, 1)),
LEFT(new PositionVector(-1, 0)),
NONE(new PositionVector(0, 0)),
RIGHT(new PositionVector(1, 0)),
UP_LEFT(new PositionVector(-1, -1)),
UP(new PositionVector(0, -1)),
UP_RIGHT(new PositionVector(1, -1));
public final PositionVector vector;
Direction(final PositionVector v) {
vector = v;
}
}
/**
* Adds two PositionVectors (e.g. car position and velocity vector or two velocity vectors).
* @param vectorA A position or velocity vector
* @param vectorB A position or velocity vector
* @return A new PositionVector holding the result of the addition. If both
* arguments are positions (not velocity), the result is mathematically
* correct but meaningless.
*/
public static PositionVector add(final PositionVector vectorA, final PositionVector vectorB) {
return new PositionVector(vectorA.getX() + vectorB.getX(), vectorA.getY() + vectorB.getY());
}
/**
* Subtracts two PositionVectors (e.g. car position and velocity vector or two velocity vectors).
* @param vectorA A position or velocity vector
* @param vectorB A position or velocity vector
* @return A new PositionVector holding the result of the addition. If both
* arguments are positions (not velocity), the result is mathematically
* correct but meaningless.
*/
public static PositionVector subtract(final PositionVector vectorA, final PositionVector vectorB) {
return new PositionVector(vectorA.getX() - vectorB.getX(), vectorA.getY() - vectorB.getY());
}
/**
* Calculates the scalar product (Skalarprodukt) of two 2D vectors. The scalar product
* multiplies the lengths of the parallel components of the vectors.
* @param vectorA A position or velocity vector
* @param vectorB A position or velocity vector
* @return The scalar product (vectorA * vectorB). Since vectorA and
* vectorB are PositionVectors, which hold only integer coordinates,
* the resulting scalar product is an integer.
*/
public static int scalarProduct(final PositionVector vectorA, final PositionVector vectorB) {
return (vectorA.getY() * vectorB.getY()) + (vectorA.getX() * vectorB.getX());
}
public PositionVector(final int x, final int y) {
this.y = y;
this.x = x;
}
/**
* Copy constructor
* @param other
*/
public PositionVector(final PositionVector other) {
this.x = other.getX();
this.y = other.getY();
}
public PositionVector() {
this.x = 0;
this.y = 0;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
@Override
public boolean equals(final Object other) {
if (!(other instanceof PositionVector)) throw new ClassCastException();
final PositionVector otherPositionVector = (PositionVector) other;
return this.y == otherPositionVector.getY() && this.x == otherPositionVector.getX();
}
@Override
public int hashCode() {
return this.x ^ this.y;
}
@Override
public String toString() {
return "(X:" + this.x + ", Y:" + this.y + ")";
}
}
@@ -0,0 +1,169 @@
package ch.zhaw.pm2.racetrack;
import ch.zhaw.pm2.racetrack.given.TrackSpecification;
import java.io.File;
import java.io.FileNotFoundException;
/**
* This class represents the racetrack board.
*
* <p>The racetrack board consists of a rectangular grid of 'width' columns and 'height' rows.
* The zero point of he grid is at the top left. The x-axis points to the right and the y-axis points downwards.</p>
* <p>Positions on the track grid are specified using {@link PositionVector} objects. These are vectors containing an
* x/y coordinate pair, pointing from the zero-point (top-left) to the addressed space in the grid.</p>
*
* <p>Each position in the grid represents a space which can hold an enum object of type {@link Config.SpaceType}.<br>
* Possible Space types are:
* <ul>
* <li>WALL : road boundary or off track space</li>
* <li>TRACK: road or open track space</li>
* <li>FINISH_LEFT, FINISH_RIGHT, FINISH_UP, FINISH_DOWN : finish line spaces which have to be crossed
* in the indicated direction to winn the race.</li>
* </ul>
* <p>Beside the board the track contains the list of cars, with their current state (position, velocity, crashed,...)</p>
*
* <p>At initialization the track grid data is read from the given track file. The track data must be a
* rectangular block of text. Empty lines at the start are ignored. Processing stops at the first empty line
* following a non-empty line, or at the end of the file.</p>
* <p>Characters in the line represent SpaceTypes. The mapping of the Characters is as follows:</p>
* <ul>
* <li>WALL : '#'</li>
* <li>TRACK: ' '</li>
* <li>FINISH_LEFT : '&lt;'</li>
* <li>FINISH_RIGHT: '&gt;'</li>
* <li>FINISH_UP : '^;'</li>
* <li>FINISH_DOWN: 'v'</li>
* <li>Any other character indicates the starting position of a car.<br>
* The character acts as the id for the car and must be unique.<br>
* There are 1 to {@link Config#MAX_CARS} allowed. </li>
* </ul>
*
* <p>All lines must have the same length, used to initialize the grid width).
* Beginning empty lines are skipped.
* The the tracks ends with the first empty line or the file end.<br>
* An {@link InvalidTrackFormatException} is thrown, if
* <ul>
* <li>not all track lines have the same length</li>
* <li>the file contains no track lines (grid height is 0)</li>
* <li>the file contains more than {@link Config#MAX_CARS} cars</li>
* </ul>
*
* <p>The Track can return a String representing the current state of the race (including car positons)</p>
*/
public class Track implements TrackSpecification {
public static final char CRASH_INDICATOR = 'X';
// TODO: Add necessary variables
/**
* Initialize a Track from the given track file.
*
* @param trackFile Reference to a file containing the track data
* @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 {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Return the type of space at the given position.
* If the location is outside the track bounds, it is considered a wall.
*
* @param position The coordinates of the position to examine
* @return The type of track position at the given location
*/
@Override
public Config.SpaceType getSpaceType(PositionVector position) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Return the number of cars.
*
* @return Number of cars
*/
@Override
public int getCarCount() {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Get instance of specified car.
*
* @param carIndex The zero-based carIndex number
* @return The car instance at the given index
*/
@Override
public Car getCar(int carIndex) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Get the id of the specified car.
*
* @param carIndex The zero-based carIndex number
* @return A char containing the id of the car
*/
@Override
public char getCarId(int carIndex) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Get the position of the specified car.
*
* @param carIndex The zero-based carIndex number
* @return A PositionVector containing the car's current position
*/
@Override
public PositionVector getCarPos(int carIndex) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Get the velocity of the specified car.
*
* @param carIndex The zero-based carIndex number
* @return A PositionVector containing the car's current velocity
*/
@Override
public PositionVector getCarVelocity(int carIndex) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Gets character at the given position.
* If there is a crashed car at the position, {@link #CRASH_INDICATOR} is returned.
*
* @param y position Y-value
* @param x position X-vlaue
* @param currentSpace char to return if no car is at position (x,y)
* @return character representing position (x,y) on the track
*/
@Override
public char getCharAtPosition(int y, int x, Config.SpaceType currentSpace) {
// TODO: implementation
throw new UnsupportedOperationException();
}
/**
* Return a String representation of the track, including the car locations.
*
* @return A String representation of the track
*/
@Override
public String toString() {
// TODO: implementation
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,25 @@
package ch.zhaw.pm2.racetrack.given;
import ch.zhaw.pm2.racetrack.PositionVector;
import ch.zhaw.pm2.racetrack.strategy.MoveStrategy;
/**
* This interface specifies stuff we use to test Racetrack for grading. It shall not be altered!
*/
public interface CarSpecification {
void setPosition(PositionVector position);
PositionVector nextPosition();
void accelerate(PositionVector.Direction acceleration);
void move();
void crash();
boolean isCrashed();
void setMoveStrategy(MoveStrategy moveStrategy);
MoveStrategy getMoveStrategy();
}
@@ -0,0 +1,54 @@
package ch.zhaw.pm2.racetrack.given;
import java.io.File;
/**
* This interface specifies stuff we use to test Racetrack for grading. It shall not be altered! <br/>
* It defines how the Game can be configured.
*/
public interface ConfigSpecification {
int MAX_CARS = 9;
File getMoveDirectory();
void setMoveDirectory(File moveDirectory);
File getFollowerDirectory();
void setFollowerDirectory(File followerDirectory);
File getTrackDirectory();
void setTrackDirectory(File trackDirectory);
/**
* Possible Move Strategies selected by the Console to configure the Cars. (This shall not be altered!)
*/
public enum StrategyType {
DO_NOT_MOVE, USER, MOVE_LIST, PATH_FOLLOWER
}
/**
* Possible space types of the grid. (This shall not be altered!)
* The char value is used to parse from the track file and represents
* the space type in the text representation created by toString().
*/
public enum SpaceType {
WALL('#'),
TRACK(' '),
FINISH_UP('^'),
FINISH_DOWN('v'),
FINISH_LEFT('<'),
FINISH_RIGHT('>');
public final char value;
SpaceType(final char c) {
value = c;
}
public char getValue() {
return value;
}
}
}
@@ -0,0 +1,28 @@
package ch.zhaw.pm2.racetrack.given;
import ch.zhaw.pm2.racetrack.PositionVector;
import java.util.List;
/**
* This interface specifies stuff we use to test Racetrack for grading. It shall not be altered!
*/
public interface GameSpecification {
int getCurrentCarIndex();
char getCarId(int carIndex);
PositionVector getCarPosition(int carIndex);
PositionVector getCarVelocity(int carIndex);
int getWinner();
void doCarTurn(PositionVector.Direction acceleration);
void switchToNextActiveCar();
List<PositionVector> calculatePath(PositionVector startPosition, PositionVector endPosition);
boolean willCarCrash(int carIndex, PositionVector position);
}
@@ -0,0 +1,25 @@
package ch.zhaw.pm2.racetrack.given;
import ch.zhaw.pm2.racetrack.Config;
import ch.zhaw.pm2.racetrack.PositionVector;
/**
* This interface specifies stuff we use to test Racetrack for grading. It shall not be altered!
*/
public interface TrackSpecification {
Config.SpaceType getSpaceType(PositionVector position);
int getCarCount();
CarSpecification getCar(int carIndex);
char getCarId(int carIndex);
PositionVector getCarPos(int carIndex);
PositionVector getCarVelocity(int carIndex);
char getCharAtPosition(int y, int x, Config.SpaceType currentSpace);
String toString();
}
@@ -0,0 +1,15 @@
package ch.zhaw.pm2.racetrack.strategy;
import static ch.zhaw.pm2.racetrack.PositionVector.Direction;
/**
* Do not accelerate in any direction.
*/
public class DoNotMoveStrategy implements MoveStrategy {
@Override
public Direction nextMove() {
// TODO: implementation
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,12 @@
package ch.zhaw.pm2.racetrack.strategy;
import ch.zhaw.pm2.racetrack.PositionVector.Direction;
public class MoveListStrategy implements MoveStrategy {
@Override
public Direction nextMove() {
// TODO: implementation
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,7 @@
package ch.zhaw.pm2.racetrack.strategy;
import static ch.zhaw.pm2.racetrack.PositionVector.Direction;
public interface MoveStrategy {
Direction nextMove();
}
@@ -0,0 +1,15 @@
package ch.zhaw.pm2.racetrack.strategy;
import ch.zhaw.pm2.racetrack.PositionVector.Direction;
/**
* The PathFollowerMoveStrategy class determines the next move based on a file containing points on a path.
*/
public class PathFollowerMoveStrategy implements MoveStrategy {
@Override
public Direction nextMove() {
// TODO: implementation
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,15 @@
package ch.zhaw.pm2.racetrack.strategy;
import ch.zhaw.pm2.racetrack.PositionVector.Direction;
/**
* Let the user decide the next move.
*/
public class UserMoveStrategy implements MoveStrategy {
@Override
public Direction nextMove() {
// TODO: implementation
throw new UnsupportedOperationException();
}
}
@@ -0,0 +1,29 @@
package ch.zhaw.pm2.racetrack;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PositionVectorTest {
@Test
void testEquals() {
PositionVector a = new PositionVector(3, 5);
PositionVector b = new PositionVector(3, 5);
assertEquals(a, b);
}
@Test
void testEqualsWithHashMap() {
Map<PositionVector, Integer> map = new HashMap<>();
PositionVector a = new PositionVector(3, 5);
map.put(a, 1);
PositionVector b = new PositionVector(3, 5);
assertTrue(map.containsKey(a), "Test with same object");
assertTrue(map.containsKey(b), "Test with equal object");
}
}