Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Name: Nate Wheeler
- * Date: Oct 16, 2016
- * Course Number: csc220
- * Course Name: Data Structures
- * Problem Number: hw 4
- * Email: nate23nate23@gmail.com
- * Short Description of the Problem:
- * Write a class called TicTacToe to handle the
- * basics of a two-player game of Tic-Tac-Toe.
- */
- package compsci220;
- public class TicTacToe {
- char[][] board;
- int turns;
- public TicTacToe() {
- board = new char[3][3];
- turns = 0;
- for (int i = 0; i < board.length; i++) {
- for (int j = 0; j < board[i].length; j++) {
- board[i][j] = ' ';
- }
- }
- }
- public int getTurns() {
- return this.turns;
- }
- public char getPlayerAt(int r, int c) {
- return this.board[r][c];
- }
- public String toString() {
- String array = "";
- for (int i = 0; i < board.length; i++) {
- for (int j = 0; j < board[0].length; j++) {
- array += " " + this.board[i][j];
- }
- array += "\n";
- }
- return array;
- }
- public boolean isFull() {
- if (this.turns == 9)
- return true;
- else
- return false;
- }
- public boolean isValid(int r, int c) {
- if (0 <= r && r <= 2 && c >= 0 && c <= 2)
- return true;
- else
- return false;
- }
- public boolean isTied() {
- if (this.isFull() == true && this.isWinner('X') == false && this.isWinner('O') == false)
- return true;
- else
- return false;
- }
- public boolean isWinner(char p) {
- Character.toUpperCase(p);
- if (p == this.board[0][0] && p == this.board[0][1] && p == this.board[0][2])
- return true;
- if (p == this.board[1][0] && p == this.board[1][1] && p == this.board[1][2])
- return true;
- if (p == this.board[2][0] && p == this.board[2][1] && p == this.board[2][2])
- return true;
- if (p == this.board[0][0] && p == this.board[1][0] && p == this.board[2][0])
- return true;
- if (p == this.board[0][1] && p == this.board[1][1] && p == this.board[2][1])
- return true;
- if (p == this.board[0][2] && p == this.board[1][2] && p == this.board[2][2])
- return true;
- if (p == this.board[0][0] && p == this.board[1][1] && p == this.board[2][2])
- return true;
- if (p == this.board[0][2] && p == this.board[1][1] && p == this.board[2][0])
- return true;
- return false;
- }
- public void playMove(char p, int r, int c) {
- Character.toUpperCase(p);
- this.turns++;
- if (p == 'X' || p == 'O')
- this.board[r][c] = p;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement