[Two-dimensional array] Determine whether the tic-tac-toe player wins

Hits: 0

Topic description

Given a [two-dimensional array] board, representing the chessboard, where the element is 1 represents the current player’s piece, 0 means no piece, and -1 represents the opponent’s piece. When a player has consecutive rows in the horizontal and vertical directions and wins (and the tic-tac-toe rules), it returns whether the current player wins or not.

Test example:

import java.util.*;

public  classBo  _  _
     _  _  _ _ _ _  _ _ 
        _ _ _ _ _ _ _ _ _ _ + board[ 2 ][ 2 ] == 3 || board[ 0 ][ 2 ] + board[ 1 ][ 1 ] + board[ 2 ][ 0 ] == 3 ) {
             return  true ;
        }
        for ( int i = 0 ; i < 3 ;i++) { //A loop is used to determine whether each row and column are connected by the player 
            if (board[i][ 0 ] + board[i][ 1 ] + board[i ][ 2 ] == 3 || board[ 0 ][i] + board[ 1 ][i] + board[ 2 ][i] == 3 ) {
                 return  true ;
            }
        }
        return  false ;
    }
}

return: true

topic analysis

The rules of the tic-tac-toe game are to judge whether the pieces on the row, column and diagonal are all the same

According to the given [two-dimensional array] , since the rows and columns of tic-tac-toe are equal, and the current player’s piece is 1, it is only necessary to calculate the sum of a row or a column as the number of rows in the two-dimensional array, and then judge the two diagonals and, if one of the conditions is met, the player wins.

When calculating, pay attention to counting each row and column each time, and set the sum to 0 when the sum of the diagonals is set, otherwise it will be disturbed by the last calculation result and cause a program error.

code show as below:

import java.util.*;

public  classBo  _  _
     _  _  _ _ _ _  _ _ 
        _ _ _ _ _ _ _ _ _ _ + board[ 2 ][ 2 ] == 3 || board[ 0 ][ 2 ] + board[ 1 ][ 1 ] + board[ 2 ][ 0 ] == 3 ) {
             return  true ;
        }
        for ( int i = 0 ; i < 3 ;i++) { //A loop is used to determine whether each row and column are connected by the player 
            if (board[i][ 0 ] + board[i][ 1 ] + board[i ][ 2 ] == 3 || board[ 0 ][i] + board[ 1 ][i] + board[ 2 ][i] == 3 ) {
                 return  true ;
            }
        }
        return  false ;
    }
}

You may also like...

Leave a Reply

Your email address will not be published.