What is each line of code doing in this Java Program? Please explain line by lin
ID: 3889625 • Letter: W
Question
What is each line of code doing in this Java Program? Please explain line by line.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tictactoe.java;
import java.util.Scanner;
public class TicTacToeJava {
public static Scanner sc = new Scanner(System.in); /**
* @param args the command line arguments
*/
public static void main(String[] args) {
final int SIZE = 3;
char[][] board = new char[SIZE][SIZE]; // game board
resetBoard(board); // initialize the board (with ' ' for all cells)
// First, welcome message and display the board.
System.out.println("===== WELCOME TO THE TIC-TAC-TOE GAME!! ===== ");
showBoard(board);
// Then ask the user which symbol (x or o) he/she wants to play.
System.out.print(" Which symbol do you want to play, "x" or "o"? ");
char userSymbol = sc.next().toLowerCase().charAt(0);
char compSymbol = (userSymbol == 'x') ? 'o' : 'x';
// Also ask whether or not the user wants to go first.
System.out.println();
System.out.print(" Do you want to go first (y/n)? ");
char ans = sc.next().toLowerCase().charAt(0);
int turn; // 0 -- the user, 1 -- the computer
int remainCount = SIZE * SIZE; // empty cell count
// THE VERY FIRST MOVE.
if (ans == 'y') {
turn = 0;
userPlay(board, userSymbol); // user puts his/her first tic
}
else {
turn = 1;
compPlay(board, compSymbol); // computer puts its first tic
}
// Show the board, and decrement the count of remaining cells.
showBoard(board);
remainCount--;
// Play the game until either one wins.
boolean done = false;
int winner = -1; // 0 -- the user, 1 -- the computer, -1 -- draw
while (!done && remainCount > 0) {
// If there is a winner at this time, set the winner and the done flag to true.
done = isGameWon(board, turn, userSymbol, compSymbol); // Did the turn won?
if (done)
winner = turn; // the one who made the last move won the game
else {
// No winner yet. Find the next turn and play.
turn = (turn + 1 ) % 2;
if (turn == 0)
userPlay(board, userSymbol);
else
compPlay(board, compSymbol);
// Show the board after one tic, and decrement the rem count.
showBoard(board);
remainCount--;
}
}
// Winner is found. Declare the winner.
if (winner == 0)
System.out.println(" ** YOU WON. CONGRATULATIONS!! **");
else if (winner == 1)
System.out.println(" ** YOU LOST.. Maybe next time :) **");
else
System.out.println(" ** DRAW... **");
}
public static void resetBoard(char[][] brd)
{
for (int i = 0; i < brd.length; i++)
for (int j = 0; j < brd[0].length; j++)
brd[i][j] = ' ';
}
public static void showBoard(char[][] brd)
{
int numRow = brd.length;
int numCol = brd[0].length;
System.out.println();
// First write the column header
System.out.print(" ");
for (int i = 0; i < numCol; i++)
System.out.print(i + " ");
System.out.print(' ');
System.out.println(); // blank line after the header
// The write the table
for (int i = 0; i < numRow; i++) {
System.out.print(i + " ");
for (int j = 0; j < numCol; j++) {
if (j != 0)
System.out.print("|");
System.out.print(" " + brd[i][j] + " ");
}
System.out.println();
if (i != (numRow - 1)) {
// separator line
System.out.print(" ");
for (int j = 0; j < numCol; j++) {
if (j != 0)
System.out.print("+");
System.out.print("---");
}
System.out.println();
}
}
System.out.println();
}
public static void userPlay(char[][] brd, char usym)
{
System.out.print(" Enter the row and column indices: ");
int rowIndex = sc.nextInt();
int colIndex = sc.nextInt();
while (brd[rowIndex][colIndex] != ' ') {
System.out.print(" !! The cell is already taken. Enter the row and column indices: ");
rowIndex = sc.nextInt();
colIndex = sc.nextInt();
}
brd[rowIndex][colIndex] = usym;
}
public static void compPlay(char[][] brd, char csym)
{
// Find the first empty cell and put a tic there.
for (int i = 0; i < brd.length; i++) {
for (int j = 0; j < brd[0].length; j++) {
if (brd[i][j] == ' ') { // empty cell
brd[i][j] = csym;
return;
}
}
}
}
public static boolean isGameWon(char[][] brd, int turn, char usym, char csym)
{
char sym;
if (turn == 0)
sym = usym;
else
sym = csym;
int i, j;
boolean win = false;
// Check win by a row
for (i = 0; i < brd.length && !win; i++) {
for (j = 0; j < brd[0].length; j++) {
if (brd[i][j] != sym)
break;
}
if (j == brd[0].length)
win = true;
}
// Check win by a column
for (j = 0; j < brd[0].length && !win; j++) {
for (i = 0; i < brd.length; i++) {
if (brd[i][j] != sym)
break;
}
if (i == brd.length)
win = true;
}
// Check win by a diagonal (1)
if (!win) {
for (i = 0; i < brd.length; i++) {
if (brd[i][i] != sym)
break;
}
if (i == brd.length)
win = true;
}
// Check win by a diagonal (2)
if (!win) {
for (i = 0; i < brd.length; i++) {
if (brd[i][brd.length - 1 - i] != sym)
break;
}
if (i == brd.length)
win = true;
}
// Finally return win
return win;
}
}
Explanation / Answer
//package tictactoe.java;//package
import java.util.Scanner;
public class TicTacToeJava {
public static Scanner sc = new Scanner(System.in); //to read input...
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
final int SIZE = 3;
char[][] board = new char[SIZE][SIZE]; // game board
resetBoard(board); // initialize the board (with ' ' for all cells)
// First, welcome message and display the board.
System.out.println("===== WELCOME TO THE TIC-TAC-TOE GAME!! ===== ");//printing welcome, game name
showBoard(board);//calling showBoard function...passing array board as parameter
// Then ask the user which symbol (x or o) he/she wants to play.
System.out.print(" Which symbol do you want to play, "x" or "o"? ");//showing symbols to select
char userSymbol = sc.next().toLowerCase().charAt(0);//reading and setting user symbol
char compSymbol = (userSymbol == 'x') ? 'o' : 'x';//setting comp symbol...other one
// Also ask whether or not the user wants to go first.
System.out.println();//printing line
System.out.print(" Do you want to go first (y/n)? ");
char ans = sc.next().toLowerCase().charAt(0);//reading uwer decision
int turn; // 0 -- the user, 1 -- the computer
int remainCount = SIZE * SIZE; // empty cell count//initial empty cel count
// THE VERY FIRST MOVE.
if (ans == 'y') {//if user want to go first then
turn = 0;//setting turn to 0, for user
userPlay(board, userSymbol); // user puts his/her first tic//calling userPlay function
}
else {
turn = 1;//setting comp turn to 1
compPlay(board, compSymbol); // computer puts its first tic//calling comPlay function
}
// Show the board, and decrement the count of remaining cells.
showBoard(board);
remainCount--;//decreasing count
// Play the game until either one wins.
boolean done = false;//variable to denote game over or not
int winner = -1; // 0 -- the user, 1 -- the computer, -1 -- draw
while (!done && remainCount > 0) {//loop runs..until game over or.. remainCount is zero
// If there is a winner at this time, set the winner and the done flag to true.
done = isGameWon(board, turn, userSymbol, compSymbol); // Did the turn won?//checking game over or not
if (done)//if game over
winner = turn; // the one who made the last move won the game//storing winner//
else {//not done
// No winner yet. Find the next turn and play.
turn = (turn + 1 ) % 2;//finding the next turn player|comp
if (turn == 0)//if users turn
userPlay(board, userSymbol);//calling userPlay function
else//if comp turn
compPlay(board, compSymbol);//calling compPlay function
// Show the board after one tic, and decrement the rem count.
showBoard(board);//showing board after each turn
remainCount--;//decreasing count
}
}
// Winner is found. Declare the winner.
if (winner == 0)//if user is winner
System.out.println(" ** YOU WON. CONGRATULATIONS!! **");
else if (winner == 1)//if cpu is winner
System.out.println(" ** YOU LOST.. Maybe next time :) **");
else//if draw
System.out.println(" ** DRAW... **");
}
public static void resetBoard(char[][] brd)//method to reset board..means setting all values in 2d array brd to ' '
{
for (int i = 0; i < brd.length; i++)//traversing all rows
for (int j = 0; j < brd[0].length; j++)//traversing all columns
brd[i][j] = ' ';//setting all values in 2d array brd to ' '
}
public static void showBoard(char[][] brd)//to show the contents of 2d array brd
{
int numRow = brd.length;//getting number rows brd
int numCol = brd[0].length;//getting number of columns in brd
System.out.println();
// First write the column header
System.out.print(" ");
for (int i = 0; i < numCol; i++)
System.out.print(i + " ");//printing column numbers
System.out.print(' ');
System.out.println(); // blank line after the header
// The write the table
for (int i = 0; i < numRow; i++) //traversing all row
{
System.out.print(i + " ");//printing row number and space
for (int j = 0; j < numCol; j++)//traversing all columns///means single row
{
if (j != 0)
System.out.print("|");
System.out.print(" " + brd[i][j] + " ");//printing all elements in ith row
}
System.out.println();
if (i != (numRow - 1)) //after printing last row
{
// separator line
System.out.print(" ");
//printing additional row with---- +
for (int j = 0; j < numCol; j++) {
if (j != 0)
System.out.print("+");
System.out.print("---");
}
System.out.println();
}
}
System.out.println();
}
public static void userPlay(char[][] brd, char usym)//method to set user symbol in board
{
System.out.print(" Enter the row and column indices: ");//asking to enter the position to place ... the symbol
int rowIndex = sc.nextInt();//reading row index
int colIndex = sc.nextInt();//reading col index
while (brd[rowIndex][colIndex] != ' ') //to ask user repeatedly..upto the valid index...which is an empty place..to keep the symbol
{
System.out.print(" !! The cell is already taken. Enter the row and column indices: ");//showing error msg
rowIndex = sc.nextInt();//reading again row index
colIndex = sc.nextInt();//reading again col index
}
brd[rowIndex][colIndex] = usym;//setting user symbol in desired position
}
public static void compPlay(char[][] brd, char csym)//method to set computer symbol in board
{
// Find the first empty cell and put a tic there.
for (int i = 0; i < brd.length; i++) {
for (int j = 0; j < brd[0].length; j++) {
if (brd[i][j] == ' ') { // empty cell//finding first empty cell
brd[i][j] = csym;//placing in empty symbol
return;
}
}
}
}
public static boolean isGameWon(char[][] brd, int turn, char usym, char csym)//method to check game status//checking who won the game
{
char sym;
//checking the last turn
if (turn == 0)//if users
sym = usym;//setting sym to users
else//if comps
sym = csym;//setting sym to comp
int i, j;
boolean win = false;//initially setting win to false
// Check win by a row
for (i = 0; i < brd.length && !win; i++) //traversing rows..//runs upto win is false
{
for (j = 0; j < brd[0].length; j++) //traversing cols.
{//means reading row by row
if (brd[i][j] != sym)//if the i,j th symbol of board is not equals to sym
break;//then breaking loop
}
if (j == brd[0].length)//j is equals to complete row length(ie number of cols)..means one complete row has same symbol
win = true;//then setting win to true
}
// Check win by a column
for (j = 0; j < brd[0].length && !win; j++)//traversing cols.//runs upto win is false
{
for (i = 0; i < brd.length; i++) //traversing rows..
{
//means reading col by col
if (brd[i][j] != sym)//if the i,j th symbol of board is not equals to sym
break;//then breaking loop
}
if (i == brd.length)//i is equals to complete col length(ie number of rows)..means one complete col has same symbol
win = true;//setting win to true
}
// Check win by a diagonal (1)
if (!win) {
for (i = 0; i < brd.length; i++) //traversing diagonally
{
if (brd[i][i] != sym)//if the i,i th symbol of board is not equals to sym
break;//then breaking loop
}
if (i == brd.length)//i is equals to complete length(ie number of rows|cols)..means one diagonal1 has same symbol
win = true;//setting win to true
}
// Check win by a diagonal (2)
if (!win) {
for (i = 0; i < brd.length; i++)//traversing diagonally
{
if (brd[i][brd.length - 1 - i] != sym)//if the i,lenght-1-i th symbol of board is not equals to sym
break;//then breaking loop
}
if (i == brd.length)//i is equals to completelength(ie number of rows|cols)..means one diagonal2 has same symbol
win = true;
}
// Finally return win
return win;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.