This program in Java: Create a class TicTacToe that will enable you to write a p
ID: 3562396 • Letter: T
Question
This program in Java:
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 array. Use an enumeration to represent the value in each cell of the array. The enumerations constants should be named X, O and EMPTY (for a position that does not contain an X or an O). The constructor should initialize the board elements to EMPTY. Allow two human players. Wherever the first player moves, place an X in the specified square, and place an O 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 it's a draw.
Explanation / Answer
import java.util.Scanner;
public class TicTacToe
{
public enum Value{ EMPTY,X, O;}
private static Value [][] board = new Value[3][3];
public TicTacToe()
{
for(int i = 0 ; i <3 ;i++ )
{
for(int j = 0; j<3 ;j++)
{
board[i][j] = Value.EMPTY;
}
}
}
public static void main(String [] x)
{
TicTacToe game = new TicTacToe();
Scanner input = new Scanner(System.in);
int count=0;
int row,column;
boolean chance = true;
while(true)
{
System.out.printf("Player %d's chance: Enter row column Co-ordinates seprated by space",chance?1:2);
row = input.nextInt(); column = input.nextInt();
Value mark = chance?Value.O:Value.X;
count++;
try
{
game.move(row,column,mark);
}
catch(Exception e)
{
System.out.println(e);
continue;
}
game.displayBoard();
if(game.check(row, column, mark))
{
System.out.println("Player 1 won");
break;
}
else
{
chance = !chance;
}
if(count ==9)
{
System.out.println("Draw");
break;
}
}
input.close();
}
public void move(int row,int column, Value x )
{
if(board[row ][column] == Value.EMPTY)
board[row][column] = x;
else
throw new IllegalArgumentException("Position already Filled");
}
private boolean check(int row , int column, Value x)
{
boolean check1=true , check2= true;
if(row ==1 && column == 1)
{
if((board[0][0]== x && board[2][2] == x) | (board[0][2] == x && board[2][0] == x))
return true;
}
if((row == 0 | row == 2) && (column == 0 | column == 2))
{
if(board[1][1] == x && board[2-row][2-column] == x )
return true;
}
for(int i=0; i <3; i++)
{
if(board[row][i]!=x)
{
check1 = false;
break;
}
}
for(int i = 0; i<3; i++)
{
if(board[i][column] != x)
{
check2 = false;
break;
}
}
return check1|check2;
}
public void displayBoard()
{
for(Value[] row : board )
{
for(Value element : row)
{
System.out.print(" "+element);
}
System.out.println();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.