Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- A 3 x 3 tic-tac-toe board.
- */
- public class TicTacToe
- {
- /**
- Constructs an empty board.
- */
- public TicTacToe()
- {
- board = new String[ROWS][COLUMNS];
- // Fill with spaces
- for (int i = 0; i < ROWS; i++)
- for (int j = 0; j < COLUMNS; j++)
- board[i][j] = " ";
- }
- /**
- Sets a field in the board. The field must be unoccupied.
- @param i the row index
- @param j the column index
- @param player the player ("x" or "o")
- */
- public void set(int i, int j, String player)
- {
- if (board[i][j].equals(" "))
- board[i][j] = player;
- }
- /**
- Creates a string representation of the board, such as
- |x o|
- | x |
- | o|
- @return the string representation
- */
- public String toString()
- {
- String r = "";
- for (int i = 0; i < ROWS; i++)
- {
- r = r + "|";
- for (int j = 0; j < COLUMNS; j++)
- r = r + board[i][j];
- r = r + "|\n";
- }
- return r;
- }
- public String getWinner()
- {
- int a = 0;
- int b = 0;
- String win = "";
- for (int i = 0; i < 3; i++)
- {
- for (int j = 0; j < 3; j++)
- {
- if (board[i][j].equals(" "))
- return null;
- else if (board[i][j].equals("x"))
- a++;
- else if (board[i][j].equals("o"))
- b++;
- }
- }
- if (a == 3)
- {
- win = "Player x is the winner.";
- }
- else if (b == 3)
- {
- win = "Player o is the winner.";
- }
- return win;
- }
- private String[][] board;
- private static final int ROWS = 3;
- private static final int COLUMNS = 3;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement