natsi

Chess Function canBeCaptured

Oct 24th, 2025 (edited)
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | Source Code | 0 0
  1.    private static int[][] d = new int[][]{{1, 1, 'P', 'b'}, {-1, 1, 'P'}, {1, -1, 'p'}, {-1, -1, 'p'}};
  2.    private static int[][] o = new int[][]{{0, 1, '.', 'r'}, {0, -1, '.'}, {1, 0, '.'}, {-1, 0, '.'}};
  3.    private static int[][][] all = {d, o};
  4.  
  5.     public static boolean canBeCaptured(int x, int y, char[][] board) {
  6.  
  7.         char color = color(board[y][x]);
  8.         for (int[][] d_o : all) {
  9.             for (int[] dir : d_o) {
  10.                 for (int i = 1; i < 8; i++) {
  11.                     char square = get(x + i * dir[0], y + i * dir[1], board);
  12.                     if (square == ' ') {
  13.                         continue;
  14.                     }
  15.                     if (color(square) == color|| square=='x') {
  16.                         break;
  17.                     }
  18.                     if (sameLtr(square, 'q') || sameLtr(square, (char) d_o[0][3]) || (i == 1 && (square == dir[2] || sameLtr(square, 'k')))) {
  19.                         return true;
  20.                     }
  21.                     break;
  22.                 }
  23.             }
  24.         }
  25. for (int[] dir : d) {
  26.             for (int[] n : new int[][]{{2, 1}, {1, 2}}) {
  27.                 char square = get(x + n[0] * dir[0], y + n[1] * dir[1], board);
  28.                 if (sameLtr(square, 'n') && color(square) != color) {
  29.                     return true;
  30.                 }
  31.             }
  32.         }
  33.         return false;
  34.     }
  35.  
  36.  
  37.  
  38.  private static char get(int x, int y, char[][] board) {
  39.        return (x > 7 || x < 0 || y > 7 || y < 0) ? 'x' : board[y][x];
  40.     }
  41.  private static boolean sameLtr(char ch, char ch2) {
  42.         return Character.toUpperCase(ch) == Character.toUpperCase(ch2);
  43.     }
  44. private static char color(char ch) {        
  45.         return Character.isUpperCase(ch) ? 'W' : 'b';      
  46.     }
Tags: Chess function
Advertisement
Add Comment
Please, Sign In to add comment