Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Omar Natour
- * 10/17/2016
- * Csc-220 Data Structures
- * Hw4 Tic Tac Toe
- * Create a tic tac toe object
- * Ojnatour0001@student.stcc.edu
- */
- package tictactoe;
- public class TicTacToe {
- private char[][] caBoard = new char[3][3];
- private int turns;
- public TicTacToe() {
- for (int i = 0; i < caBoard.length; i++) {
- for (int j = 0; j < caBoard[i].length; j++) {
- caBoard[i][j] = ' ';
- }
- }
- turns = 0;
- }
- public int getTurns() {
- return this.turns;
- }
- public char getPlayerAt(int r, int c) {
- return this.caBoard[r][c];
- }
- public String toString() {
- String sBoard = "+---+---+---+ \n";
- for (int i = 0; i < caBoard.length; i++) {
- for (int j = 0; j < caBoard[i].length; j++) {
- sBoard += ("| " + caBoard[i][j] + " ");
- }
- sBoard += "|";
- sBoard += "\n";
- for (int k = 0; k < caBoard.length; k++) {
- sBoard += ("+---");
- }
- sBoard += "+";
- sBoard += ("\n");
- }
- return sBoard;
- }
- public void playMove(char p, int r, int c) {
- if (isValid(r, c)) {
- this.caBoard[r][c] = p;
- this.turns++;
- }
- }
- public boolean isValid(int r, int c) {
- if ((r >= 0 && r <= this.caBoard.length) && (c >= 0 && c <= this.caBoard[r].length))
- return true;
- return false;
- }
- public boolean isWinner(char p) {
- if ((caBoard[0][0] == p && caBoard[1][1] == p && caBoard[2][2] == p)
- || (caBoard[0][2] == p && caBoard[1][1] == p && caBoard[2][0] == p))
- return true;
- for (int i = 0; i < this.caBoard.length; i++) {
- if (checkColumn(p, i))
- return true;
- }
- for (int i = 0; i < this.caBoard.length; i++) {
- if (checkRow(p, i))
- return true;
- }
- return false;
- }
- private boolean checkRow(char p, int r) {
- for (int i = 0; i < this.caBoard.length; i++) {
- if (caBoard[r][i] != p)
- return false;
- }
- return true;
- }
- private boolean checkColumn(char p, int c) {
- for (int i = 0; i < this.caBoard.length; i++) {
- if (caBoard[i][c] != p)
- return false;
- }
- return true;
- }
- public boolean isFull() {
- if (this.turns >= 9)
- return true;
- return false;
- }
- private boolean isTied() {
- if (isFull() && !(isWinner('X') || isWinner('O')))
- return true;
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement