weberwe3
weberwe3

Reputation: 13

How to check for Vertical and diagonal Win in Java 2d array Tic Tac Toe

I'm writing a tic tac toe game in Java using a 2d array of JButtons. I need to be able to check for a winner of the game using For loops. I have been successful in checking for the winner when the winning set of X's or O's is contained in a row, but i'm not quite sure how to check in a column, diagonal, and reverse diagonal. I would use another method to check for the winner but im required to write this in a very specific manner.

        buttons = new JButton[3][3];

        public String checkWin() {
        String winString = null;

        for (int i = 0; i < buttons.length; i++){

            int xCount = 0;
            int oCount = 0;

            for(int j = 0; j < buttons[i].length; j++){
                if (buttons[i][j].getText().equals("X")){
                    xCount ++;
                }

                if (buttons[i][j].getText().equals("O")){
                    oCount ++;
                }

                if (xCount == buttons[i].length){
                    winString = "X wins!";
                }

                if (oCount == buttons[i].length){
                    winString = "O wins!";
                }
            }
        }

        return (winString);

    }

Upvotes: 0

Views: 4911

Answers (2)

user1296902
user1296902

Reputation: 11

vertically: replace buttons[i][j] with buttons[j][i] in your code. diagonal: Make a single loop that checks buttons[i][i]. reverse diagonal: make a single loop where you check buttons [buttons.size - i - 1] [i].

Upvotes: 1

Tony Ennis
Tony Ennis

Reputation: 12289

Start by drawing a board on paper, and noting the coordinates of vertical winning configurations.

Then repeat for the diagonal wins.

This should tell you what you need to know.

Upvotes: 1

Related Questions