Skip to content

Instantly share code, notes, and snippets.

@izebit
Created November 12, 2020 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izebit/459b6bc9fdf9d2a4e6c8a25651e72300 to your computer and use it in GitHub Desktop.
Save izebit/459b6bc9fdf9d2a4e6c8a25651e72300 to your computer and use it in GitHub Desktop.
chess.java
public static boolean canMove(final String chessPiece,
final String currentLocationStr,
final String targetLocationStr) {
class Position {
private int x;
private int y;
public Position(String position) {
this.x = Character.toUpperCase(position.charAt(0)) - 'A';
this.y = position.charAt(1) - '1';
}
}
final Position currentLocation = new Position(currentLocationStr);
final Position targetLocation = new Position(targetLocationStr);
switch (chessPiece) {
case "конь":
return Math.abs(currentLocation.x - targetLocation.x) + Math.abs(currentLocation.y - targetLocation.y) == 3;
case "слон":
//по диагонали
return Math.abs(currentLocation.x - targetLocation.x) == Math.abs(currentLocation.y - targetLocation.y);
case "ладья":
// по горизонтали
return currentLocation.x == targetLocation.x || currentLocation.y == targetLocation.y;
case "ферзь":
//по диагонали и горизонатали
return canMove("слон", currentLocationStr, targetLocationStr) ||
canMove("ладья", currentLocationStr, targetLocationStr);
case "король":
return Math.max(currentLocation.x, targetLocation.x) - Math.min(currentLocation.x, targetLocation.x) == 1
&& Math.max(currentLocation.y, targetLocation.y) - Math.min(currentLocation.y, targetLocation.y) == 1;
case "пешка":
return targetLocation.y - currentLocation.y == 1 && targetLocation.x == currentLocation.x;
default:
throw new IllegalArgumentException(String.format("can't recognize a chess piece: %s", chessPiece));
}
}
@izebit
Copy link
Author

izebit commented Nov 12, 2020

    System.out.println(canMove("ладья", "A8", "H8"));
    System.out.println(canMove("слон", "A7", "G1"));
    System.out.println(canMove("ферзь", "C4", "D6"));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment