【发布时间】:2022-01-05 13:07:36
【问题描述】:
我目前正在编写我的第一个国际象棋游戏,但我的棋子有一个小问题。我将在下面添加一些代码,但一般来说,我想检查玩家将某个棋子(在本例中为国王)移动到的棋子是否已被另一棋子占据,因为在这种情况下,另一棋子会要么被杀死(如果棋子属于其他玩家),要么移动是错误的(自己的棋子占据了瓷砖)。 如果您对如何完成有任何想法,我将不胜感激。 最好的问候
public abstract class Piece
{
protected int x;
protected int y;
protected Tile finalTile;
protected Type type;
protected boolean killed;
protected boolean white;
public Piece(boolean white, int x, int y)
{
this.setWhite(white);
this.x = x;
this.y = y;
this.finalTile = finalTile;
}
public boolean isWhite() {
return this.white;
}
public void setWhite (boolean white) {
this.white = white;
}
public boolean isKilled() {
return this.killed;
}
public void setKilled (boolean killed) {
this.killed = killed;
}
// which type of Piece is being used
public abstract Type getType();
//is the chosen move valid?
public abstract boolean canMovePiece (Chessboard chessboard, int finalX, int finalY);
//The validation of the move does not show in which direction the piece is being moved. To set
the piece at its new spot (tile), a determination of the direction is needed for the
// calculation of the new spot on the chessboard
public abstract void setNewPieceLocation();
}
public class King extends Piece
{
public King(boolean white, int x, int y)
{
super(white, x, y);
type = Type.KING;
}
public Type getType() {
return Type.KING;
}
@Override
public boolean canMovePiece(Chessboard chessboard, int finalX, int finalY) {
int x_diff = Math.abs(finalX - this.x);
int y_diff = Math.abs(finalY - this.y);
//the king can only move one tile per round. The direction does not matter. Therefore, the
movements can be either one on the x-axis, the y-axis or one on both.
if ( x_diff == 1 && y_diff == 0 || x_diff == 0 && y_diff == 1 || x_diff == 1 && y_diff ==1) {
return true;
}
}
@Override
public void setNewPieceLocation() {
int finalX = this.x;
int finalY = this.y;
}
}
【问题讨论】:
-
顺便说一句:为什么要把
getType()抽象化?只需将Type传递给超级构造函数,并将其存储在其中的一个字段中。 -
“如果你有任何想法怎么做”你需要看看
chessboard,它似乎没有被使用,你也没有显示它的定义。 -
另外一点:国王的
canMovePiece条件可以简化为Math.max(x_diff, y_diff) <= 1。 -
这是一个想法。创建一个包含逻辑棋盘的 8 x 8 int 数组。黑兵是 1,马是 2,象是 3,车是 5,后是 10,国王是 20。白棋有相似的负值。在 int 数组上移动,然后使用 int 数组绘制棋盘的状态。
-
嗨@Alice333!如果答案已解决您的问题,请单击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。