In a game of TicTacToe, two players take turns marking an available cell in a 3x3 grid with their respective tokens(either X or O). When one player has placed three tokens in a horizontal, vertical, or diagonal row on the grid, the game is over and that player has won, A draw (no winner) occurs when all the cells on the grid have been filled with token and neither player has achieved a win. Create a program for playing TicTacToe.
The program prompts two players to enter X token and O token alternately. Whenever a token is entered, the program redisplays the broad on the console and determines the status of the game (win, draw, or continue).
import java.util.Date;
import java.util.Scanner;
import java.util.Calendar;
import javax.swing.JFrame;
public class TicIacIoe
{
char[][] block={{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
TicIacIoe(){}
public void show()
{
System.out.println("-------");
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
System.out.print("|" + block[i][j]);
System.out.println("|");
System.out.println("-------");
}
}
public void playx()
{
int i=0,j=0;
Scanner input = new Scanner(System.in);
while(true)
{
System.out.print("Enter a row (0, 1, or 2) for player X:");
i=input.nextInt();
System.out.print("Enter a column (0, 1, or 2) for player X:");
j=input.nextInt();
if(i>2||j>2)
System.out.println("Your range is wrong!");
else if(block[i][j]!=' ')
System.out.println("The step is wrong!");
else
break;
}
block[i][j]='X';
}
public void playo()
{
int i=0,j=0;
Scanner input = new Scanner(System.in);
while(true)
{
System.out.print("Enter a row (0, 1, or 2) for player O:");
i=input.nextInt();
System.out.print("Enter a column (0, 1, or 2) for player O:");
j=input.nextInt();
if(block[i][j]!=' '||i>2||j>2)
System.out.println("The step is wrong!");
else
break;
}
block[i][j]='O';
}
public boolean check(char n)
{
if((block[0][0]==n&&block[0][1]==n&&block[0][2]==n)||(block[1][0]==n&&block[1][1]==n&&block[1][2]==n)||(block[2][0]==n&&block[2][1]==n&&block[2][2]==n))
return true;
if((block[0][0]==n&&block[1][0]==n&&block[2][0]==n)||(block[0][1]==n&&block[1][1]==n&&block[2][1]==n)||(block[0][2]==n&&block[1][2]==n&&block[2][2]==n))
return true;
if((block[0][0]==n&&block[1][1]==n&&block[2][2]==n)||(block[0][2]==n&&block[1][1]==n&&block[2][0]==n))
return true;
return false;
}
public static void main(String[] args)
{
TicIacIoe ticIacIoe =new TicIacIoe();
int cnt=0;
while(true)
{
ticIacIoe.show();
ticIacIoe.playx();
ticIacIoe.show();
if(ticIacIoe.check('X'))
{
System.out.println("X palyer won");
break;
}
cnt++;
if(cnt==9)
{
System.out.println("It is a draw");
break;
}
ticIacIoe.playo();
ticIacIoe.show();
if(ticIacIoe.check('O'))
{
System.out.println("O palyer won");
break;
}
cnt++;
}
}
}