Question
. a. Create a class TicTacToe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional integer
.
a. Create a class TicTacToe that will enable you to write a program to play Tic-Tac-Toe. The class contains a private 3-by-3 two-dimensional integer array where 1 represents X, 0 represents available/empty, -1 represents O. The constructor should initialize the board elements to empty. Allow two human players. Wherever the first player moves, place a 1 in the specified square, and place a -1 wherever the second player moves. Each move must be to an empty square. After each move, determine whether the game has been won and whether its a draw. If it is a win then print which player won and if its a draw then reinitialize the array to empty and restart the game: this could be done using a sentinel controlled loop. You are provided with a class
//given program
package Chapter9;
public class TicTacToePrinter
{
//1 represent X and -1 represents O
public void printBoard(int array[][])
{
//check if array is of the dimension 3X3
if(array.length==3 && array[0].length==3 && array[1].length==3
&& array[2].length==3)
;
else
{
System.out.println("Your array must be of 3X3 dimension");
return;
}
String values[][] = new String[3][3];
//check if array contains anything else than 1, 0, -1
//1 means X, 0 means available, -1 means O
for(int index1=0;index1 { for(int index2=0;index2 { if(array[index1][index2]>1 || array[index1][index2]<-1) { System.out.println("Your array contains invalid values"); System.out.println("Correct values are: 1=X, 0=available, -1=O"); return; } if(array[index1][index2]==1) { values[index1][index2]= "X"; } else if (array[index1][index2]==-1) { values[index1][index2]= "O"; } else { values[index1][index2]= "-"; } } } System.out.println(); System.out.println("- is available"); System.out.println(); System.out.printf("%-8s %2s %2s %2s%n", "column \u2192", "0","1","2"); System.out.println("row \u2193"); System.out.printf("%-8s %2s | %2s | %2s%n", "0", values[0][0],values[0][1],values[0][2]); System.out.printf("%-8s %2s | %2s | %2s%n", "1", values[1][0],values[1][1],values[1][2]); System.out.printf("%-8s %2s | %2s | %2s%n", "2", values[2][0],values[2][1],values[2][2]); } } //second provided class public class TicTacToePrinterDriver { public static void main(String a[]) { int arr[][] = { {-1,0,1}, {1,1,-1}, {-1,0,1} }; TicTacToePrinter t = new TicTacToePrinter(); t.printBoard(arr); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started