ntal win, one to solve for a vertical win, and one to solve for a diagonal win. A win occurs when three symbols for a player are in a line (horizontal, vertical, or diagonal). Create four 2-d (3x3) arrays, one with a horizontal win for O, one with a vertical win for X, one with a diagonal win for O, and the last being a cat game (no player wins). It is tempting to populate the arrays with a ‘X’ and ‘O’ characters but consider representing these values with int values instead which makes calculating a win much easier. Consider a zero value as an e
Write a JAVA program that handles a 2-dimensional array representing a 3x3 tic-tac-toe board. In the game, players take turns writing an X or an O and trying to get three in a row. Write three methods, one to solve for a horizontal win, one to solve for a vertical win, and one to solve for a diagonal win. A win occurs when three symbols for a player are in a line (horizontal, vertical, or diagonal).
Create four 2-d (3x3) arrays, one with a horizontal win for O, one with a vertical win for X, one with a diagonal win for O, and the last being a cat game (no player wins). It is tempting to populate the arrays with a ‘X’ and ‘O’ characters but consider representing these values with int values instead which makes calculating a win much easier. Consider a zero value as an empty cell. You do not have to write code to input the values, just define the four arrays using initializer lists (see example below).
For example: an array with { {1, 0, -1}, {1, -1, 0}, {1, -1, 0} } has a vertical win in the first column for X, where 1 represents an ‘X,’ a -1 represents an ‘O,’ and 0 represents an empty cell.
Write the main() method to call each solver for a board until one returns a win; specify which player won and the orientation (horizontal, vertical, diagonal) of the win. If none return a win, output that the board is a cat game.
Make the code as minimal as possible.
In this program, we define the three possible states of a cell on the board (EMPTY, X, O) as constants. Then we define the checkForWin() method, which takes a board as a parameter and returns the value of the winning player or 0 if there is no winner. This method checks for horizontal, vertical, and diagonal wins by iterating over the rows, columns, and diagonal lines of the board.
In the main method, we define four boards with different winning configurations and call checkForWin() on each of them until one returns a non-zero value. If a win is detected, we print out the winning player and the orientation of the win. Otherwise, we print out that it's a cat game.
JAVA program that handles a 2-dimensional array representing a 3x3 tic-tac-toe board:
Step by step
Solved in 5 steps with 5 images