我正在使用Java构建国际象棋游戏(可能不会使用任何gui或任何简单的控制台游戏),但是我有ChessBoard类,如下所示:
public class ChessBoard {
private BasePiece[][] board = new BasePiece[8][8];
private int charToInt(char input){
return (int)input - 97;
}
public void setPiece(String colour, String type, char x, int y){
board[charToInt(x)][y-1] = new BasePiece(colour, type);
}
public void setPiece(String piece, char x, int y){
board[charToInt(x)][y-1] = new BasePiece(piece);
}
public String getPiece(char x, int y){
return board[charToInt(x)][y-1].getPiece();
}
}
这是目前非常简单的代码,能够将部件添加到板上,然后打印出任何给定位置的部件,但是我还有一个ChessPiece类,如下所示:
public class ChessPiece {
private String colour;
private String type;
ChessPiece(String colour, String type){
setColour(colour);
setType(type);
}
ChessPiece(String piece){
setColour(piece.toCharArray()[0]);
setType(piece.toCharArray()[1]);
}
private void setColour(String colour){
this.colour = colour.toLowerCase();
}
private void setColour(char colour){
switch (colour) {
case 'w':
setColour("white");
break;
case 'b':
setColour("black");
break;
default:
setColour("invalid colour");
break;
}
}
private void setType(String type){
this.type = type.toLowerCase();
}
private void setType(char type){
switch (type) {
case 'K':
setType("king");
break;
case 'q':
setType("queen");
break;
case 'r':
setType("rook");
break;
case 'b':
setType("bishop");
break;
case 'k':
setType("knight");
break;
case 'p':
setType("pawn");
break;
default:
setType("invalid type");
break;
}
}
public String getColour(){
return colour;
}
public String getType(){
return type;
}
public String getPiece(){
return getColour() + " " + getType();
}
}
到目前为止一切正常,但是我想知道让棋子移动是更好的做法(所以移动应该在ChessPiece类中进行)还是仅具有如何在ChessPiece类中移动然后再给出将他们转移到ChessBoard类的实际工作 谢谢
答案 0 :(得分:1)
正如我在评论中提到的那样,我认为您的OOP结构可能有点过于简单。我建议您考虑创建:
public boolean moveAllowed(ChessSquare square)
的几种方法,它们返回true。 List<ChessPiece> capturedPieces
,用于进行移动,提议平局,投降的方法... 答案 1 :(得分:0)
您应该使用computer style chess notation
来回答这个正则表达式"^[a-h][1-8][a-h][1-8]$"
所代表的四个字符的问题:例如,e1g1
表示怀特城堡为白宫,{{1 }}表示黑城堡位于皇后区。
我们使用此e8c8
是因为它易于从数字来回转换。
还要注意,computer style chess notation
的动作需要en passant
。