问题
So I keep running into a problem with my code for checking if there is a connect 4 vertically. Preface to my code: the board has 6 rows and 7 columns, the variable player1 holds the value of the character being used as a chip and playerID just holds the value of whoever gets the connect 4.
public int verticalWin() {
int playerID = 0;
for (int x = 0; x < board[x].length; x++) {
int count = 1;
for (int y = board.length-2; y >= 0; y--) {
if (board[y][x] == board[y+1][x]) {
count++;
if (count == 4) {
if (board[y][x] == player1) {
playerID = 1;
} else {
playerID = 2;
}
}
} else {
count = 1;
}
}
}
return playerID;
}
The problem I keep running into is that an exception java.lang.ArrayIndexOutOfBoundsException: 6 keeps happening and I think it's in the first line, but I can't seem to find the problem.
回答1:
Some cleaner code
boolean isWinnerOnColumn(int playerID, int column) {
int count = 0;
for (int row = 0; row < 6; row++) {
count = (board[row][column] == playerID) ? (count + 1) : 0;
if (count == 4){
return true;
}
}
return false;
}
public int verticalWin() {
for (int column = 0; column < 7; column++) {
if (isWinnerOnColumn(1, column) {
return 1;
}
if (isWinnerOnColumn(2, column) {
return 2;
}
}
return 0; // no winner
}
来源:https://stackoverflow.com/questions/40810891/exception-being-thrown-for-connect-4-algorithm