Я реализую шахматный движок, поэтому я создал следующую функцию для проверки возможных ходов (без фактического создания) для части AI двигателя.Не могу решить nullPointerException
Функция принимает в качестве параметров сторону (черный или белый), объект типа платы, содержащий арраилист всех частей шахматной доски, а также некоторую другую информацию, а также исходные и целевые квадраты перемещения в виде строк ,
Моя проблема заключается в том, что ходы не «сделаны» должным образом. Что я имею в виду, так это то, что в объекте платы, который возвращается после завершения этой функции, куски не имеют измененной строки или столбца, хотя если функция меняет их . Совет меняется только в том случае, если кусок удаляется из него.
public Board doTestMove(int side,Board b, String srcSq, String destSq) {
//check source square notation for validity
if (checkSqValidity(srcSq)) {
//check destination square notation for validity
if (checkSqValidity(destSq)) {
//find the piece based on the source square notation.
Piece piece =new Piece(b.notationToPiece(srcSq));
if(piece==null){
System.out.println("The piece is null");
}
//make sure the piece is owned by the player
if (piece.getColor()==side) {
//get all movements that are allowed for the selected piece
ArrayList<ArrayList<Integer>> legalMoves=new ArrayList<ArrayList<Integer>>();
legalMoves = possiblePieceMoves(piece, false);
//array coordinates for new destination
Index newLoc = new Index(b.notationToIndex(destSq).getX(),b.notationToIndex(destSq).getY());
//find out if destination location is included in the legal moves list
ArrayList<Integer> x = legalMoves.get(0); //list of row numbers
ArrayList<Integer> y = legalMoves.get(1); //list of column numbers
ListIterator<Integer> xList = x.listIterator(); //row iterator
ListIterator<Integer> yList = y.listIterator(); //column iterator
int xL, yL;
while (xList.hasNext() && yList.hasNext()) { //while lists have coordinates
//listiterator next() method doesn't work inside if statement -> assign to variables
xL = xList.next();
yL = yList.next();
if (newLoc.getX()==xL && newLoc.getY()==yL) { //legal move
b.removePiece(newLoc.getX(), newLoc.getY()); //remove captured piece from the board
piece.setRow(newLoc.getX()); //change piece row
piece.setCol(newLoc.getY()); //change piece column
b.updateGameState(); //populate the board with new location of pieces.
//place source and destination square to history of moves
if (side==0) { //if white
getHistoryOfMoves().addWhiteMove(srcSq, destSq); //add white piece move to history
} else if (side==1) { //if black
getHistoryOfMoves().addBlackMove(srcSq, destSq); //add black piece move to history
}
//promote pawns to queens if they reach enemy's end
b.promotePawnsToQueen(side);
return new Board(b); //move successful
}
}
}
} else {
System.out.println("Not a valid destination square. ");
}
} else {
System.out.println("Not a valid source notation.");
}
return null;
}
Как вы можете видеть объект часть определяется следующим образом:
Piece piece =new Piece(b.notationToPiece(srcSq));
я пришел к выводу, что я должен изменить его на:
Piece piece =b.notationToPiece(srcSq);
Подумав, что единственное, что происходит правильно, это удаление куска. Таким образом, происходит смена чего-то непосредственно на доске, которая должна быть возвращена.
Поэтому я решил, что изменения, которые выполняет функция, должны влиять на часть, которая является частью массива объекта b, а не какой-то новый объект.
Однако, когда я пытаюсь сделать это я получаю сообщение об ошибке:
java.lang.NullPointerException
At the line:
if (piece.getColor()==side) {
Это довольно странно, так как эта функция для тестирования ходов почти идентична функции я использую для создания движения (что хорошо работает), который является следующим:
public boolean doMove(Player player, String srcSq, String destSq) {
//check source square notation for validity
if (checkSqValidity(srcSq)) {
//check destination square notation for validity
if (checkSqValidity(destSq)) {
//find the piece based on the source square notation.
Piece piece = getBoard().notationToPiece(srcSq);
//make sure the piece is owned by the player
if (piece.getColor()==player.getSide()) {
//get all movements that are allowed for the selected piece
ArrayList<ArrayList<Integer>> legalMoves = possiblePieceMoves(piece, false);
//array coordinates for new destination
Index newLoc = getBoard().notationToIndex(destSq);
//find out if destination location is included in the legal moves list
ArrayList<Integer> x = legalMoves.get(0); //list of row numbers
ArrayList<Integer> y = legalMoves.get(1); //list of column numbers
ListIterator<Integer> xList = x.listIterator(); //row iterator
ListIterator<Integer> yList = y.listIterator(); //column iterator
int xL, yL;
while (xList.hasNext() && yList.hasNext()) { //while lists have coordinates
xL = xList.next();
yL = yList.next();
if (newLoc.getX()==xL && newLoc.getY()==yL) { //legal move
getBoard().removePiece(newLoc.getX(), newLoc.getY()); //remove captured piece from the board
piece.setRow(newLoc.getX()); //change piece row
piece.setCol(newLoc.getY()); //change piece column
//place source and destination square to history of moves
if (player.getSide()==0) { //if white
getHistoryOfMoves().addWhiteMove(srcSq, destSq); //add white piece move to history
} else if (player.getSide()==1) { //if black
getHistoryOfMoves().addBlackMove(srcSq, destSq); //add black piece move to history
}
//promote pawns to queens if they reach enemy's end
getBoard().promotePawnsToQueen(player.getSide());
return true; //move successful
}
}
}
} else {
System.out.println("Not a valid destination square. ");
}
} else {
System.out.println("Not a valid source notation.");
}
return false; //move failed, not own piece
}
Я не могу найти причину проблемы.
'«Я не могу найти источник проблемы.»' - в этот момент, я боюсь, что только вы можете ** ** найти источник, так как только у вас есть исполняемый код. Используйте отладчик и найдите нулевую переменную, которая вызывает выброс NPE, а затем отследите, чтобы узнать, почему. –