private Coordinate getDisplacement(Direction direction) { switch (direction) { case WEST: return new Coordinate(-1, 0); case NORTH_WEST: return new Coordinate(-1, -1); case NORTH: return new Coordinate(0, -1); case NORTH_EAST: return new Coordinate(1, -1); case EAST: return new Coordinate(1, 0); case SOUTH_EAST: return new Coordinate(1, 1); case SOUTH: return new Coordinate(0, 1); case SOUTH_WEST: default: return new Coordinate(-1, 1); } }
/** * Returns the position adjacent to the provided one in a specific direction. */ public Position getAdjacentItemPosition(Position position, Direction direction) { Position adjacent; Coordinate displacement = getDisplacement(direction); int adjacentColumn = position.getColumn() + displacement.getX(); int adjacentRow = position.getRow() + displacement.getY(); int numberOfRows = getNumberOfRows(); int numberOfColumns = getNumberOfColumns(); int numberOfItems = getNumberOfItems(); if (adjacentColumn < 0 || adjacentColumn >= numberOfColumns || adjacentRow < 0 || adjacentRow > numberOfRows || adjacentColumn + numberOfColumns * adjacentRow >= numberOfItems) { adjacent = Position.INVALID_POSITION; } else { adjacent = new Position( numberOfColumns * adjacentRow + adjacentColumn, adjacentColumn, adjacentRow, numberOfColumns - 1, numberOfRows - 1); } return adjacent; }