I'm trying to check if a player won diagonally (going from the top left to bottom right). The top left portion of the grid is (0,0). I'm not checking if a player won based on the last tile placed. Instead, I'm checking all the spots on the grid to check if someone won diagonally. This is what I came up with.
public class TestWin {
private int count_piece;
private char[][] board;
public void myBoard(char[][] x){
this.board = x;
//vertWin();
//horizontalWin();
diagDownWin();
}
public boolean diagDownWin(){
for(int row = 0; row < board.length; row++){
for(int col = 0; col < board[0].length; col++){
if(board[row][col] == board[row+1][col+1]){
count_piece++;
if(count_piece >= 4){
System.out.println("You win");
return true;
}
}else{
count_piece = 0;
}
}
}
System.out.println("No win");
return false;
}
public static void main(String[] args) {
char[][] myGrid = {
{ 'X', 'O', 'O', 'O'},
{ 'X', 'X', 'O', 'O'},
{ 'O', 'X', 'X', 'O'},
{ 'O', 'O', 'X', 'X'},
{ 'O', 'O', 'O', 'O'}
};
TestWin m1 = new TestWin();
m1.myBoard(myGrid);
}
}
Because there are two ways to win from a diagonal-- I'm checking moving from top-left to bottom-right. I want to go down one and over one (row + 1 and col +1), but I run into an array out of bounds error on line where I write:
if(board[row][col] == board[row+1][col+1])
I assume this happens because when I reach the last row and last col I'm adding one which is greater the board.length and board[0].length
What can I do to prevent the error?