In: Computer Science
Write a class (and a client class to test it) that encapsulates a tic-tac-toe board. A tic-tac-toe board looks like a table of three rows and three columns partially or completely filled with the characters X and O. At any point, a cell of that table could be empty or could contain an X or an O. You should have one instance variable, a two-dimensional array of values representing the tic-tac-toe board.
This game should involve one human player vs. the computer. At the start of each game, randomly select if the computer will play X or O and who (i.e. human or computer) will make the first move.
Your default constructor should instantiate the array so that it represents an empty board.
You should include the following methods:
*a method that generates a valid play by the computer and displays the board after each play. *
a method that requests a valid play from the human and displays the board after each play.
*a method to display the tic-tac-toe board. a method checking if a player has won based on the contents of the board; this method takes no parameter. It returns X if the "X player" has won, O if the "O player" has won, T if the game was a tie. A player wins if he or she has placed an X (or an O) in all cells in a row, all cells in a column, or all cells in one of the diagonals.
NOTE: Be sure to display the board after each move. You must provide clear prompts for the human player to select a space on the tic-tac-toe board.
Input Validation: Verify that all moves by the human player are to a valid space on the tic-tac-toe board. An incorrect choice should not halt or terminate the game.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TicTacToeGame {
private char[][] board = new char[3][3];
private String playername1;
private String playername2;
private int currentplayingPlayer;
private char markerpoint1;
private char markerpoint2;
private int noplays;
private BufferedReader bufferedreader = new
BufferedReader(
new
InputStreamReader(System.in));
protected void init() {
int counter = 0;
for (int i = 0; i < 3; i++)
{
for (int j1 = 0;
j1 < 3; j1++) {
board[i][j1] = Character.forDigit(++counter,
10);
}
}
currentplayingPlayer = 1;
noplays = 0;
}
protected void switchPlayers() {
if (getCurrentplayingPlayer() == 1)
{
setCurrentplayingPlayer(2);
} else {
setCurrentplayingPlayer(1);
}
setNoplays(getNoplays() + 1);
}
protected boolean placeMarkerpoint(int play)
{
for (int i = 0; i < 3; i++)
{
for (int i1 = 0;
i1 < 3; i1++) {
if (board[i][i1] == Character.forDigit(play,
10)) {
board[i][i1] =
(getCurrentplayingPlayer() == 1) ? getMarkerpoint1()
: getMarkerpoint2();
return true;
}
}
}
return false;
}
protected boolean winner() {
// Checking rows
char current = ' ';
for (int i = 0; i < 3; i++)
{
int i1 =
0;
for (i1 = 0; i1
< 3; i1++) {
if (!Character.isLetter(board[i][i1])) {
break;
}
if (i1 == 0) {
current = board[i][i1];
} else if (current != board[i][i1]) {
break;
}
if (i1 == 2) {
// Found winner
return true;
}
}
}
// Checking columns
for (int i = 0; i < 3; i++)
{
current = '
';
int i1 =
0;
for (i1 = 0; i1
< 3; i1++) {
if (!Character.isLetter(board[i1][i])) {
break;
}
if (i1 == 0) {
current = board[i1][i];
} else if (current != board[i1][i]) {
break;
}
if (i1 == 2) {
// Found winner
return true;
}
}
}
// Checking diagonals
current = board[0][0];
if (Character.isLetter(current)
&& board[1][1] == current
&& board[2][2] == current) {
return
true;
}
current = board[2][0];
if (Character.isLetter(current)
&& board[1][1] == current
&& board[0][2] == current) {
return
true;
}
return false;
}
protected String getRules() {
StringBuilder builder = new
StringBuilder();
builder.append("Players take turns
marking a square. Only squares \n");
builder.append("not already marked
can be picked. Once a player has \n");
builder.append("marked three
squares in a row, the player wins! If all squares \n");
builder.append("are marked and no
three squares are the same, a tie game is declared.\n");
builder.append("Have Fun!
\n\n");
return builder.toString();
}
protected String getPrompt() {
String prompting = "";
try {
prompting =
bufferedreader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return prompting;
}
protected String drawBoard() {
StringBuilder stringbuilder = new
StringBuilder(
"tic tac toe Game board: \n");
for (int i = 0; i < 3; i++)
{
for (int i1 = 0;
i1 < 3; i1++) {
stringbuilder.append("[" + board[i][i1] +
"]");
}
stringbuilder.append("\n");
}
return
stringbuilder.toString();
}
public String getPlayername1() {
return playername1;
}
public void setPlayername1(String playername1)
{
this.playername1 =
playername1;
}
public String getPlayername2() {
return playername2;
}
public void setPlayername2(String playername2)
{
this.playername2 =
playername2;
}
public char getMarkerpoint1() {
return markerpoint1;
}
public void setMarkerpoint1(char markerpoint1)
{
this.markerpoint1 =
markerpoint1;
}
public char getMarkerpoint2() {
return markerpoint2;
}
public void setMarkerpoint2(char markerpoint2)
{
this.markerpoint2 =
markerpoint2;
}
public int getCurrentplayingPlayer() {
return currentplayingPlayer;
}
public void setCurrentplayingPlayer(int
currentplayingPlayer) {
this.currentplayingPlayer =
currentplayingPlayer;
}
public int getNoplays() {
return noplays;
}
public void setNoplays(int noplays) {
this.noplays = noplays;
}
}
public class TicTacToeGameMain {
public void play() {
TicTacToeGame maingame = new TicTacToeGame();
System.out.println("Welcome! Tic
Tac Toe is a two player game.");
System.out.print("Enter player
one's name: ");
maingame.setPlayername1(maingame.getPrompt());
System.out.print("Enter player
two's name: ");
maingame.setPlayername2(maingame.getPrompt());
boolean markerpointOk =
false;
while (!markerpointOk) {
System.out.print("Select any letter as "
+ maingame.getPlayername1() +
"'s marker: ");
String
markerpoint = maingame.getPrompt();
if
(markerpoint.length() == 1
&&
Character.isLetter(markerpoint.toCharArray()[0])) {
markerpointOk = true;
maingame.setMarkerpoint1(markerpoint.toCharArray()[0]);
} else {
System.out.println("Invalid marker, try
again");
}
}
markerpointOk = false;
while (!markerpointOk) {
System.out.print("Select any letter as "
+ maingame.getPlayername2() +
"'s marker: ");
String
markerpoint2 = maingame.getPrompt();
if
(markerpoint2.length() == 1
&&
Character.isLetter(markerpoint2.toCharArray()[0])) {
markerpointOk = true;
maingame.setMarkerpoint2(markerpoint2.toCharArray()[0]);
} else {
System.out.println("Invalid marker, try
again");
}
}
boolean continuePlaying = true;
while (continuePlaying) {
maingame.init();
System.out.println();
System.out.println(maingame.getRules());
System.out.println();
System.out.println(maingame.drawBoard());
System.out.println();
String player
= null;
while
(!maingame.winner() && maingame.getNoplays() < 9)
{
player = maingame.getCurrentplayingPlayer() == 1
? maingame
.getPlayername1() : maingame.getPlayername2();
boolean validPick = false;
while (!validPick) {
System.out.print("It is " +
player
+ "'s turn. Pick a square: ");
String square =
maingame.getPrompt();
if (square.length() ==
1
&&
Character.isDigit(square.toCharArray()[0])) {
int pick =
0;
try
{
pick = Integer.parseInt(square);
} catch
(NumberFormatException e) {
// Do nothing here, it'll evaluate as an
invalid
// pick on the next row.
}
validPick
= maingame.placeMarkerpoint(pick);
}
if (!validPick) {
System.out.println("Square can not be selected. Retry");
}
}
maingame.switchPlayers();
System.out.println();
System.out.println(maingame.drawBoard());
System.out.println();
}
if
(maingame.winner()) {
System.out.println("Game Over - " + player + "
WINS!!!");
} else {
System.out.println("Game Over - Draw");
}
System.out.println();
System.out.print("Play again? (Y/N): ");
String choice =
maingame.getPrompt();
if
(!choice.equalsIgnoreCase("Y")) {
continuePlaying = false;
}
}
}
/**
* @param args
* the command line arguments
*/
public static void main(String[] args) {
TicTacToeGameMain mainclass = new
TicTacToeGameMain();
mainclass.play();
}
}
output
Welcome! Tic Tac Toe is a two player game.
Enter player one's name: mark
Enter player two's name: smith
Select any letter as mark's marker: x
Select any letter as smith's marker: o
Players take turns marking a square. Only squares
not already marked can be picked. Once a player has
marked three squares in a row, the player wins! If all
squares
are marked and no three squares are the same, a tie game is
declared.
Have Fun!
tic tac toe Game board:
[1][2][3]
[4][5][6]
[7][8][9]
It is mark's turn. Pick a square: 1
tic tac toe Game board:
[x][2][3]
[4][5][6]
[7][8][9]
It is smith's turn. Pick a square: 2
tic tac toe Game board:
[x][o][3]
[4][5][6]
[7][8][9]
It is mark's turn. Pick a square: 3
tic tac toe Game board:
[x][o][x]
[4][5][6]
[7][8][9]
It is smith's turn. Pick a square: 5
tic tac toe Game board:
[x][o][x]
[4][o][6]
[7][8][9]
It is mark's turn. Pick a square: 6
tic tac toe Game board:
[x][o][x]
[4][o][x]
[7][8][9]
It is smith's turn. Pick a square: 7
tic tac toe Game board:
[x][o][x]
[4][o][x]
[o][8][9]
It is mark's turn. Pick a square: 8
tic tac toe Game board:
[x][o][x]
[4][o][x]
[o][x][9]
It is smith's turn. Pick a square: 9
tic tac toe Game board:
[x][o][x]
[4][o][x]
[o][x][o]
It is mark's turn. Pick a square: 4
tic tac toe Game board:
[x][o][x]
[x][o][x]
[o][x][o]
Game Over - Draw
Play again? (Y/N): y
Players take turns marking a square. Only squares
not already marked can be picked. Once a player has
marked three squares in a row, the player wins! If all
squares
are marked and no three squares are the same, a tie game is
declared.
Have Fun!
tic tac toe Game board:
[1][2][3]
[4][5][6]
[7][8][9]
It is mark's turn. Pick a square: 1
tic tac toe Game board:
[x][2][3]
[4][5][6]
[7][8][9]
It is smith's turn. Pick a square: 2
tic tac toe Game board:
[x][o][3]
[4][5][6]
[7][8][9]
It is mark's turn. Pick a square: 3
tic tac toe Game board:
[x][o][x]
[4][5][6]
[7][8][9]
It is smith's turn. Pick a square: 5
tic tac toe Game board:
[x][o][x]
[4][o][6]
[7][8][9]
It is mark's turn. Pick a square: 6
tic tac toe Game board:
[x][o][x]
[4][o][x]
[7][8][9]
It is smith's turn. Pick a square: 8
tic tac toe Game board:
[x][o][x]
[4][o][x]
[7][o][9]
Game Over - smith WINS!!!
Play again? (Y/N): n