SlideShare a Scribd company logo
1 of 15
Download to read offline
Here is the code for you:
import java.util.Scanner;
import java.util.Random;
public class TicTacToeGame {
static char[] [] board = new char[3][3];
static Scanner input=new Scanner(System.in);
//Object of Stats class to maintain statistics
static Stats stat = new Stats();
/**
* Prints the TicTacToe board
* @param arr: The board so far
*/
public static void printBoard(char [][] arr){
System.out.println();
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
System.out.print(arr[i][j]);
if(j!=2)
//Print the | for readable output
System.out.print(" " + "|" + " ");
}
System.out.println();
if(i!=2) {
System.out.print("_ _ _ "); // Print _ for readability
System.out.println();;
}
}
}
/**
* Clear the TicTacToe board before starting a new game
* @param arr: The board so far
*/
public static void clearBoard(char [][] arr){
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
arr[i][j]=' ';
}
}
}
/** Determines if the player with the specified token wins
*
* @param symbol: Specifies whether the player is X or O
* @return true if player has won, false otherwise
*/
public static boolean isWon(char symbol) {
for (int i = 0; i < 3; i++) //horizontal
if (board[i][0] == symbol
&& board[i][1] == symbol
&& board[i][2] == symbol) {
return true;
}
//TODO!!! Also check for vertical and the two diagonals
for (int i = 0; i < 3; i++) //vertical
if (board[0][i] == symbol
&& board[1][i] == symbol
&& board[2][i] == symbol) {
return true;
}
//Leading diagonal
if (board[0][0] == symbol
&& board[1][1] == symbol
&& board[2][2] == symbol) {
return true;
}
//Trailing diagonal
if (board[0][2] == symbol
&& board[1][1] == symbol
&& board[2][0] == symbol) {
return true;
}
return false;
}
/** Determines if the cell is occupied
*
* @param row: Row of the cell to be checked
* @param col: Column of the cell to be checked
* @return true if the cell is occupied, false otherwise
*/
public static boolean isOccupied(int row, int col){
if (board[row][col]!=' ') return false;
else return true;
}
/** Determines who starts the game
*/
public static int whoStarts(){
//TODO: Randomly chooses between 0 and 1 and returns the choice
return (int)(Math.random() + 0.5 );
}
/** takes care of the human's move
* 1. Prompt for a cell, then column
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a human wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean humanTurn(char symbol){
//Prompt for a cell. User must enter
//row and column with a space in between.
System.out.print("  Enter your move: (row column): " );
int row = input.nextInt();
int col = input.nextInt();
//TODO!!! Mark user move in the board, print
//the board and check if user has won!
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** takes care of the computer's move
* 1. Generates numbers until finds an empty cell
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a comp wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean compTurn(char symbol) {
int row, col;
// TODO!!!
//Choose a random row (0-2) and column (0-2)
row = new Random().nextInt(3);
col = new Random().nextInt(3);
//Check if the randomly chosen cell is occupied. Keep choosing
//until an empty cell is found
while(isOccupied(row, col))
{
row = new Random().nextInt(3);
col = new Random().nextInt(3);
}
System.out.println("  My Move is: "+row+" "+ col);
//Mark the move, print the board and check if computer won
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** If human goes first:
* We have 9 moves in total (max). 8 moves will be in a loop
* and the last human move is outside of the loop:
* 1. human goes first, with a X
* 2. If the returned value is true (human won), then boolean flag=true
* and we break out of the loop. done indicates that the game is over.
* 3. If the game is not over, then it is computer's turn.
* 4. If the returned value is true (comp won), then boolean flag=true
* and we break out of the loop. done indicates that the game is over
* 5. Repeat the two steps above 3 more times.
* 6. If the done is still false, then a human performs one more move and
* we check if the move led to the win or tie.
* */
public static void humanFirst(){
boolean done=false;
for (int i=0; i<4; i++) {
if (humanTurn('X')) {
done=true;
break;
}
if (compTurn('O')){
done=true;
break;
}
} //end of for loop;
if (!done){
if (!humanTurn('X')) {
System.out.println("  A tie!");
stat.incrementTies();
}
}
}
/**
* Same logic as above, only the first computer's move happens before
* the loop. We do not need to check for winning combination here, since
* comp can't win after one move.
* After the loop we check if the game is done. If not, report a tie and
* update statistics.
*/
public static void compFirst(){
//TODO: Complete the method
boolean done=false;
for (int i=0; i<4; i++) {
if (compTurn('X')) {
done=true;
break;
}
if (humanTurn('O')){
done=true;
break;
}
} //end of for loop;
if (!done){
if (!compTurn('X')) {
System.out.println("  A tie!");
stat.incrementTies();
}
}
}
public static void main(String[] args) {
// input from the user, if he wants to play another game
String playAgain="";
// input from the user, if he wants to clear stats
String clearStats="";
do { //play until 'n' is pressed
clearBoard(board); //clear the baord
//Generate Random Assignment, determines who goes first;
int move = whoStarts();
if (move == 0) {
System.out.println(" I start first. I choose X and you get 0");
computerFirst();
}
else{
System.out.println(" You start first. You get X and I get 0");
humanFirst();
}
//TODO!!!
//Print statistics and ask if a user wants to repeat a game
stat.printStat();
System.out.print("Do you want to play again: ");
playAgain = input.next();
// If user enters 'y', ask to clear statistics
if(playAgain.charAg(0) == 'y')
{
System.out.print("Do you want to clear statistics: ");
clearStats = input.next();
if(clearStats.charAt(0) == 'y')
stats.clearStatistics();
}
// if user enters 'y', clear statistics and restart the game
//If user enters 'n', continue without clearing
// //If user enters 'n', quit the game
} while(playAgain.charAt(0)!='n'); //done with the outer loop
System.out.println(" Bye, see you later!");
}
}
Solution
Here is the code for you:
import java.util.Scanner;
import java.util.Random;
public class TicTacToeGame {
static char[] [] board = new char[3][3];
static Scanner input=new Scanner(System.in);
//Object of Stats class to maintain statistics
static Stats stat = new Stats();
/**
* Prints the TicTacToe board
* @param arr: The board so far
*/
public static void printBoard(char [][] arr){
System.out.println();
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
System.out.print(arr[i][j]);
if(j!=2)
//Print the | for readable output
System.out.print(" " + "|" + " ");
}
System.out.println();
if(i!=2) {
System.out.print("_ _ _ "); // Print _ for readability
System.out.println();;
}
}
}
/**
* Clear the TicTacToe board before starting a new game
* @param arr: The board so far
*/
public static void clearBoard(char [][] arr){
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
arr[i][j]=' ';
}
}
}
/** Determines if the player with the specified token wins
*
* @param symbol: Specifies whether the player is X or O
* @return true if player has won, false otherwise
*/
public static boolean isWon(char symbol) {
for (int i = 0; i < 3; i++) //horizontal
if (board[i][0] == symbol
&& board[i][1] == symbol
&& board[i][2] == symbol) {
return true;
}
//TODO!!! Also check for vertical and the two diagonals
for (int i = 0; i < 3; i++) //vertical
if (board[0][i] == symbol
&& board[1][i] == symbol
&& board[2][i] == symbol) {
return true;
}
//Leading diagonal
if (board[0][0] == symbol
&& board[1][1] == symbol
&& board[2][2] == symbol) {
return true;
}
//Trailing diagonal
if (board[0][2] == symbol
&& board[1][1] == symbol
&& board[2][0] == symbol) {
return true;
}
return false;
}
/** Determines if the cell is occupied
*
* @param row: Row of the cell to be checked
* @param col: Column of the cell to be checked
* @return true if the cell is occupied, false otherwise
*/
public static boolean isOccupied(int row, int col){
if (board[row][col]!=' ') return false;
else return true;
}
/** Determines who starts the game
*/
public static int whoStarts(){
//TODO: Randomly chooses between 0 and 1 and returns the choice
return (int)(Math.random() + 0.5 );
}
/** takes care of the human's move
* 1. Prompt for a cell, then column
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a human wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean humanTurn(char symbol){
//Prompt for a cell. User must enter
//row and column with a space in between.
System.out.print("  Enter your move: (row column): " );
int row = input.nextInt();
int col = input.nextInt();
//TODO!!! Mark user move in the board, print
//the board and check if user has won!
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** takes care of the computer's move
* 1. Generates numbers until finds an empty cell
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a comp wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean compTurn(char symbol) {
int row, col;
// TODO!!!
//Choose a random row (0-2) and column (0-2)
row = new Random().nextInt(3);
col = new Random().nextInt(3);
//Check if the randomly chosen cell is occupied. Keep choosing
//until an empty cell is found
while(isOccupied(row, col))
{
row = new Random().nextInt(3);
col = new Random().nextInt(3);
}
System.out.println("  My Move is: "+row+" "+ col);
//Mark the move, print the board and check if computer won
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** If human goes first:
* We have 9 moves in total (max). 8 moves will be in a loop
* and the last human move is outside of the loop:
* 1. human goes first, with a X
* 2. If the returned value is true (human won), then boolean flag=true
* and we break out of the loop. done indicates that the game is over.
* 3. If the game is not over, then it is computer's turn.
* 4. If the returned value is true (comp won), then boolean flag=true
* and we break out of the loop. done indicates that the game is over
* 5. Repeat the two steps above 3 more times.
* 6. If the done is still false, then a human performs one more move and
* we check if the move led to the win or tie.
* */
public static void humanFirst(){
boolean done=false;
for (int i=0; i<4; i++) {
if (humanTurn('X')) {
done=true;
break;
}
if (compTurn('O')){
done=true;
break;
}
} //end of for loop;
if (!done){
if (!humanTurn('X')) {
System.out.println("  A tie!");
stat.incrementTies();
}
}
}
/**
* Same logic as above, only the first computer's move happens before
* the loop. We do not need to check for winning combination here, since
* comp can't win after one move.
* After the loop we check if the game is done. If not, report a tie and
* update statistics.
*/
public static void compFirst(){
//TODO: Complete the method
boolean done=false;
for (int i=0; i<4; i++) {
if (compTurn('X')) {
done=true;
break;
}
if (humanTurn('O')){
done=true;
break;
}
} //end of for loop;
if (!done){
if (!compTurn('X')) {
System.out.println("  A tie!");
stat.incrementTies();
}
}
}
public static void main(String[] args) {
// input from the user, if he wants to play another game
String playAgain="";
// input from the user, if he wants to clear stats
String clearStats="";
do { //play until 'n' is pressed
clearBoard(board); //clear the baord
//Generate Random Assignment, determines who goes first;
int move = whoStarts();
if (move == 0) {
System.out.println(" I start first. I choose X and you get 0");
computerFirst();
}
else{
System.out.println(" You start first. You get X and I get 0");
humanFirst();
}
//TODO!!!
//Print statistics and ask if a user wants to repeat a game
stat.printStat();
System.out.print("Do you want to play again: ");
playAgain = input.next();
// If user enters 'y', ask to clear statistics
if(playAgain.charAg(0) == 'y')
{
System.out.print("Do you want to clear statistics: ");
clearStats = input.next();
if(clearStats.charAt(0) == 'y')
stats.clearStatistics();
}
// if user enters 'y', clear statistics and restart the game
//If user enters 'n', continue without clearing
// //If user enters 'n', quit the game
} while(playAgain.charAt(0)!='n'); //done with the outer loop
System.out.println(" Bye, see you later!");
}
}

More Related Content

Similar to Here is the code for youimport java.util.Scanner; import java.u.pdf

Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfhainesburchett26321
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdfkavithaarp
 
Please observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdfPlease observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdfapexjaipur
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docxPiersRCoThomsonw
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdffonecomp
 
#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docx#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docxajoy21
 
Write a program (any language) to randomly generate the following se.pdf
Write a program (any language) to randomly generate the following se.pdfWrite a program (any language) to randomly generate the following se.pdf
Write a program (any language) to randomly generate the following se.pdfarchanaemporium
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
 
Nested For Loops and Class Constants in Java
Nested For Loops and Class Constants in JavaNested For Loops and Class Constants in Java
Nested For Loops and Class Constants in JavaPokequesthero
 
Introduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdfIntroduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdffeelinggifts
 

Similar to Here is the code for youimport java.util.Scanner; import java.u.pdf (14)

Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdf
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 
Utility.ppt
Utility.pptUtility.ppt
Utility.ppt
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
Please observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdfPlease observe the the code and validations of user inputs.import .pdf
Please observe the the code and validations of user inputs.import .pdf
 
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
#include -stdio-h- #include -stdlib-h- #include -stdbool-h- #include - (1).docx
 
The following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdfThe following code, is a one player battleship game in JAVA. Im tryi.pdf
The following code, is a one player battleship game in JAVA. Im tryi.pdf
 
#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docx#include fstream#include iostream#include cstdlib#includ.docx
#include fstream#include iostream#include cstdlib#includ.docx
 
Write a program (any language) to randomly generate the following se.pdf
Write a program (any language) to randomly generate the following se.pdfWrite a program (any language) to randomly generate the following se.pdf
Write a program (any language) to randomly generate the following se.pdf
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
Nested For Loops and Class Constants in Java
Nested For Loops and Class Constants in JavaNested For Loops and Class Constants in Java
Nested For Loops and Class Constants in Java
 
Introduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdfIntroduction You implemented a Deck class in Activity 2. This cla.pdf
Introduction You implemented a Deck class in Activity 2. This cla.pdf
 

More from anithareadymade

We will be making 4 classes Main - for testing the code Hi.pdf
 We will be making 4 classes Main - for testing the code Hi.pdf We will be making 4 classes Main - for testing the code Hi.pdf
We will be making 4 classes Main - for testing the code Hi.pdfanithareadymade
 
#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdf#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdfanithareadymade
 
ITs both by the way... it depends on the situatio.pdf
                     ITs both by the way... it depends on the situatio.pdf                     ITs both by the way... it depends on the situatio.pdf
ITs both by the way... it depends on the situatio.pdfanithareadymade
 
I believe you are correct. The phase transfer cat.pdf
                     I believe you are correct. The phase transfer cat.pdf                     I believe you are correct. The phase transfer cat.pdf
I believe you are correct. The phase transfer cat.pdfanithareadymade
 
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdfThere are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdfanithareadymade
 
The correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdfThe correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdfanithareadymade
 
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdfThis is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdfanithareadymade
 
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdfThe possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdfanithareadymade
 
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdfThe answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdfanithareadymade
 
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdfRainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdfanithareadymade
 
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdfby taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdfanithareadymade
 
import java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdfimport java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdfanithareadymade
 
i did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdfi did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdfanithareadymade
 
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdfHello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdfanithareadymade
 
Following are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdfFollowing are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdfanithareadymade
 
During meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdfDuring meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdfanithareadymade
 
B parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdfB parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdfanithareadymade
 
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdfANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdfanithareadymade
 
Array- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdfArray- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdfanithareadymade
 

More from anithareadymade (20)

We will be making 4 classes Main - for testing the code Hi.pdf
 We will be making 4 classes Main - for testing the code Hi.pdf We will be making 4 classes Main - for testing the code Hi.pdf
We will be making 4 classes Main - for testing the code Hi.pdf
 
#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdf#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdf
 
MgO = 2416 = 1.5 .pdf
                     MgO = 2416 = 1.5                               .pdf                     MgO = 2416 = 1.5                               .pdf
MgO = 2416 = 1.5 .pdf
 
ITs both by the way... it depends on the situatio.pdf
                     ITs both by the way... it depends on the situatio.pdf                     ITs both by the way... it depends on the situatio.pdf
ITs both by the way... it depends on the situatio.pdf
 
I believe you are correct. The phase transfer cat.pdf
                     I believe you are correct. The phase transfer cat.pdf                     I believe you are correct. The phase transfer cat.pdf
I believe you are correct. The phase transfer cat.pdf
 
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdfThere are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
 
The correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdfThe correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdf
 
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdfThis is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
 
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdfThe possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
 
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdfThe answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
 
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdfRainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
 
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdfby taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
 
import java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdfimport java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdf
 
i did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdfi did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdf
 
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdfHello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
 
Following are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdfFollowing are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdf
 
During meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdfDuring meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdf
 
B parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdfB parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdf
 
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdfANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
 
Array- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdfArray- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdf
 

Recently uploaded

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Here is the code for youimport java.util.Scanner; import java.u.pdf

  • 1. Here is the code for you: import java.util.Scanner; import java.util.Random; public class TicTacToeGame { static char[] [] board = new char[3][3]; static Scanner input=new Scanner(System.in); //Object of Stats class to maintain statistics static Stats stat = new Stats(); /** * Prints the TicTacToe board * @param arr: The board so far */ public static void printBoard(char [][] arr){ System.out.println(); for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { System.out.print(arr[i][j]); if(j!=2) //Print the | for readable output System.out.print(" " + "|" + " "); } System.out.println(); if(i!=2) { System.out.print("_ _ _ "); // Print _ for readability System.out.println();; } } } /** * Clear the TicTacToe board before starting a new game * @param arr: The board so far
  • 2. */ public static void clearBoard(char [][] arr){ for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { arr[i][j]=' '; } } } /** Determines if the player with the specified token wins * * @param symbol: Specifies whether the player is X or O * @return true if player has won, false otherwise */ public static boolean isWon(char symbol) { for (int i = 0; i < 3; i++) //horizontal if (board[i][0] == symbol && board[i][1] == symbol && board[i][2] == symbol) { return true; } //TODO!!! Also check for vertical and the two diagonals for (int i = 0; i < 3; i++) //vertical if (board[0][i] == symbol && board[1][i] == symbol && board[2][i] == symbol) { return true; } //Leading diagonal if (board[0][0] == symbol && board[1][1] == symbol && board[2][2] == symbol) { return true;
  • 3. } //Trailing diagonal if (board[0][2] == symbol && board[1][1] == symbol && board[2][0] == symbol) { return true; } return false; } /** Determines if the cell is occupied * * @param row: Row of the cell to be checked * @param col: Column of the cell to be checked * @return true if the cell is occupied, false otherwise */ public static boolean isOccupied(int row, int col){ if (board[row][col]!=' ') return false; else return true; } /** Determines who starts the game */ public static int whoStarts(){ //TODO: Randomly chooses between 0 and 1 and returns the choice return (int)(Math.random() + 0.5 ); } /** takes care of the human's move * 1. Prompt for a cell, then column * 2. Puts a symbol (X or O) on the board * 3. Prints the updated board * 4. If a human wins: prints, updates stats and returns true * 5. If not a win yet, returns false */ public static boolean humanTurn(char symbol){
  • 4. //Prompt for a cell. User must enter //row and column with a space in between. System.out.print(" Enter your move: (row column): " ); int row = input.nextInt(); int col = input.nextInt(); //TODO!!! Mark user move in the board, print //the board and check if user has won! board[row][col] = symbol; printBoard(board); if(isWon(symbol)) return true; return false; } /** takes care of the computer's move * 1. Generates numbers until finds an empty cell * 2. Puts a symbol (X or O) on the board * 3. Prints the updated board * 4. If a comp wins: prints, updates stats and returns true * 5. If not a win yet, returns false */ public static boolean compTurn(char symbol) { int row, col; // TODO!!! //Choose a random row (0-2) and column (0-2) row = new Random().nextInt(3); col = new Random().nextInt(3); //Check if the randomly chosen cell is occupied. Keep choosing //until an empty cell is found while(isOccupied(row, col)) { row = new Random().nextInt(3); col = new Random().nextInt(3);
  • 5. } System.out.println(" My Move is: "+row+" "+ col); //Mark the move, print the board and check if computer won board[row][col] = symbol; printBoard(board); if(isWon(symbol)) return true; return false; } /** If human goes first: * We have 9 moves in total (max). 8 moves will be in a loop * and the last human move is outside of the loop: * 1. human goes first, with a X * 2. If the returned value is true (human won), then boolean flag=true * and we break out of the loop. done indicates that the game is over. * 3. If the game is not over, then it is computer's turn. * 4. If the returned value is true (comp won), then boolean flag=true * and we break out of the loop. done indicates that the game is over * 5. Repeat the two steps above 3 more times. * 6. If the done is still false, then a human performs one more move and * we check if the move led to the win or tie. * */ public static void humanFirst(){ boolean done=false; for (int i=0; i<4; i++) { if (humanTurn('X')) { done=true; break; } if (compTurn('O')){ done=true; break; }
  • 6. } //end of for loop; if (!done){ if (!humanTurn('X')) { System.out.println(" A tie!"); stat.incrementTies(); } } } /** * Same logic as above, only the first computer's move happens before * the loop. We do not need to check for winning combination here, since * comp can't win after one move. * After the loop we check if the game is done. If not, report a tie and * update statistics. */ public static void compFirst(){ //TODO: Complete the method boolean done=false; for (int i=0; i<4; i++) { if (compTurn('X')) { done=true; break; } if (humanTurn('O')){ done=true; break; } } //end of for loop; if (!done){ if (!compTurn('X')) { System.out.println(" A tie!"); stat.incrementTies(); }
  • 7. } } public static void main(String[] args) { // input from the user, if he wants to play another game String playAgain=""; // input from the user, if he wants to clear stats String clearStats=""; do { //play until 'n' is pressed clearBoard(board); //clear the baord //Generate Random Assignment, determines who goes first; int move = whoStarts(); if (move == 0) { System.out.println(" I start first. I choose X and you get 0"); computerFirst(); } else{ System.out.println(" You start first. You get X and I get 0"); humanFirst(); } //TODO!!! //Print statistics and ask if a user wants to repeat a game stat.printStat(); System.out.print("Do you want to play again: "); playAgain = input.next(); // If user enters 'y', ask to clear statistics if(playAgain.charAg(0) == 'y') { System.out.print("Do you want to clear statistics: "); clearStats = input.next(); if(clearStats.charAt(0) == 'y') stats.clearStatistics();
  • 8. } // if user enters 'y', clear statistics and restart the game //If user enters 'n', continue without clearing // //If user enters 'n', quit the game } while(playAgain.charAt(0)!='n'); //done with the outer loop System.out.println(" Bye, see you later!"); } } Solution Here is the code for you: import java.util.Scanner; import java.util.Random; public class TicTacToeGame { static char[] [] board = new char[3][3]; static Scanner input=new Scanner(System.in); //Object of Stats class to maintain statistics static Stats stat = new Stats(); /** * Prints the TicTacToe board * @param arr: The board so far */ public static void printBoard(char [][] arr){ System.out.println(); for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { System.out.print(arr[i][j]); if(j!=2) //Print the | for readable output
  • 9. System.out.print(" " + "|" + " "); } System.out.println(); if(i!=2) { System.out.print("_ _ _ "); // Print _ for readability System.out.println();; } } } /** * Clear the TicTacToe board before starting a new game * @param arr: The board so far */ public static void clearBoard(char [][] arr){ for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { arr[i][j]=' '; } } } /** Determines if the player with the specified token wins * * @param symbol: Specifies whether the player is X or O * @return true if player has won, false otherwise */ public static boolean isWon(char symbol) { for (int i = 0; i < 3; i++) //horizontal if (board[i][0] == symbol && board[i][1] == symbol && board[i][2] == symbol) { return true;
  • 10. } //TODO!!! Also check for vertical and the two diagonals for (int i = 0; i < 3; i++) //vertical if (board[0][i] == symbol && board[1][i] == symbol && board[2][i] == symbol) { return true; } //Leading diagonal if (board[0][0] == symbol && board[1][1] == symbol && board[2][2] == symbol) { return true; } //Trailing diagonal if (board[0][2] == symbol && board[1][1] == symbol && board[2][0] == symbol) { return true; } return false; } /** Determines if the cell is occupied * * @param row: Row of the cell to be checked * @param col: Column of the cell to be checked * @return true if the cell is occupied, false otherwise */ public static boolean isOccupied(int row, int col){ if (board[row][col]!=' ') return false; else return true; } /** Determines who starts the game */
  • 11. public static int whoStarts(){ //TODO: Randomly chooses between 0 and 1 and returns the choice return (int)(Math.random() + 0.5 ); } /** takes care of the human's move * 1. Prompt for a cell, then column * 2. Puts a symbol (X or O) on the board * 3. Prints the updated board * 4. If a human wins: prints, updates stats and returns true * 5. If not a win yet, returns false */ public static boolean humanTurn(char symbol){ //Prompt for a cell. User must enter //row and column with a space in between. System.out.print(" Enter your move: (row column): " ); int row = input.nextInt(); int col = input.nextInt(); //TODO!!! Mark user move in the board, print //the board and check if user has won! board[row][col] = symbol; printBoard(board); if(isWon(symbol)) return true; return false; } /** takes care of the computer's move * 1. Generates numbers until finds an empty cell * 2. Puts a symbol (X or O) on the board * 3. Prints the updated board * 4. If a comp wins: prints, updates stats and returns true * 5. If not a win yet, returns false */ public static boolean compTurn(char symbol) {
  • 12. int row, col; // TODO!!! //Choose a random row (0-2) and column (0-2) row = new Random().nextInt(3); col = new Random().nextInt(3); //Check if the randomly chosen cell is occupied. Keep choosing //until an empty cell is found while(isOccupied(row, col)) { row = new Random().nextInt(3); col = new Random().nextInt(3); } System.out.println(" My Move is: "+row+" "+ col); //Mark the move, print the board and check if computer won board[row][col] = symbol; printBoard(board); if(isWon(symbol)) return true; return false; } /** If human goes first: * We have 9 moves in total (max). 8 moves will be in a loop * and the last human move is outside of the loop: * 1. human goes first, with a X * 2. If the returned value is true (human won), then boolean flag=true * and we break out of the loop. done indicates that the game is over. * 3. If the game is not over, then it is computer's turn. * 4. If the returned value is true (comp won), then boolean flag=true * and we break out of the loop. done indicates that the game is over * 5. Repeat the two steps above 3 more times. * 6. If the done is still false, then a human performs one more move and * we check if the move led to the win or tie.
  • 13. * */ public static void humanFirst(){ boolean done=false; for (int i=0; i<4; i++) { if (humanTurn('X')) { done=true; break; } if (compTurn('O')){ done=true; break; } } //end of for loop; if (!done){ if (!humanTurn('X')) { System.out.println(" A tie!"); stat.incrementTies(); } } } /** * Same logic as above, only the first computer's move happens before * the loop. We do not need to check for winning combination here, since * comp can't win after one move. * After the loop we check if the game is done. If not, report a tie and * update statistics. */ public static void compFirst(){ //TODO: Complete the method boolean done=false; for (int i=0; i<4; i++) { if (compTurn('X')) {
  • 14. done=true; break; } if (humanTurn('O')){ done=true; break; } } //end of for loop; if (!done){ if (!compTurn('X')) { System.out.println(" A tie!"); stat.incrementTies(); } } } public static void main(String[] args) { // input from the user, if he wants to play another game String playAgain=""; // input from the user, if he wants to clear stats String clearStats=""; do { //play until 'n' is pressed clearBoard(board); //clear the baord //Generate Random Assignment, determines who goes first; int move = whoStarts(); if (move == 0) { System.out.println(" I start first. I choose X and you get 0"); computerFirst(); } else{ System.out.println(" You start first. You get X and I get 0"); humanFirst(); }
  • 15. //TODO!!! //Print statistics and ask if a user wants to repeat a game stat.printStat(); System.out.print("Do you want to play again: "); playAgain = input.next(); // If user enters 'y', ask to clear statistics if(playAgain.charAg(0) == 'y') { System.out.print("Do you want to clear statistics: "); clearStats = input.next(); if(clearStats.charAt(0) == 'y') stats.clearStatistics(); } // if user enters 'y', clear statistics and restart the game //If user enters 'n', continue without clearing // //If user enters 'n', quit the game } while(playAgain.charAt(0)!='n'); //done with the outer loop System.out.println(" Bye, see you later!"); } }