Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TicTacToeTester
- {
- public static void main(String[] args)
- {
- //This is to help you test your methods. Feel free to add code at the end to check
- //to see if your checkWin method works!
- TicTacToe game = new TicTacToe();
- System.out.println("Initial Game Board:");
- game.printBoard();
- //Prints the first row of turns taken
- for(int row = 0; row < 3; row++)
- {
- if(game.pickLocation(0, row))
- {
- game.takeTurn(0, row);
- }
- }
- System.out.println("\nAfter three turns:");
- game.printBoard();
- }
- }
- public class TicTacToe
- {
- //copy over your constructor from the Tic Tac Toe Board activity in the previous lesson!
- private int turn;
- private String[][] t = new String[3][3];
- public TicTacToe() {
- for (int x = 0; x < t.length; x++) {
- String[] empty = {"-", "-", "-"};
- t[x] = empty;
- }
- }
- //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()
- {
- System.out.println(" 0 1 2");
- for (int x = 0; x < t.length; x++) {
- System.out.print(x + " ");
- for (int y = 0; y < t[x].length; y++) {
- System.out.print(t[x][y] + " ");
- }
- System.out.println();
- }
- }
- //This method returns true if space row, col is a valid space
- public boolean pickLocation(int row, int col)
- {
- if (t[row][col].equals("-")) return true;
- 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 (pickLocation(row, col) && turn%2 == 0) {
- t[row][col] = "X";
- turn++;
- }
- else if (pickLocation(row, col) && turn%2 != 0) {
- t[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()
- {
- for (int x = 0; x < t[x].length - 1; x++) {
- if (t[x][0].equals(t[x][1]) && t[x][0].equals(t[x][2])) return true;
- }
- return false;
- }
- //This method returns a boolean that returns true if a col has three X or O's
- public boolean checkCol()
- {
- for (int x = 0; x < t.length; x++)
- {
- if (t[0][x].equals(t[1][x]) && t[0][x].equals(t[2][x])) return true;
- }
- return false;
- }
- //This method returns a boolean that returns true if either diagonal has three X or O's
- public boolean checkDiag()
- {
- if (t[0][0].equals(t[1][1]) && t[0][0].equals(t[2][2])) return true;
- else if (t[0][2].equals(t[1][1]) && t[0][2].equals(t[2][0])) return true;
- return false;
- }
- //This method returns a boolean that checks if someone has won the game
- public boolean checkWin()
- {
- if (checkRow() || checkCol() || checkDiag()) return true;
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement