Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tic Tac Toe
- public class TicTacToe
- {
- //copy over your constructor from the Tic Tac Toe Board activity in the previous lesson!
- private int turn;
- private String [][] chess = new String [3][3];
- public TicTacToe()
- {
- for(int i = 0; i < 3; i++)
- {
- for(int a = 0; a < 3; a++)
- {
- chess[i][a] = "-";
- }
- }
- }
- //this method returns the current turn
- public int getTurn()
- {
- return turn;
- }
- /*This method prints out the board array on to the console
- */
- public void printBoard()
- {
- int a = 0;
- System.out.println(" " + "0" + " " + "1" + " " + "2");
- for(int row = 0; row < chess.length; row++)
- {
- System.out.print(a + " ");
- for(int col = 0; col < chess[row].length; col++)
- {
- System.out.print(chess[row][col] + " ");
- }
- a++;
- System.out.println("");
- }
- }
- //This method returns true if space row, col is a valid space
- public boolean pickLocation(int row, int col)
- {
- if(chess[row][col].equals("-"))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- //This method places an X or O at location row,col based on the int turn
- public void takeTurn(int row, int col)
- {
- if(turn % 2 == 0)
- {
- chess[row][col] = "X";
- }
- else if(turn % 2 == 1)
- {
- chess[row][col] = "O";
- }
- turn++;
- }
- //This method returns a boolean that returns true if a row has three X or O's in a row
- public boolean checkRow()
- {
- boolean a = false;
- for(int row = 0; row < chess.length; row++)
- {
- if(chess[row][0].equals(chess[row][1]) && chess[row][0].equals(chess[row][2]))
- {
- a = true;
- }
- }
- return a;
- }
- //This method returns a boolean that returns true if a col has three X or O's
- public boolean checkCol()
- {
- boolean a = false;
- for(int col = 0; col < chess.length; col++)
- {
- if(chess[0][col].equals(chess[1][col]) && chess[0][col].equals(chess[2][col]))
- {
- a = true;
- }
- }
- return a;
- }
- //This method returns a boolean that returns true if either diagonal has three X or O's
- public boolean checkDiag()
- {
- boolean a = false;
- if(chess[1][1].equals(chess[0][0]) && chess[1][1].equals(chess[2][2]))
- {
- a = true;
- }
- else if(chess[1][1].equals(chess[0][2]) && chess[1][1].equals(chess[2][0]))
- {
- a = true;
- }
- return a;
- }
- //This method returns a boolean that checks if someone has won the game
- public boolean checkWin()
- {
- if(checkRow())
- {
- return true;
- }
- else if(checkCol())
- {
- return true;
- }
- else if(checkDiag())
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement