2021年3月20日星期六

Elegant way to count how many pieces of each type are present in a position

I have an abstract class which has 1 attributes like so:

PieceColor {      WHITE, BLACK  }    abstract class Piece {      PieceColor color        abstract char getAbbr();  }  

This class Piece has been extended by the classes Bishop Knight Rook King Queen and Pawn. Each of those class have a method called getAbbr() which returns the abbreviation of the Piece, KQBNRP.

Now I have a Map<Piece, Tile> piecePlacements which represents all the pieces currently on the board at a particular time.

I need to count how many pieces are there of a type say White Rook, Black Queen etc. But the normal way of doing this gets too long and is very ugly to look at. This is how I did it...

//0: White pieces, 1: Black pieces; 0-5: KQRBNP      int[][] pieceCount = new int[2][6];        for(Piece piece : piecePlacements.keySet()) {          switch (piece.getAbbr()) {              case 'K' :                  if (piece.color == PieceColor.WHITE) {                      pieceCount[0][0]++;                  } else {                      pieceCount[1][0]++;                  }                  break;              case 'Q' :                  if (piece.color == PieceColor.WHITE) {                      pieceCount[0][1]++;                  } else {                      pieceCount[1][1]++;                  }                  break;              case 'R' :                  if (piece.color == PieceColor.WHITE) {                      pieceCount[0][2]++;                  } else {                      pieceCount[1][2]++;                  }                  break;              case 'B' :                  if (piece.color == PieceColor.WHITE) {                      pieceCount[0][3]++;                  } else {                      pieceCount[1][3]++;                  }                  break;              case 'N' :                  if (piece.color == PieceColor.WHITE) {                      pieceCount[0][4]++;                  } else {                      pieceCount[1][4]++;                  }                  break;              case 'P' :                  if (piece.color == PieceColor.WHITE) {                      pieceCount[0][5]++;                  } else {                      pieceCount[1][5]++;                  }                  break;           }      }  

There has to be a more elegant way to this, which takes fewer lines of code. I mean what if there were more than 6 types of pieces and 2 types of colors. I cant just keep adding cases to the switch statement like this right? But I cant figure how to make this more elegant.

https://stackoverflow.com/questions/66727759/elegant-way-to-count-how-many-pieces-of-each-type-are-present-in-a-position March 21, 2021 at 08:25AM

没有评论:

发表评论