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.pdf
hainesburchett26321
 
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
kavithaarp
 
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
apexjaipur
 
#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
PiersRCoThomsonw
 
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
fonecomp
 
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
archanaemporium
 
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
aoneonlinestore1
 
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
archanaemporium
 
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
feelinggifts
 

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.pdf
anithareadymade
 
#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
anithareadymade
 
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
anithareadymade
 
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
anithareadymade
 
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
anithareadymade
 
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
anithareadymade
 
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
anithareadymade
 
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
anithareadymade
 
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
anithareadymade
 

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

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

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!"); } }