所以我对Java语言还不熟悉,所以我必须忘记这里的某些东西。因此,对于家庭作业,我必须用Java创建一个国际象棋游戏。截至目前,我已经为一个" Pawn"创建了一个类。另一个名为" GameState"的类,其中包含游戏的棋盘。 Pawn类有一个名为move()的方法,它将棋盘上的点的x和y坐标移动到当前的gamestate对象,而move()函数会将pawn移动到该位置上。板。 pawn类是从名为" Piece"的抽象类扩展而来的,我制作的所有其他特定的类将继承自这个类。
我的问题是move()方法没有正确修改GameState类中的板。
以下是pawn类的move()方法的相关代码片段:
public GameState move(GameState state, int xDest, int yDest) {
//Make sure that the destination coordinates are not outside of the board
if (xDest < 0 || yDest < 0 || xDest >= state.getBoardCols() || yDest >= state.getBoardRows())
return null;
/*
* A black piece moves forward on the downward pointing y
* axis, and a a white piece moves up. Thus, we assign a
* +1 to the variable if the piece is white, and -1 if the
* piece is black.
*/
int dir = (color.equals("black")) ? -1 : 1;
//In the case that the pawn is moving forward 2 spaces
if (firstMove == true && xCurr == xDest && yDest == yCurr + dir * 2) {
if (state.insertPiece(xDest, yDest, this)) {
firstMove = false;
//Null the old coordinates the Pawn was at
state.nullCoordinates(xCurr, yCurr);
return state;
} else
return null;
}
所以,insertPiece()方法实际上是将棋子插入棋盘上的x和y坐标。我使用了eclipse调试器,当程序运行insertPiece()方法时,&#34;状态&#34;对象确实将pawn插入正确的x和y坐标。现在,我有一个运行此移动方法的单元测试函数,如下所示:
state = pawnToTest.move(state, 4, 1 + dir * 2);
assertEquals(false, pawnToTest.firstMove());
assertEquals(pawnToTest, state.getPiece(4, 1 + dir * 2));
assertEquals(null, state.getPiece(4, 1));
现在,在这种情况下,我最初在棋盘上放置了一个位于x = 4,y = 1的棋子(其索引为[1] [4],但无论如何)。所以,这里的第一个move()调用会将它向前移动到x = 4,y = 3。现在,我已经验证了调试器在INSING pawnToTest.move()调用中,x = 4,y = 3的板确实包含了pawn。但是,当程序退出该方法的控件时,pawn不再位于该位置,因此第二个断言等于失败。为什么董事会没有得到适当的修改?
编辑:nvm,我发现了这个错误,原来我没有正确更新pawn的位置,愚蠢的我:P