public void move() { Grid<Actor> gr = getGrid(); if (gr == null) { return; } if (getLocation().equals(targetLocation)) { Location oldTargetLocation = targetLocation; targetLocation = initialLocation; initialLocation = oldTargetLocation; return; } Location loc = getLocation(); Location nextLocation = calculateNextLocation(loc); if (canMove(nextLocation)) { setDirection(loc.getDirectionToward(nextLocation)); moveTo(nextLocation); } else { ArrayList<Location> availableLocations = gr.getEmptyAdjacentLocations(getLocation()); if (availableLocations.get(0) != null) // if not empty { int totalDifference = 0; int leastDifference = 10; Location leastDifferenceLocation = availableLocations.get(0); for (int i = 0; i < availableLocations.size(); i++) { totalDifference += Math.abs(availableLocations.get(i).getCol() - targetLocation.getCol()); totalDifference += Math.abs(availableLocations.get(i).getRow() - targetLocation.getRow()); if (totalDifference < leastDifference) { leastDifference = totalDifference; leastDifferenceLocation = availableLocations.get(i); } totalDifference = 0; } setDirection(loc.getDirectionToward(leastDifferenceLocation)); moveTo(leastDifferenceLocation); } } }