1

这里显示的是 ChessBoard 类,它创建了 Multi-D 数组块 - 表示棋盘 (8x8)。当一块移动时,我试图扫描棋盘以查看该块是否会移动穿过任何被占用的空间(如果是,则抛出非法移动异常)。下面附上我如何为每个 chessPiece 启动嵌套 for 循环。如何创建嵌套 for 循环来扫描点 [] [] 是否有空间空缺

public class ChessBoard {

private Piece spots[][];

public ChessBoard() {
    spots = new Piece[8][8];    
}

public void placePieceAt(Piece piece, ChessPosition position) 
{
    spot[position.getX()][position.getY()] = piece;
    piece.setPosition(position);
}
public abstract class Piece {

private ChessPlayer owner;
private ChessGame game;
protected ChessPosition position;



protected CPiece(ChessPlayer owner, ChessGame game, ChessPosition init_position) {
    this.owner = owner;
    this.game = game;
    this.position = null;

    game.getBoard().placePieceAt(this, init_position);
}

******here is where I was trying 
public void checkIfPositionOccupied(ChessPosition destination){
    ChessBoard[][] occupiedSpaces = new ChessBoard[8][8];
    for (int i = 0; i <8 ; i++){
        for(int j = 0; j<8; i++){


        }
    }

}
public void moveTo(ChessPosition destination) 



        throws IllegalMove
{
    // Replace with your code as necessary
    throw new IllegalMove(this, position, destination);
}

public char getMark() {
    return mark;
}

}

class Rook extends Piece {
public Rook(ChessPlayer owner, ChessGame game, ChessPosition init_position) {
    super(owner, game, init_position);
    if (owner == game.getPlayer1()) {
        mark = 'r';
    } else {
        mark = 'R';
    }
}   

public void moveTo(ChessPosition destination) throws IllegalMove
{
    if((position.getX() == destination.getX() && position.getY() != destination.getY()) || (position.getX() != destination.getX() && position.getY() == destination.getY())){
        setPosition(destination);
    } else {
        throw new IllegalMove(this, position, destination);
    }
}

}

4

2 回答 2

1

不知道你是不是在问这个,但好吧:

 ChessBoard[][] occupiedSpaces = new ChessBoard[8][8];
     for (int i = 0; i <8 ; i++){
     for(int j = 0; j<8; i++){
     if (spot[i][j]!=null)   
          //okay, occupied. 
         {
           // Make whatever you want here.
         }
     }
   }

创建一个 hasPiece() 方法,如果该位置被占用,则返回一个布尔值。

于 2013-04-24T16:17:25.283 回答
1

完全错了。。

如果Piece是类似的东西Rook看你的关系Rook is Piece。那你ChessBoard64 (8*8) Piece?你应该有单独的类Spots而不是用来Piece定义ChessSPots

另外根据你的问题can the board to see if the piece will move through any spaces

您不仅需要扫描DestinationPosition,还需要扫描当前位置的可能方式Piece。因此该Move方法应该特定于ConCrete Piece like Rook

您的checkIfPositionOccupied方法不需要循环。

public void checkIfPositionOccupied(ChessPosition destination){
    if(spot[destination.getX()][destination.getY()] !=null){
      /*Destination is Occupied*/
    }else{
      /*Destination is Not Occupied*/
    }

}
于 2013-04-24T16:31:17.660 回答