59 lines
1.3 KiB
Java
59 lines
1.3 KiB
Java
package chess.model;
|
|
|
|
/**
|
|
* Enumation of the different directions from a cell in a chessboard, and how to navigate the cells.
|
|
*/
|
|
|
|
public enum Direction {
|
|
|
|
Unset(65),
|
|
Front(-8), Back(8), Left(-1), Right(1),
|
|
FrontLeft(-9), FrontRight(-7), BackLeft(7), BackRight(9);
|
|
|
|
private final int indexOffset;
|
|
|
|
Direction(int indexOffset) {
|
|
this.indexOffset = indexOffset;
|
|
}
|
|
|
|
public int getIndexOffset() {
|
|
return indexOffset;
|
|
}
|
|
|
|
public static Direction fromInt(int direction) {
|
|
for (Direction dir : Direction.values()) {
|
|
if (dir.getIndexOffset() == direction)
|
|
return dir;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static Direction findDirection(Move move) {
|
|
assert move.isValid() : "Move is invalid!";
|
|
int diffX = move.getFinish().getX() - move.getStart().getX();
|
|
int diffY = move.getFinish().getY() - move.getStart().getY();
|
|
|
|
if (diffX == 0 && diffY < 0)
|
|
return Direction.Front;
|
|
if (diffX == 0 && diffY > 0)
|
|
return Direction.Back;
|
|
|
|
if (diffX < 0 && diffY == 0)
|
|
return Direction.Left;
|
|
if (diffX > 0 && diffY == 0)
|
|
return Direction.Right;
|
|
|
|
if (diffX < 0 && -diffX == diffY)
|
|
return Direction.BackLeft;
|
|
if (diffX > 0 && diffX == diffY)
|
|
return Direction.BackRight;
|
|
|
|
if (diffY < 0 && diffX == diffY)
|
|
return Direction.FrontLeft;
|
|
if (diffX > 0 && diffX == -diffY)
|
|
return Direction.FrontRight;
|
|
|
|
return Direction.Unset;
|
|
}
|
|
}
|