***JAVA***
Write a program that randomly populates a standard tic tac toe board, and then determines if there is a winner or if there is a tie (“cat”). Also the program should print out the randomly generated board to verify its findings. You may also assume that the board is fully populated before a winner is checked, and in the event that both players have a winning condition print out that both win.
Example Dialog:
Welcome to Random Tic Tac Toe Checker. Let’s see our randomly generated board.
XOX
XOX
OXX
The X’s win!
Another Example Dialog:
Welcome to Random Tic Tac Toe Checker. Let’s see our randomly generated board.
XOX
XOX
OXO
Cat! No one wins
Yet Another Example Dialog:
Welcome to Random Tic Tac Toe Checker. Let’s see our randomly generated board.
XOX
XOO
XOX
The X’s win! The O’s win!
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class TicTacToe1 {
static char board[][]; //2D char array to store
tictactoe board
static boolean flag=false;
public static void main(String a[]){
board=new char[3][3];
Random r=new Random();
List<Integer> rans=new
ArrayList<Integer>();
//populate the board
for(int i=0;i<3;i++){
for(int
j=0;j<3;j++){
//generate random number between 0-10
int temp=r.nextInt(10);
//if number is generated before then
regenerate
while(rans.contains(temp)){
temp=r.nextInt(10);
}
rans.add(temp);
//if number is greater than 4 select O else
select X
char c=temp>4 ? 'O' : 'X';
board[i][j]=c;
System.out.print(c+" ");
}
System.out.println();
}
checkRowsForWin(); //if any row has
same characters
checkColsForWin(); //if any collumn
has same characters
checkDiagForWin(); //if diagonal
has same characters
//if no one wins
if(!flag){
System.out.println("Cat!No one wins");
}
}
private static void checkRowsForWin(){
//check for all 3 rows
for(int i=0;i<3;i++){
if(checkRowCol(board[i][0],board[i][1], board[i][2])==true){
System.out.println("The "+board[i][0]+"'s
Win!");
flag=true;
}
}
}
private static void checkColsForWin(){
//check for all 3 cols
for(int i=0;i<3;i++){
if(checkRowCol(board[0][i],board[1][i], board[2][i])==true){
System.out.println("The "+board[0][i]+"'s
Win!");
flag=true;
}
}
}
private static void checkDiagForWin(){
//check for both diagonals
if(checkRowCol(board[0][0],board[1][1], board[2][2])==true ||
checkRowCol(board[0][2],board[1][1], board[2][0])==true){
System.out.println("The "+board[1][1]+"'s
Win!");
flag=true;
}
}
private static boolean checkRowCol(char c1,char
c2,char c3){
return
((c1==c2)&&(c2==c3));
}
}
OutPut:
O O O
X X O
X O X
The O's Win!
X X X
X O O
O O O
The X's Win!
The O's Win!
X O X
O O X
O X O
Cat!No one wins
X O X
X X O
O O X
The X's Win!
Get Answers For Free
Most questions answered within 1 hours.