Created
November 12, 2020 09:29
-
-
Save izebit/459b6bc9fdf9d2a4e6c8a25651e72300 to your computer and use it in GitHub Desktop.
chess.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Author
izebit
commented
Nov 12, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment