这里显示的是ChessBoard类,它创建了代表棋盘(8x8)的Multi-D阵列片段。当一块物在移动时,我试图扫描板子以查看该块是否将移动通过任何被占用的空间(如果是这样则抛出非法移动异常)。下面是我为每个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);
}
}
}
答案 0 :(得分:0)
不确定你是否在问这个问题,但是很好:
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()方法,如果该位置被占用,则返回一个布尔值。
答案 1 :(得分:0)
完全错了..
如果Piece
类似于Rook
,请查看您的关系Rook is Piece
。那么您的ChessBoard
如何64 (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*/
}
}