我正在使用 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 类的实际工作 谢谢
最佳答案
正如我在评论中提到的,我认为您的 OOP 结构可能有点过于简单化。我建议您考虑创建:
- enum ChessColor:白色、黑色。最好使用枚举而不是字符串,因为后者容易出错并且不允许方法参数和其他编译时类型检查
- 抽象类 AbstractChessPiece:棋子继承自的抽象类。它有一个 ChessColor 字段,以及所有棋子都需要的任何其他抽象方法。实际上可能并不需要这个。
- enum ChessPiece extends AbstractChessPiece:不妨对其进行枚举,因为它们将是常量。有几种方法包括
public boolean moveAllowed(ChessSquare square)
如果该棋子允许移动,则返回 true。 - 类 ChessSquare:它知道自己的行列和文件(int 字段)以及 getter 和 setter,并且有一个 ChessPiece 字段,如果方格为空,则该字段为 null,否则保存一个 ChessPiece。
- 类 ChessBoard:保存 ChessSquares 网格
- class ChessPlayer:代表两个玩家之一。它有一个 ChessColor 字段,一个
List<ChessPiece> capturedPieces
,下棋的方法,提议平局的方法,投降的方法…… - 类 ChessGame:启动一切并控制游戏流程的程序。进行该移动的玩家将向游戏对象提出一个移动,该游戏对象将检查有效性,如果有效,则进行该移动并检查该移动的游戏结果,包括捕获、检查、将死……
关于java - 在国际象棋游戏中,棋子应该移动还是棋盘应该移动棋子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58979763/