Search code examples
javaarraysfor-loopmultidimensional-arraytic-tac-toe

How can I check if the first row of a 2D array with no fixed dimension all have the same value?


I'm making a tic tac toe game in Java with a customizable dimension feature (user can choose to play 3x3, 4x4, 5x5, etc.) and was working on the logic regarding finding a winner. Currently I'm trying to figure out checking for wins horizontally.

I've had the idea to make a nested for-loop to check the 2d array that hosts the board, but am not sure how to execute this. The problem with this code:

for (int i = 0; i < dimension; i++) {
        if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != '-') {
                // you won!
        }
}

...Is that its logic is fixed for a 3x3 game, not for any other dimensions. I only know how to add values into 2d arrays, so how can I check if these values are equal? Thank you in advance.


Solution

  • I'm not sure about the rules for winning tic tac toe in higher dimensions, so let's say you have to fill the whole row/column to win.

    Divide the if in two parts: The check for the first chararacter and the comparisons. Then use a second for-loop for the comparisons, like this:

    for (int i = 0; i < dimension; i++) { // iterate rows
        // check for first character
        if (board[i][0] == '-') {    // if wrong character...
            continue;                // ... check next row
        }
    
        boolean won = true;
    
        for (int j = 0; j < dimension - 1; j++) { // iterate columns
            if (board[i][j] != board[i][j+1]) {   // if other character...
                won = false;                      // ...not winnable with this column and...
                break;                            // ...stop iteration of columns
            }
        }
    
        if (won) {
            // you won!
        }
    }
    

    If you win with less crosses 'X' in all dimensions, you would have to add a third loop to go through the possible start points or you could count the amount of crosses in the column and reset the number if there is an 'O'.