Hay1990
Hay1990

Reputation: 101

Java chessboard border?

Im kinda stuck trying to make a border for my chessboard, running top to bottom 8-1 and left to right a-h. Im not quite sure how to do it. Advice and help is much appreciated! Cheers :)

The output is currently:

BR BKn BB BK BQ BB BKn BR
BP BP BP BP BP BP BP BP

WP WP WP WP WP WP WP WP
WR WKn WB WK WQ WB WKn WR

Below is the Java code:

public class ex5 {
public enum Chessmen {
    WHITE_KING,
    WHITE_QUEEN,
    WHITE_ROOK,
    WHITE_BISHOP,
    WHITE_KNIGHT,
    WHITE_PAWN,
    BLACK_KING,
    BLACK_QUEEN,
    BLACK_ROOK,
    BLACK_BISHOP,
    BLACK_KNIGHT,
    BLACK_PAWN,
    EMPTY
}
public static void printBoard (Chessmen [][] chessboard){
    for (int i=0; i<chessboard.length;i++){
        for (int j = 0; j<chessboard.length;j++){
            switch (chessboard [i][j]){
            case WHITE_KING:
                System.out.print("WK\t");
                break;
            case WHITE_QUEEN:
                System.out.print("WQ\t");
                break;
            case WHITE_ROOK:
                System.out.print("WR\t");
                break;
            case WHITE_BISHOP:
                System.out.print("WB\t");
                break;
            case WHITE_KNIGHT:
                System.out.print("WKn\t");
                break;
            case WHITE_PAWN:
                System.out.print("WP\t");
                break;
            case BLACK_KING:
                System.out.print("BK\t");
                break;
            case BLACK_QUEEN:
                System.out.print("BQ\t");
                break;
            case BLACK_ROOK:
                System.out.print("BR\t");
                break;
            case BLACK_BISHOP:
                System.out.print("BB\t");
                break;
            case BLACK_KNIGHT:
                System.out.print("BKn\t");
                break;
            case BLACK_PAWN:
                System.out.print("BP\t");
                break;
            default:
                System.out.print(" " + "\t");
                break;
            }
        }
        System.out.println("");
    }
}



public static void main(String[] args) {
    int Rows = 8;
    int Columns = 8;
    Chessmen [][] chessboard = new Chessmen [Rows][Columns];
    for (int i=0;i<chessboard.length; i++){
        for (int j=0;j<chessboard[0].length;j++){
            if (i==1){
                chessboard [i][j]= Chessmen.BLACK_PAWN;
            }else if (i==6){
                chessboard [i][j]= Chessmen.WHITE_PAWN;
            }else if ((i==0&&j==7)||(i==0&&j==0)){
                chessboard [i][j]= Chessmen.BLACK_ROOK;
            }else if ((i==0&&j==1)||(i==0&&j==6)){
                chessboard [i][j] = Chessmen.BLACK_KNIGHT;
            }else if ((i==0&&j==2)||(i==0&&j==5)){
                chessboard [i][j] = Chessmen.BLACK_BISHOP;
            }else if (i==0&&j==3){
                chessboard [i][j] = Chessmen.BLACK_KING;
            }else if (i==0&&j==4){
                chessboard [i][j] = Chessmen.BLACK_QUEEN;
            }else if ((i==7&&j==0)||(i==7&&j==7)){
                chessboard [i][j]= Chessmen.WHITE_ROOK;
            }else if ((i==7&&j==1)||(i==7&&j==6)){
                chessboard [i][j] = Chessmen.WHITE_KNIGHT;
            }else if ((i==7&&j==2)||(i==7&&j==5)){
                chessboard [i][j] = Chessmen.WHITE_BISHOP;
            }else if (i==7&&j==3){
                chessboard [i][j] = Chessmen.WHITE_KING;
            }else if (i==7&&j==4){
                chessboard [i][j] = Chessmen.WHITE_QUEEN;
        }else {
                chessboard [i][j]= Chessmen.EMPTY;
            }

        }   

    }
        printBoard (chessboard);

}
}

Upvotes: 1

Views: 2997

Answers (4)

mistahenry
mistahenry

Reputation: 8744

I did this for an N queens problem in Java. So, if you're trying to print other pieces besides a queen, then tailor your code accordingly. If you are unfamiliar with this problem, it's the challenge of placing N queens on an N x N chessboard such that no two queens are checking each other. I know this is years after you posted the question, but I figured I'd put the code snippets on here for someone to use in the future.

Anyway, first step is to create our N x N array representing the spaces on a chessboard and the value of the pieces currently on the board. It's worth noting that since this is Java, our board is 0-based (as in the spaces in each row are numbered 0 to 7, not 1 to 8):

public static final int N = 8;
public static char [][] board = new char[N][N];
//initialize every space to a space
for(int i = 0; i < N; i++){
    for(int j = 0; j < N; j++){
        board[i][j] = ' ';
    }
}

See we initialize every spot to a space, so that we can then iterate through the vector I have for the queens locations and only alter the spots where a Queen needs to be placed.

Here's an example vector of a solution: [1 6 2 5 7 4 0 3]. Let's assume this vector is represented by int[] vector = new int[N].The number of elements is equal to the number of rows in the board. It's index in the vector corresponds to the row, and the value itself corresponds to the column number where the queen is in that row. So we just loop through these and update the board array accordingly:

for(int j = 0; j < N; j++){
    board[j][vector[j]] = 'Q';
}

If your problem involves an actual game of chess, you would need to iterate through every piece and update its board location in a similar manner.

Before I explain how to make this board, let me show you the board that corresponds to the vector mentioned previously. As an aside, notice how no queens are checking! I solved this problem using genetic algorithms.

+---+---+---+---+---+---+---+---+
|   | Q |   |   |   |   |   |   | 
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   | Q |   | 
+---+---+---+---+---+---+---+---+
|   |   | Q |   |   |   |   |   | 
+---+---+---+---+---+---+---+---+
|   |   |   |   |   | Q |   |   | 
+---+---+---+---+---+---+---+---+
|   |   |   |   |   |   |   | Q | 
+---+---+---+---+---+---+---+---+
|   |   |   |   | Q |   |   |   | 
+---+---+---+---+---+---+---+---+
| Q |   |   |   |   |   |   |   | 
+---+---+---+---+---+---+---+---+
|   |   |   | Q |   |   |   |   | 
+---+---+---+---+---+---+---+---+

Our next step is to create the borders in between rows (and on the top and bottom). I treat each row as a formatted string. Since we have space rows and border rows, our row array is 2 * N + 1 in size.

String[] row = new String[2*N + 1];
String border = "";
//must be the length of board
for(int i = 0; i < N; i++){
    border += "+---";
}
border += "+";
//every other row is a border row
for(int i = 0; i < 2*N +1; i+=2){
    row[i] = border;
}
//must include the bottom
row[2*N] = border;

Next we create the strings for the board spaces themselves. Since we already have these in our board[][], we only need to format.

for(int i = 0; i < N; i++){
    //left bar
    String spaces = "| ";
    //place enclosing right bar and spaces so next char goes in middle of next space
    for(int j = 0; j < N; j++){
        spaces += board[i][j];
        spaces += " | ";
    }
    //add the spaces string to the rows at the odd indices
    row[2*k +1 ] = spaces;

}

All that's left is to print that board.

for(int i = 0; i < 2*N +1; i++){
    System.out.println(row[i]);
}

Hope this helps somebody!

Upvotes: 0

Mathieu Pag&#233;
Mathieu Pag&#233;

Reputation: 11094

As other have said, you need to display the empty lines and the empty squares on a line. Also, you need to print the same amount of characters for every squares, so I suggest you use BN for a black night and BK for a black king. N is used to represenet the knight in algebraic chess notation to differentiate it from the king.

Since I already solve this problem in C++, I'll post my code below. You could use it as an algorithm to translate it in Java. It will display a board like this :

  (Coups reversibles : 0)
  +-X-+---+---+---+---+---+---+-X-+
8 |=R=|=N=|=B=|=Q=|=K=|=B=|=N=|=R=|
  +---+---+---+---+---+---+---+---+
7 |=P=|=P=|=P=|=P=|=P=|=P=|=P=|=P=|
  +---+---+---+---+---+---+---+---+
6 |   | . |   | . |   | . |   | . |
  +---+---+---+---+---+---+---+---+
5 | . |   | . |   | . |   | . |   |
  +---+---+---+---+---+---+---+---+
4 |   | . |   | . |   | . |   | . |
  +---+---+---+---+---+---+---+---+
3 | . |   | . |   | . |   | . |   |
  +---+---+---+---+---+---+---+---+
2 | P | P | P | P | P | P | P | P |
  +---+---+---+---+---+---+---+---+
1 | R | N | B | Q | K | B | N | R |
=>+-X-+---+---+---+---+---+---+-X-+
    a   b   c   d   e   f   g   h

It has, I think some interesings features. Black square without piece have a dot in their center. An arrow on the bottom on the board or on the top tells the user which side is to move next. An 'X' or the absence of it tells you if a rook can castle. An arrow '^' bellow a column indicate that the pawn in the said column can be taken "en passant".

So here is the code (There may be errors, I just translated the identifiers and comments from french whitout compiling it again) :

///////////////////////////////////////////////////////////////////////////
   std::ostream& operator << (std::ostream& out, const CPlanche& planche)
   {
      static const string piecesNames[] = {"   ","   ",
                                            " P ","=P=",
                                            " N ","=N=",
                                            " K ","=K=",
                                            "   ","   ",
                                            " B ","=B=",
                                            " R ","=R=",
                                            " Q ","=Q="};

      // We display how many revirsable moves have been playes
      out <<"  (Coups reversibles : " <<board.RecersiblesMoves() <<")\n";

      // If it's black to move we display an arrow
      if (board.ColorToMove() == BLACK)
      {
         out <<"=>";
      }
      else
      {
         out <<"  ";
      }

      // We display the top line
      out <<"+-" <<(Board.Castling(Black, QueenSideCastling)?'X':'-') <<"-+---+---+---+---+---+---+-" <<(board.Castling(Black, LingSideCastling)?'X':'-') <<"-+\n";

      // We display all 8 lines
      for (int line = 0; line < 8; line++)
      {
        out <<(char)('8' - line) <<' ';

        // for each column
        for (int column = 0; column < 8; column++)
        {
          out <<'|';

          if (board[56 - 8 * line + column] != EMPTY)
          {
             out <<piecesNames[board[56 - 8 * iLigne + column]];
          }
          else
          {
            // If both the line and column are even OR if both are odds
            if (!((line | column) & 1) || (line & column & 1))
            {
               out <<"   ";
            }
            else
            {
               out <<" . ";
            }
          }
        }

        out <<"|\n";

        if (line != 7)
        {
          out <<"  +---+---+---+---+---+---+---+---+\n";
        }
      }

      // If it's white to move we display an arrow
      if (board.ColorToMove() == WHITE)
      {
         out <<"=>";
      }
      else
      {
         out <<"  ";
      }

      // We display the bottom line
      out <<"+-" <<(planche.Castling(WHITE, CastlingQueenSide)?'X':'-') <<"-+---+---+---+---+---+---+-" <<(Board.Castling(WHITE, CastlingKingSide)?'X':'-') <<"-+\n";

      // Whe display the arrow for the prise en passant if there is one.
      if (board.ColumnPriseEnPassant() != NO_PRISE_EN_PASSANT)
      {
         for (int i = 0; i < (board.ColumnPriseEnPassant() + 1); i++)
         {
            out <<"    ";
         }
         out <<"^\n";
      }

      // We display the columns letters
      out <<"    a   b   c   d   e   f   g   h\n";

      return out;
   }

I hope this helps.

mp

Upvotes: 2

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28439

[EDIT] In response to your comment...

I think what you want is actually a 10x10 grid, and you'll need to adjust your logic to only print the game area as 8x8 inside the 10x10 and use the outer squares (not including the corners) to print your letters and numbers. [ END EDIT]

your default isn't EMPTY it's just nothing. catch the EMPTY case in your switch and print your tab and you'll see all your empty spaces

in other words, instead of

case BLACK_PAWN:
            System.out.print("BP\t");
            break;
        default:
            System.out.print(" " + "\t");
            break;
        }

you want to do:

case BLACK_PAWN:
            System.out.print("BP\t");
            break;
        case EMPTY:
            System.out.print(" " + "\t");
            break;
        }

Upvotes: 0

mcfinnigan
mcfinnigan

Reputation: 11638

call System.out.println("+--------------------------------+") before and after your outer rendering loop.

call System.out.print("|") before and after the inner rendering loop.

You'll need to tweak it a bit.

Upvotes: 2

Related Questions