将对象添加到来自不同类的ArrayList(Chess in Java)

时间:2017-09-15 01:45:40

标签: java arraylist

我正在用Java编写国际象棋程序。在我的Board类中,它处理了Piece的所有动作,我创建了一个名为movePiece的函数,它将一个片段移动到一个特定的位置,并捕获敌人块(如果它存在于该位置)。 movePiece的功能如下所示:

public void movePiece(int x, int y, Piece pieceToMove) {

    if(pieceToMove.canMove(board, this.x, this.y, x, y)){ //Check if the piece canMove to the location

        if(board[x][y] == null) { //Check if the location is empty

            removePiece(this.x, this.y);
            board[x][y] = pieceToMove;

        } else {

            if(board[x][y].getColor() != pieceToMove.getColor()) { //Check if the location is occupied by an enemy

                removePiece(this.x, this.y);
                board[x][y] = pieceToMove;  

            } else {
                System.out.println("Invalid Move");
            }
        }

    } else {

        System.out.println("Invalid Move");

    }
}

它工作正常,但我想跟踪ArrayList中捕获的敌人Piece。因此,我在Player类中创建了一个ArrayList captureList以跟踪它,并尝试添加

        if(board[x][y].getColor() != pieceToMove.getColor()) { //Check if the location is occupied by an enemy

            addCapturedPiece(board[x][y], capturedList); <--- THIS LINE
            removePiece(this.x, this.y);
            board[x][y] = pieceToMove;  

        }

但是这没有用,因为captureList在Player类中。有没有办法让这项工作顺利进行?

1 个答案:

答案 0 :(得分:1)

您可以在Player类中设置HarshBuilder方法。然后,正在移动当前作品的玩家可以调用该方法并将该作品添加到他/她的特定/// Note that this factory will be consumed upon initialization. #[derive(Debug, Default)] pub struct HarshBuilder { salt: Option<Vec<u8>>, // ...ommitted for brevity } impl HarshBuilder { /// Creates a new `HarshBuilder` instance. pub fn new() -> HarshBuilder { HarshBuilder { salt: None, // ...ommited for brevity } } /// Note that this salt will be converted into a `[u8]` before use, meaning /// that multi-byte utf8 character values should be avoided. pub fn salt<T: Into<Vec<u8>>>(mut self, salt: T) -> HarshBuilder { self.salt = Some(salt.into()); self } 。例如:

addCapturedPiece