SlideShare a Scribd company logo
1 of 10
Download to read offline
In Java using Eclipse, I'm suppose to write a class that encapsulates a tic tac toe board using two
dimensional arrays. It should only involve the human player vs. the computer, and should
randomly select who should use 'X' or 'O' and whether the human player or the computer
should go first. Verify that all moves by the human player are to a valid space on the tic-tac-toe
board, and an incorrect choice should not halt or terminate the game. Below is my Java program
that is currently a work in progress. Can you help me remodify it? Thanks.
import java.util.Scanner;
public class LeavinesTicTacToe
{
public static Scanner sc = new Scanner(System.in);
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;
}
}
Solution
Please see below program, I made this few years back . Please follow this and comment if you
have any doubts.
import java.util.Scanner;
public class LeavinesTicTacToeNew {
public static final int EMPTY = 0;
public static final int CROSS = 1;
public static final int NOUGHT = 2;
public static final int PLAYING = 0;
public static final int DRAW = 1;
public static final int CROSS_WON = 2;
public static final int NOUGHT_WON = 3;
public static final int ROWS = 3, COLS = 3; // number of rows and columns
public static int[][] board = new int[ROWS][COLS];
public static int currentState; // the current state of the game
public static int currentPlayer; // the current player (CROSS or NOUGHT)
public static int currntRow, currentCol; // current seed's row and column
public static Scanner in = new Scanner(System.in); // the input Scanner
public static void main(String[] args) {
// Initialize the game-board and current status
resetBoard();
// Play the game once
do {
playerMove(currentPlayer); // update currentRow and currentCol
updateGame(currentPlayer, currntRow, currentCol); // update
// currentState
printBoard();
// Print message if game-over
if (currentState == CROSS_WON) {
System.out.println("'X' won! Bye!");
} else if (currentState == NOUGHT_WON) {
System.out.println("'O' won! Bye!");
} else if (currentState == DRAW) {
System.out.println("It's a Draw! Bye!");
}
// Switch player
currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS;
} while (currentState == PLAYING); // repeat if not game-over
}
public static void resetBoard() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
board[row][col] = EMPTY; // all cells empty
}
}
currentState = PLAYING; // ready to play
currentPlayer = CROSS; // cross plays first
}
public static void playerMove(int theSeed) {
boolean validInput = false; // for input validation
do {
if (theSeed == CROSS) {
System.out
.print("Player 'X', enter your move (row[1-3] column[1-3]): ");
} else {
System.out
.print("Player 'O', enter your move (row[1-3] column[1-3]): ");
}
int row = in.nextInt() - 1; // array index starts at 0 instead of 1
int col = in.nextInt() - 1;
if (row >= 0 && row < ROWS && col >= 0 && col < COLS
&& board[row][col] == EMPTY) {
currntRow = row;
currentCol = col;
board[currntRow][currentCol] = theSeed; // update game-board
// content
validInput = true; // input okay, exit loop
} else {
System.out.println("This move at (" + (row + 1) + ","
+ (col + 1) + ") is not valid. Try again...");
}
} while (!validInput); // repeat until input is valid
}
/**
* Update the "currentState" after the player with "theSeed" has placed on
* (currentRow, currentCol).
*/
public static void updateGame(int theSeed, int currentRow, int currentCol) {
if (hasWon(theSeed, currentRow, currentCol)) { // check if winning move
currentState = (theSeed == CROSS) ? CROSS_WON : NOUGHT_WON;
} else if (isDraw()) { // check for draw
currentState = DRAW;
}
// Otherwise, no change to currentState (still PLAYING).
}
/** Return true if it is a draw (no more empty cell) */
// TODO: Shall declare draw if no player can "possibly" win
public static boolean isDraw() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
if (board[row][col] == EMPTY) {
return false; // an empty cell found, not draw, exit
}
}
}
return true; // no empty cell, it's a draw
}
public static boolean hasWon(int theSeed, int currentRow, int currentCol) {
return (board[currentRow][0] == theSeed // 3-in-the-row
&& board[currentRow][1] == theSeed
&& board[currentRow][2] == theSeed
|| board[0][currentCol] == theSeed // 3-in-the-column
&& board[1][currentCol] == theSeed
&& board[2][currentCol] == theSeed
|| currentRow == currentCol // 3-in-the-diagonal
&& board[0][0] == theSeed
&& board[1][1] == theSeed
&& board[2][2] == theSeed || currentRow + currentCol == 2 // 3-in-the-opposite-
diagonal
&& board[0][2] == theSeed
&& board[1][1] == theSeed
&& board[2][0] == theSeed);
}
/** Print the game board */
public static void printBoard() {
for (int row = 0; row < ROWS; ++row) {
for (int col = 0; col < COLS; ++col) {
printCell(board[row][col]); // print each of the cells
if (col != COLS - 1) {
System.out.print("|"); // print vertical partition
}
}
System.out.println();
if (row != ROWS - 1) {
System.out.println("-----------"); // print horizontal partition
}
}
System.out.println();
}
/** Print a cell with the specified "content" */
public static void printCell(int content) {
switch (content) {
case EMPTY:
System.out.print(" ");
break;
case NOUGHT:
System.out.print(" O ");
break;
case CROSS:
System.out.print(" X ");
break;
}
}
}

More Related Content

Similar to In Java using Eclipse, Im suppose to write a class that encapsulat.pdf

Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfhainesburchett26321
 
This is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdfThis is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdfcalderoncasto9163
 
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdfNO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdffms12345
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdfkavithaarp
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfanwarsadath111
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfrajkumarm401
 
import javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfimport javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfADITIEYEWEAR
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfaoneonlinestore1
 
write the TODO part of the program.docx
write the TODO part of the program.docxwrite the TODO part of the program.docx
write the TODO part of the program.docxannetnash8266
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfarchanaemporium
 
GameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdfGameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdfaravlitraders2012
 
include ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfinclude ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfcontact32
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfinfo430661
 

Similar to In Java using Eclipse, Im suppose to write a class that encapsulat.pdf (14)

Need help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdfNeed help writing the code for a basic java tic tac toe game Tic.pdf
Need help writing the code for a basic java tic tac toe game Tic.pdf
 
This is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdfThis is the Java code i have for a Battleship project i am working o.pdf
This is the Java code i have for a Battleship project i am working o.pdf
 
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdfNO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
 
public interface Game Note interface in place of class { .pdf
public interface Game  Note interface in place of class { .pdfpublic interface Game  Note interface in place of class { .pdf
public interface Game Note interface in place of class { .pdf
 
import java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdfimport java.util.Scanner;public class Main {    public static in.pdf
import java.util.Scanner;public class Main {    public static in.pdf
 
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdfObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
ObjectiveCreate a graphical game of minesweeper IN JAVA. The boar.pdf
 
Include
IncludeInclude
Include
 
import javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdfimport javautilLinkedList import javautilQueue import .pdf
import javautilLinkedList import javautilQueue import .pdf
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdfimport java.awt.;import java.awt.event.;import javax.swing.;.pdf
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
 
write the TODO part of the program.docx
write the TODO part of the program.docxwrite the TODO part of the program.docx
write the TODO part of the program.docx
 
I dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdfI dont know what is wrong with this roulette program I cant seem.pdf
I dont know what is wrong with this roulette program I cant seem.pdf
 
GameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdfGameOfLife.cs using System; using System.Collections.Generic;.pdf
GameOfLife.cs using System; using System.Collections.Generic;.pdf
 
include ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdfinclude ltiostreamgt include ltstringgt include .pdf
include ltiostreamgt include ltstringgt include .pdf
 
package com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdfpackage com.tictactoe; public class Main {public void play() {.pdf
package com.tictactoe; public class Main {public void play() {.pdf
 

More from anjandavid

I am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdfI am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdfanjandavid
 
How many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdfHow many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdfanjandavid
 
How are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdfHow are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdfanjandavid
 
Hi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdfHi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdfanjandavid
 
How did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdfHow did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdfanjandavid
 
For problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfFor problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfanjandavid
 
Give an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdfGive an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdfanjandavid
 
Discuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdfDiscuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdfanjandavid
 
E, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdfE, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdfanjandavid
 
Describe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdfDescribe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdfanjandavid
 
Briefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdfBriefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdfanjandavid
 
A student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdfA student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdfanjandavid
 
All answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdfAll answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdfanjandavid
 
Can someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdfCan someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdfanjandavid
 
A polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdfA polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdfanjandavid
 
Why are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdfWhy are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdfanjandavid
 
Which of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdfWhich of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdfanjandavid
 
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdfWhich liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdfanjandavid
 
What is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdfWhat is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdfanjandavid
 
What are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdfWhat are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdfanjandavid
 

More from anjandavid (20)

I am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdfI am exploring the basic components of advanced broadband networks..pdf
I am exploring the basic components of advanced broadband networks..pdf
 
How many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdfHow many different instances of the ls command are installed on .pdf
How many different instances of the ls command are installed on .pdf
 
How are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdfHow are the Allen Bradley SLC 500 program files organizedSolutio.pdf
How are the Allen Bradley SLC 500 program files organizedSolutio.pdf
 
Hi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdfHi, I need help please, this is about KaseyaWich o the following .pdf
Hi, I need help please, this is about KaseyaWich o the following .pdf
 
How did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdfHow did WWI and its aftermath provide African Americans with opportu.pdf
How did WWI and its aftermath provide African Americans with opportu.pdf
 
For problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdfFor problems 3 and 4, consider the following functions that implemen.pdf
For problems 3 and 4, consider the following functions that implemen.pdf
 
Give an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdfGive an example of a system. What are the Components, Attributes,.pdf
Give an example of a system. What are the Components, Attributes,.pdf
 
Discuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdfDiscuss the attribution process and attribution errorsSolution.pdf
Discuss the attribution process and attribution errorsSolution.pdf
 
E, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdfE, an individual, received $40,000 of non-eligible dividends from Ca.pdf
E, an individual, received $40,000 of non-eligible dividends from Ca.pdf
 
Describe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdfDescribe one (1) example in which laws granting freedom of the press.pdf
Describe one (1) example in which laws granting freedom of the press.pdf
 
Briefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdfBriefly discuss 3–5 key trends in the modern health care operation.pdf
Briefly discuss 3–5 key trends in the modern health care operation.pdf
 
A student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdfA student obtained the following data Mass of water in calorimeter 3.pdf
A student obtained the following data Mass of water in calorimeter 3.pdf
 
All answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdfAll answers must be in your own words.What is importance of the Wa.pdf
All answers must be in your own words.What is importance of the Wa.pdf
 
Can someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdfCan someone please fix my code for a hashtable frequencey counter I.pdf
Can someone please fix my code for a hashtable frequencey counter I.pdf
 
A polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdfA polycationic mRNA contains two or more promoter sequences. True Fal.pdf
A polycationic mRNA contains two or more promoter sequences. True Fal.pdf
 
Why are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdfWhy are electrons shared in molecular compoundsWhy are electron.pdf
Why are electrons shared in molecular compoundsWhy are electron.pdf
 
Which of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdfWhich of these isare true of UDPa. It provides reliability, flow-c.pdf
Which of these isare true of UDPa. It provides reliability, flow-c.pdf
 
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdfWhich liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
Which liquid would BaCl Which liquid would BaCl 4. Which liquid.pdf
 
What is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdfWhat is employee involvement What are some of the benefits of invol.pdf
What is employee involvement What are some of the benefits of invol.pdf
 
What are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdfWhat are the pros and cons of technological leader versus technologi.pdf
What are the pros and cons of technological leader versus technologi.pdf
 

Recently uploaded

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 

Recently uploaded (20)

Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 

In Java using Eclipse, Im suppose to write a class that encapsulat.pdf

  • 1. In Java using Eclipse, I'm suppose to write a class that encapsulates a tic tac toe board using two dimensional arrays. It should only involve the human player vs. the computer, and should randomly select who should use 'X' or 'O' and whether the human player or the computer should go first. Verify that all moves by the human player are to a valid space on the tic-tac-toe board, and an incorrect choice should not halt or terminate the game. Below is my Java program that is currently a work in progress. Can you help me remodify it? Thanks. import java.util.Scanner; public class LeavinesTicTacToe { public static Scanner sc = new Scanner(System.in); 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 {
  • 2. 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) {
  • 3. 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();
  • 4. } 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++) {
  • 5. 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;
  • 6. } } Solution Please see below program, I made this few years back . Please follow this and comment if you have any doubts. import java.util.Scanner; public class LeavinesTicTacToeNew { public static final int EMPTY = 0; public static final int CROSS = 1; public static final int NOUGHT = 2; public static final int PLAYING = 0; public static final int DRAW = 1; public static final int CROSS_WON = 2; public static final int NOUGHT_WON = 3; public static final int ROWS = 3, COLS = 3; // number of rows and columns public static int[][] board = new int[ROWS][COLS]; public static int currentState; // the current state of the game public static int currentPlayer; // the current player (CROSS or NOUGHT) public static int currntRow, currentCol; // current seed's row and column public static Scanner in = new Scanner(System.in); // the input Scanner public static void main(String[] args) { // Initialize the game-board and current status resetBoard(); // Play the game once do { playerMove(currentPlayer); // update currentRow and currentCol updateGame(currentPlayer, currntRow, currentCol); // update // currentState printBoard(); // Print message if game-over
  • 7. if (currentState == CROSS_WON) { System.out.println("'X' won! Bye!"); } else if (currentState == NOUGHT_WON) { System.out.println("'O' won! Bye!"); } else if (currentState == DRAW) { System.out.println("It's a Draw! Bye!"); } // Switch player currentPlayer = (currentPlayer == CROSS) ? NOUGHT : CROSS; } while (currentState == PLAYING); // repeat if not game-over } public static void resetBoard() { for (int row = 0; row < ROWS; ++row) { for (int col = 0; col < COLS; ++col) { board[row][col] = EMPTY; // all cells empty } } currentState = PLAYING; // ready to play currentPlayer = CROSS; // cross plays first } public static void playerMove(int theSeed) { boolean validInput = false; // for input validation do { if (theSeed == CROSS) { System.out .print("Player 'X', enter your move (row[1-3] column[1-3]): "); } else { System.out .print("Player 'O', enter your move (row[1-3] column[1-3]): "); } int row = in.nextInt() - 1; // array index starts at 0 instead of 1 int col = in.nextInt() - 1; if (row >= 0 && row < ROWS && col >= 0 && col < COLS && board[row][col] == EMPTY) {
  • 8. currntRow = row; currentCol = col; board[currntRow][currentCol] = theSeed; // update game-board // content validInput = true; // input okay, exit loop } else { System.out.println("This move at (" + (row + 1) + "," + (col + 1) + ") is not valid. Try again..."); } } while (!validInput); // repeat until input is valid } /** * Update the "currentState" after the player with "theSeed" has placed on * (currentRow, currentCol). */ public static void updateGame(int theSeed, int currentRow, int currentCol) { if (hasWon(theSeed, currentRow, currentCol)) { // check if winning move currentState = (theSeed == CROSS) ? CROSS_WON : NOUGHT_WON; } else if (isDraw()) { // check for draw currentState = DRAW; } // Otherwise, no change to currentState (still PLAYING). } /** Return true if it is a draw (no more empty cell) */ // TODO: Shall declare draw if no player can "possibly" win public static boolean isDraw() { for (int row = 0; row < ROWS; ++row) { for (int col = 0; col < COLS; ++col) { if (board[row][col] == EMPTY) { return false; // an empty cell found, not draw, exit } } } return true; // no empty cell, it's a draw } public static boolean hasWon(int theSeed, int currentRow, int currentCol) {
  • 9. return (board[currentRow][0] == theSeed // 3-in-the-row && board[currentRow][1] == theSeed && board[currentRow][2] == theSeed || board[0][currentCol] == theSeed // 3-in-the-column && board[1][currentCol] == theSeed && board[2][currentCol] == theSeed || currentRow == currentCol // 3-in-the-diagonal && board[0][0] == theSeed && board[1][1] == theSeed && board[2][2] == theSeed || currentRow + currentCol == 2 // 3-in-the-opposite- diagonal && board[0][2] == theSeed && board[1][1] == theSeed && board[2][0] == theSeed); } /** Print the game board */ public static void printBoard() { for (int row = 0; row < ROWS; ++row) { for (int col = 0; col < COLS; ++col) { printCell(board[row][col]); // print each of the cells if (col != COLS - 1) { System.out.print("|"); // print vertical partition } } System.out.println(); if (row != ROWS - 1) { System.out.println("-----------"); // print horizontal partition } } System.out.println(); } /** Print a cell with the specified "content" */ public static void printCell(int content) { switch (content) { case EMPTY: System.out.print(" ");
  • 10. break; case NOUGHT: System.out.print(" O "); break; case CROSS: System.out.print(" X "); break; } } }