Need better logic for TicTacToe

So, what you have (essentially) is a 2D matrix (okay, it’s a virtual one, but that makes it simpler to think about)…

What you need is a means by which you can search three cells of this matrix, starting at a given row and column.

So, given a starting point, you also need to supply information about which direction you want to search in (as sometimes, you want to search backwards), maybe something like…

public boolean matrixWin(int row, int col, int rowDelta, int colDelta) {

    boolean win = false;
    String value = button[(row * 3) + col].getText();
    if (!value.isEmpty()) {
        win = true;
        for (int count = 1; count < 3; count++) {
            row += rowDelta;
            col += colDelta;
            String test = button[(row * 3) + col].getText();
            if (test.isEmpty() || !test.equals(value)) {
                win = false;
                break;
            }
        }
    }
    return win;

}

This basically gets the value of the first cell, if it’s not empty, it begins to move through the matrix, based on the delta values, and checks each other cell to see if it’s not empty or if it matches the value of the first cell.

Okay that’s cool, but I’m way to lazy to try and set up EVERY permutation I might like to check for, so instead, I’d make some helper methods…

Basically, you want to check the three rows for a horizontal win, the three columns for a vertical win and the left or right diagonals…

public boolean horizontalWin(int row) {
    return matrixWin(row, 0, 0, 1);
}

public boolean verticalWin(int col) {
    return matrixWin(0, col, 1, 0);
}

public boolean leftDiagonalWin() {
    return matrixWin(0, 0, 1, 1);
}

public boolean rightDiagonalWin() {
    return matrixWin(0, 2, 1, -1);
}

But even then, unless I want to know which row/col/diagonal ACTUALLY won, I’d make it even easier…

public boolean horizontalWins() {

    int row = 0;
    boolean win = false;
    do {
        win = horizontalWin(row);
        row++;
    } while (row < 3 && !win);

    return win;

}

public boolean verticalWins() {

    int col = 0;
    boolean win = false;
    do {
        win = verticalWin(col);
        col++;
    } while (col < 3 && !win);

    return win;

}

Then you could get down to…

public boolean didWin() {

    return horizontalWins() || verticalWins() || leftDiagonalWin() || rightDiagonalWin();

}

Yeah, one method call, but you still have the power to determine exactly “how”

Leave a Comment