diff --git a/src/main/java/ch/zhaw/pm2/racetrack/Game.java b/src/main/java/ch/zhaw/pm2/racetrack/Game.java index c969298..25ceac2 100644 --- a/src/main/java/ch/zhaw/pm2/racetrack/Game.java +++ b/src/main/java/ch/zhaw/pm2/racetrack/Game.java @@ -141,8 +141,58 @@ public class Game implements GameSpecification { */ @Override public List calculatePath(PositionVector startPosition, PositionVector endPosition) { - // TODO: implementation - throw new UnsupportedOperationException(); + ArrayList pathList = new ArrayList(); + // Use Bresenham's algorithm to determine positions. + int x = startPosition.getX(); + int y = startPosition.getY(); + + // Relative Distance (x & y axis) between end- and starting position + int diffX = endPosition.getX() - startPosition.getY(); + int diffY = endPosition.getY() - startPosition.getY(); + + // Absolute distance (x & y axis) between end- and starting position + int distX = Math.abs(diffX); + int distY = Math.abs(diffY); + + // Direction of vector on x & y axis (-1: to left/down, 0: none, +1 : to right/up) + int dirX = Integer.signum(diffX); + int dirY = Integer.signum(diffY); + + // Determine which axis is the fast direction and set parallel/diagonal step values + int parallelStepX, parallelStepY; + int diagonalStepX, diagonalStepY; + int distanceSlowAxis, distanceFastAxis; + if (distX > distY) { + // x axis is the 'fast' direction + parallelStepX = dirX; parallelStepY = 0; // parallel step only moves in x direction + diagonalStepX = dirX; diagonalStepY = dirY; // diagonal step moves in both directions + distanceSlowAxis = distY; + distanceFastAxis = distX; + } else { + // y axis is the 'fast' direction + parallelStepX = 0; parallelStepY = dirY; // parallel step only moves in y direction + diagonalStepX = dirX; diagonalStepY = dirY; // diagonal step moves in both directions + distanceSlowAxis = distX; + distanceFastAxis = distY; + } + + int error = distanceFastAxis/2; + for(int step = 0; step < distanceFastAxis; step ++) { + error -= distanceSlowAxis; + if (error < 0) { + error += distanceFastAxis; // correct error value to be positive again + // step into slow direction; diagonal step + x += diagonalStepX; + y += diagonalStepY; + } else { + // step into fast direction; parallel step + x += parallelStepX; + y += parallelStepY; + } + + pathList.add(new PositionVector(x,y)); + } + return pathList; }