我正在开发一种跳棋游戏,如果您想了解更多信息,可以在这里查看。 http://minnie.tuhs.org/I2P/Assessment/assig2.html
当我进行测试以查看播放器是否能够从当前位置到达网格上的某个正方形(即+1 + 1,+ 1 -1 .etc)时,出现java.lang.ArrayIndexOutOfBoundsException错误。
这是我用来移动的代码。
public static String makeMove(String move, int playerNumber)
{
// variables to contain the starting and destination coordinates, subtracting 1 to match array size
int colStart = move.charAt(1) - FIRSTCOLREF - 1;
int rowStart = move.charAt(0) - FIRSTROWREF - 1;
int colEnd = move.charAt(4) - FIRSTCOLREF - 1;
int rowEnd = move.charAt(3) - FIRSTROWREF - 1;
// variable to contain which player is which
char player, enemy;
if (playerNumber==1)
{
player= WHITEPIECE;
enemy= BLACKPIECE;
}
else
{
player= BLACKPIECE;
enemy= WHITEPIECE;
}
// check that the starting square contains a player piece
if (grid [ colStart ] [ rowStart ] == player)
{
// check that the player is making a diagonal move
if (grid [ colEnd ] [ rowEnd ] == grid [ (colStart++) ] [ (rowEnd++) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart--) ] [ (rowEnd++) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart++) ] [ (rowEnd--) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart--) ] [ (rowEnd--) ])
{
// check that the destination square is free
if (grid [ colEnd ] [ rowEnd ] == BLANK)
{
grid [ colStart ] [ rowStart ] = BLANK;
grid [ colEnd ] [ rowEnd ] = player;
}
}
// check if player is jumping over a piece
else if (grid [ colEnd ] [ rowEnd ] == grid [ (colStart+2) ] [ (rowEnd+2) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart-2) ] [ (rowEnd+2) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart+2) ] [ (rowEnd-2) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart-2) ] [ (rowEnd-2) ])
{
// check that the piece in between contains an enemy
if ((grid [ (colStart++) ] [ (rowEnd++) ] == enemy ) &&
(grid [ (colStart--) ] [ (rowEnd++) ] == enemy ) &&
(grid [ (colStart++) ] [ (rowEnd--) ] == enemy ) &&
(grid [ (colStart--) ] [ (rowEnd--) ] == enemy ))
{
// check that the destination is free
if (grid [ colEnd ] [ rowEnd ] == BLANK)
{
grid [ colStart ] [ rowStart ] = BLANK;
grid [ colEnd ] [ rowEnd ] = player;
}
}
}
}
我不确定如何防止错误发生,您对此有何建议?
最佳答案
首先想到的是您在(colstart++)
语句条件中间使用诸如if
之类的后递增表达式。当然,在某些情况下这可能有用,但我不认为您就是其中之一。
使用(colstart+1)
代替;它不会更改colstart
变量本身的值,而这正是您真正想要的。
更详细地,假设colstart
为4:
System.out.println(colstart); // prints 4
System.out.println(colstart++); // prints 4
System.out.println(colstart); // prints 5
相比于:
System.out.println(colstart); // prints 4
System.out.println(colstart+1); // prints 5
System.out.println(colstart); // prints 4