我正在编写一种国际象棋游戏,我有一点问题。 在我的游戏中,棋盘上有一些棋子,棋盘分为100个棋子。
我想要做的是:当我点击一个Pawn时,它会选择它然后当我点击一个空的瓷砖时,所选的Pawn会移动到这个瓷砖。
当我点击一个Pawn时,没问题我选择它,但第二次点击会出现问题。我有一个错误:空指针异常。我不知道如何将选定的Pawn保留在内存中,然后在我再次点击时将其移动到新的坐标。
我使用带有touchDown()方法的手势检测器来监听是否点击了一个Actor。
这是我的代码,它是控制器。我只是把有趣的部分放在点击的棋子上:
Actor cibletile = tiles[(int) Cx][(int) Cy]; //the clicked tile
int tx = (int) cibletile.getX(); // pos x clicked tile
int ty = (int) cibletile.getY(); // pos y clicked tile
// if there is a Pawn on the tile
if (pieces[tx][ty] != null) {
System.out.println("there is a pawn here !");
Piece piece = pieces[tx][ty];
this.selectPiece(piece); //select the clicked pawn => this.plateau.PieceSelect
} // there are no problems with this if condition all is working
else{
this.movePiece(this.plateau.PieceSelect,tx,ty); //move the selected Pawn to new coordonates when I click a second time
} //the problem is here, I don't know how to move the Pawn after he is selected
我知道这不起作用,因为当我点击一个空格子时,IF条件不正常,而且.plateau.PieceSelect为Null。这就是为什么我有Null Pointer Exception。
我真的不知道如何选择Pawn然后在我第二次点击时移动它,也许是另一种方法?
如果能帮助我,我会很高兴的。我现在已经有一个星期了解这个问题。答案 0 :(得分:0)
这很简单。只需将else
条款转换为else if
,然后检查您是否选择了actor
。
else if(//Actor is selected i.e. some Actor object != null) {
this.movePiece(this.plateau.PieceSelect,tx,ty);
}