In: Computer Science
Can someone design a Tic Tac Toe game in java in the simplest way you can? It should have
-the markers for the players are X and O
-2 players
-instructions on how to play the game in the start of the game
-show the Tic Tac Toe grid before asking each player for their input
-be on one java file
Thank you!!!!!!! This is for an intro class so please don't make it too complicated!
JAVA PROGRAM
import java.util.*;
class TicTacToe{//class TicTacToe
private char[][] mat;
private int m;
private int n;
public TicTacToe(int m,int n){//constructor
this.m=m;
this.n=n;
mat=new char[m][n];
}
public boolean setRowColumn(int row,int column,char ch){//method
setRowColumn
if(row<0||row>=m||column<0||column>=n||mat[row][column]==ch){
System.out.println("Enter wrong input please try again!!");
return false;
}
mat[row][column]=ch;
return true;
}
public void displayboard(){//method displayboard
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(mat[i][j]=='X'||mat[i][j]=='O')
System.out.print("|"+mat[i][j]+"|");
else
System.out.print("| |");
}
System.out.println();
}
System.out.println();
}
public char WhoWin(){//method WhoWin
int count=1;
char ch=' ';
for(int i=0;i<m;i++){ //check row
for(int j=0;j<n-1;j++){
if(mat[i][j]==mat[i][j+1]){
count++;
ch=mat[i][j];
}
else
break;
}
if(count==m)
return ch;
count=1;
}
for(int i=0;i<n;i++){//check column
for(int j=0;j<m-1;j++){
if(mat[j][i]==mat[j+1][i]){
count++;
ch=mat[i][j];
}
else
break;
}
if(count==n)
return ch;
count=1;
}
for(int i=0,j=0;i<m-1&&j<n-1;i++,j++){//check
diagonal
if(mat[i][j]==mat[i+1][j+1]){
count++;
ch=mat[i][j];
}
else
break;
}
if(count==m)
return ch;
count=1;
for(int i=0,j=n-1;i<m-1&&j>0;i++,j--){//check reverse
diagonal
if(mat[i][j]==mat[i+1][j-1]){
count++;
ch=mat[i][j];
}
else
break;
}
if(count==m)
return ch;
count=1;
return ' ';
}
}
public class Main//class main
{
public static void main(String[] args) {//method
main
Scanner s=new Scanner(System.in);
System.out.print("Enter matrix
size[rowSize columnSize] : ");
int m=s.nextInt();
int n=s.nextInt();
TicTacToe T=new
TicTacToe(m,n);
int i,j;
char ch=' ';
do{
T.displayboard();
do{
System.out.print("Enter player1[row
column] : ");
i=s.nextInt();
j=s.nextInt();
}while(!T.setRowColumn(i,j,'X'));
T.displayboard();
ch=T.WhoWin();
if(ch=='X'||ch=='O')
break;
do{
System.out.print("Enter player2[row
column] : ");
i=s.nextInt();
j=s.nextInt();
}while(!T.setRowColumn(i,j,'O'));
ch=T.WhoWin();
if(ch=='X'||ch=='O')
break;
}while(true);
T.displayboard();
if(ch=='X')
System.out.println("Player1 Win!!
");
else if(ch=='O')
System.out.println("Player2 Win!!
");
}
}
OUTPUT