ComputerMove.java
You will get a null pointer exception in tic tac toe game, for the java code which we posted earlier.So these changes has to be made in the code.
While the user chose the first move other than the centre position, the Nullpointer Exception comes.
private Matrix<Character> generateFirstCompMove() throws IllegalAccessException {
int row = 1;
int col = 1;
if(matrix.isElementExist(row, col)) {
Random r = new Random();
row = r.nextInt(3);
col = r.nextInt(3);
col = (row == 1 && col == 1) ? col + 1 : col;
matrix.add(row, col, TikTocToe.COMP_MOVE);
}else {
matrix.add(1, 1, TikTocToe.COMP_MOVE);
}
return matrix;
}
TikTocToe.java
Checking the winner bug fixed. replace the following code snippet in Tic Tac Toe java class.
@SuppressWarnings("unused")
private char findWinner() {
Object[][] newMatrix = matrix.getMatrix();
if (moveCount < 5 || moveCount > MAX_MOVE) {
return Matrix.EMPTY_DATA;
}
if (null != matrix.getValue(0, 0)
&& (TikTocToe.USER_MOVE == matrix.getValue(0, 0) || TikTocToe.COMP_MOVE == matrix.getValue(0, 0))) {
winner = (Character) matrix.getValue(0, 0);
if ((null != matrix.getValue(0, 1) && winner.equals(newMatrix[0][1]))
&& (null != matrix.getValue(0, 2) && winner.equals(newMatrix[0][2]))) {
return winner;
} else if ((null != matrix.getValue(0, 1) && winner.equals(newMatrix[1][0]))
&& (null != matrix.getValue(2, 0) && winner.equals(newMatrix[2][0]))) {
return winner;
} else if ((null != matrix.getValue(1, 1) && winner.equals(newMatrix[1][1]))
&& (null != matrix.getValue(2, 2) && winner.equals(newMatrix[2][2]))) {
return winner;
}
}
if (null != matrix.getValue(1, 1)
&& (TikTocToe.USER_MOVE == matrix.getValue(1, 1) || TikTocToe.COMP_MOVE == matrix.getValue(1, 1))) {
winner = (Character) newMatrix[1][1];
if ((null != matrix.getValue(1, 0) && winner.equals(newMatrix[1][0]))
&& (null != matrix.getValue(1, 2) && winner.equals(newMatrix[1][2]))) {
return winner;
} else if ((null != matrix.getValue(0, 0) && winner.equals(newMatrix[0][0]))
&& (null != matrix.getValue(1, 2) && winner.equals(newMatrix[1][2]))) {
return winner;
} else if ((null != matrix.getValue(0, 2) && winner.equals(newMatrix[0][2]))
&& (null != matrix.getValue(2, 0) && winner.equals(newMatrix[2][0]))) {
return winner;
}
}
if (null != matrix.getValue(2, 2)
&& (TikTocToe.USER_MOVE == matrix.getValue(2, 2) || TikTocToe.COMP_MOVE == matrix.getValue(2, 2))) {
winner = (Character) newMatrix[2][2];
if ((null != matrix.getValue(2, 0) && winner.equals(newMatrix[2][0]))
&& (null != matrix.getValue(2, 1) && winner.equals(newMatrix[2][1]))) {
return winner;
} else if ((null != matrix.getValue(0, 2) && winner.equals(newMatrix[0][2]))
&& (null != matrix.getValue(1, 2) && winner.equals(newMatrix[1][2]))) {
return winner;
}
}
return Matrix.EMPTY_DATA;
}
No comments:
Post a Comment
Your feedback may help others !!!