Simplified Chess Engine

  • + 0 comments

    Some fun debugging output for people sticking with the original data structure -- will show what the whole chess board looks like with nice chess unicode characters:

    turn : 1
    
     4 ♞⬛♜⬛
     3 ⬛♛♘♖
     2 ⬜⬛♜⬛
     1 ⬛♝⬛♕
        A B C D
    
    turn : 2
    
     4 ♞⬛♜⬛
     3 ⬛♛♘♖
     2 ♝⬛♜⬛
     1 ⬛⬜⬛♕
        A B C D
    	 
    

    Code:

        // displays the full board for debugging
        static void debugBoard(char[][] white, char[][] black){
            String padding = " "; //changing this helps with weird output
            char[] board = new char[16];
            char[][][] players = new char[2][][];
            if(white == null || black == null)
                return;
            players[0] = black; players[1] = white;
            for(int i = 0; i < board.length; i++)
                board[i] = (i%2==(((i/4)%2==1)?1:0))?(char)11036:(char)11035; // unicode for white and black squares
            for(int i = 0; i < players.length; i++){
                for(char[] piece: players[i]){
                    if(piece == null || piece.length < 3)
                        continue;
                    int x = (piece[1] - '0')-17; // A becomes 1, B becomes 2 etc
                    int y = (piece[2] - '0'); // same thing but with numbers
                    int pieceUnicode = 0;
                    switch(piece[0]){
                        case 'Q': pieceUnicode = 9813; break;
                        case 'R': pieceUnicode = 9814; break;
                        case 'B': pieceUnicode = 9815; break;
                        case 'N': pieceUnicode = 9816; break;
                    }
                    board[x + (16-4*y)] = (char)(pieceUnicode+((i==0)?6:0)); // black piece = white piece + 6
                }
            }
            System.out.print("\n" + padding + "4 ");
            for(int i = 0; i < board.length; i++){
                System.out.print(board[i]);
                if((i+1)%4 == 0 && i !=0 && i != board.length -1)
                    System.out.print("\n" + padding +((16-i+1)/4) + " ");
            }
            System.out.println("\n" + padding + "  A B C D\n");
        }
    

    Just call

    debugBoard(char[][] white, char[][] black);  
    

    wherever you want and it will output the board.

    Note: hackerrank is a very buggy website, so occasionally this will happen:

     4 ������������
     3 ������������
     2 ������������
     1 ������������
        A B C D
    

    To temporarily fix this issue, it can help to add a bunch of spaces to the padding string at the top of the method. Another note: If the method is given white and black piece arrays with conflicting pieces, it will simply display the white piece. eg.

    Black Piece: B B 1, White Piece: Q B 1

    In this case B1 will be displayed with the white queen. Be wary of this in case your code isn't properly getting rid of taken pieces.