SlideShare a Scribd company logo
The main class of the tictoe game looks like.
public class Main {
public void play() {
TicTacToe game = new TicTacToe();
System.out.println("Welcome! Tic Tac Toe is a two player game.");
System.out.print("Enter player one's name: ");
game.setPlayer1(game.getPrompt());
System.out.print("Enter player two's name: ");
game.setPlayer2(game.getPrompt());
boolean markerOk = false;
while (!markerOk) {
System.out.print("Select any letter as " + game.getPlayer1() + "'s marker: ");
String marker = game.getPrompt();
if (marker.length() == 1 &&
Character.isLetter(marker.toCharArray()[0])) {
markerOk = true;
game.setMarker1(marker.toCharArray()[0]);
} else {
System.out.println("Invalid marker, try again");
}
}
markerOk = false;
while (!markerOk) {
System.out.print("Select any letter as " + game.getPlayer2() + "'s marker: ");
String marker = game.getPrompt();
if (marker.length() == 1 &&
Character.isLetter(marker.toCharArray()[0])) {
markerOk = true;
game.setMarker2(marker.toCharArray()[0]);
} else {
System.out.println("Invalid marker, try again");
}
}
boolean continuePlaying = true;
while (continuePlaying) {
game.init();
System.out.println();
System.out.println(game.getRules());
System.out.println();
System.out.println(game.drawBoard());
System.out.println();
String player = null;
while (!game.winner() && game.getPlays() < 9) {
player = game.getCurrentPlayer() == 1 ? game.getPlayer1() : game.getPlayer2();
boolean validPick = false;
while (!validPick) {
System.out.print("It is " + player + "'s turn. Pick a square: ");
String square = game.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 = game.placeMarker(pick);
}
if (!validPick) {
System.out.println("Square can not be selected. Retry");
}
}
game.switchPlayers();
System.out.println();
System.out.println(game.drawBoard());
System.out.println();
}
if (game.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 = game.getPrompt();
if (!choice.equalsIgnoreCase("Y")) {
continuePlaying = false;
}
}
}
public static void main(String[] args) {
Main main = new Main();
main.play();
}
}
The TicTacToe class code will be like
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* author Iamavinashkotina
*/
public class TicTacToe {
private char[][] board = new char[3][3];
private String player1;
private String player2;
private int currentPlayer;
private char marker1;
private char marker2;
private int plays;
private BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
protected void init() {
int counter = 0;
for (int i = 0; i < 3; i++) {
for (int i1 = 0; i1 < 3; i1++) {
board[i][i1] = Character.forDigit(++counter, 10);
}
}
currentPlayer = 1;
plays = 0;
}
protected void switchPlayers() {
if (getCurrentPlayer() == 1) {
setCurrentPlayer(2);
} else {
setCurrentPlayer(1);
}
setPlays(getPlays() + 1);
}
protected boolean placeMarker(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] = (getCurrentPlayer() == 1) ? getMarker1() : getMarker2();
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  ");
builder.append("not already marked can be picked. Once a player has  ");
builder.append("marked three squares in a row, the player wins! If all squares  ");
builder.append("are marked and no three squares are the same, a tie game is declared. ");
builder.append("Have Fun!   ");
return builder.toString();
}
protected String getPrompt() {
String prompt = "";
try {
prompt = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return prompt;
}
protected String drawBoard() {
StringBuilder builder = new StringBuilder("Game board:  ");
for (int i = 0; i < 3; i++) {
for (int i1 = 0; i1 < 3; i1++) {
builder.append("[" + board[i][i1] + "]");
}
builder.append(" ");
}
return builder.toString();
}
public int getCurrentPlayer() {
return currentPlayer;
}
public void setCurrentPlayer(int currentPlayer) {
this.currentPlayer = currentPlayer;
}
public char getMarker1() {
return marker1;
}
public void setMarker1(char marker1) {
this.marker1 = marker1;
}
public char getMarker2() {
return marker2;
}
public void setMarker2(char marker2) {
this.marker2 = marker2;
}
public int getPlays() {
return plays;
}
public void setPlays(int plays) {
this.plays = plays;
}
public String getPlayer1() {
return player1;
}
public void setPlayer1(String player1) {
this.player1 = player1;
}
public String getPlayer2() {
return player2;
}
public void setPlayer2(String player2) {
this.player2 = player2;
}
}
Solution
The main class of the tictoe game looks like.
public class Main {
public void play() {
TicTacToe game = new TicTacToe();
System.out.println("Welcome! Tic Tac Toe is a two player game.");
System.out.print("Enter player one's name: ");
game.setPlayer1(game.getPrompt());
System.out.print("Enter player two's name: ");
game.setPlayer2(game.getPrompt());
boolean markerOk = false;
while (!markerOk) {
System.out.print("Select any letter as " + game.getPlayer1() + "'s marker: ");
String marker = game.getPrompt();
if (marker.length() == 1 &&
Character.isLetter(marker.toCharArray()[0])) {
markerOk = true;
game.setMarker1(marker.toCharArray()[0]);
} else {
System.out.println("Invalid marker, try again");
}
}
markerOk = false;
while (!markerOk) {
System.out.print("Select any letter as " + game.getPlayer2() + "'s marker: ");
String marker = game.getPrompt();
if (marker.length() == 1 &&
Character.isLetter(marker.toCharArray()[0])) {
markerOk = true;
game.setMarker2(marker.toCharArray()[0]);
} else {
System.out.println("Invalid marker, try again");
}
}
boolean continuePlaying = true;
while (continuePlaying) {
game.init();
System.out.println();
System.out.println(game.getRules());
System.out.println();
System.out.println(game.drawBoard());
System.out.println();
String player = null;
while (!game.winner() && game.getPlays() < 9) {
player = game.getCurrentPlayer() == 1 ? game.getPlayer1() : game.getPlayer2();
boolean validPick = false;
while (!validPick) {
System.out.print("It is " + player + "'s turn. Pick a square: ");
String square = game.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 = game.placeMarker(pick);
}
if (!validPick) {
System.out.println("Square can not be selected. Retry");
}
}
game.switchPlayers();
System.out.println();
System.out.println(game.drawBoard());
System.out.println();
}
if (game.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 = game.getPrompt();
if (!choice.equalsIgnoreCase("Y")) {
continuePlaying = false;
}
}
}
public static void main(String[] args) {
Main main = new Main();
main.play();
}
}
The TicTacToe class code will be like
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* author Iamavinashkotina
*/
public class TicTacToe {
private char[][] board = new char[3][3];
private String player1;
private String player2;
private int currentPlayer;
private char marker1;
private char marker2;
private int plays;
private BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
protected void init() {
int counter = 0;
for (int i = 0; i < 3; i++) {
for (int i1 = 0; i1 < 3; i1++) {
board[i][i1] = Character.forDigit(++counter, 10);
}
}
currentPlayer = 1;
plays = 0;
}
protected void switchPlayers() {
if (getCurrentPlayer() == 1) {
setCurrentPlayer(2);
} else {
setCurrentPlayer(1);
}
setPlays(getPlays() + 1);
}
protected boolean placeMarker(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] = (getCurrentPlayer() == 1) ? getMarker1() : getMarker2();
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  ");
builder.append("not already marked can be picked. Once a player has  ");
builder.append("marked three squares in a row, the player wins! If all squares  ");
builder.append("are marked and no three squares are the same, a tie game is declared. ");
builder.append("Have Fun!   ");
return builder.toString();
}
protected String getPrompt() {
String prompt = "";
try {
prompt = reader.readLine();
} catch (IOException ex) {
ex.printStackTrace();
}
return prompt;
}
protected String drawBoard() {
StringBuilder builder = new StringBuilder("Game board:  ");
for (int i = 0; i < 3; i++) {
for (int i1 = 0; i1 < 3; i1++) {
builder.append("[" + board[i][i1] + "]");
}
builder.append(" ");
}
return builder.toString();
}
public int getCurrentPlayer() {
return currentPlayer;
}
public void setCurrentPlayer(int currentPlayer) {
this.currentPlayer = currentPlayer;
}
public char getMarker1() {
return marker1;
}
public void setMarker1(char marker1) {
this.marker1 = marker1;
}
public char getMarker2() {
return marker2;
}
public void setMarker2(char marker2) {
this.marker2 = marker2;
}
public int getPlays() {
return plays;
}
public void setPlays(int plays) {
this.plays = plays;
}
public String getPlayer1() {
return player1;
}
public void setPlayer1(String player1) {
this.player1 = player1;
}
public String getPlayer2() {
return player2;
}
public void setPlayer2(String player2) {
this.player2 = player2;
}
}

More Related Content

PDF
package com.tictactoe; public class Main {public void play() {.pdf
info430661
 
PDF
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
anjandavid
 
PDF
Here is the code for youimport java.util.Scanner; import java.u.pdf
anithareadymade
 
PDF
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
preetajain
 
PDF
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
jeeteshmalani1
 
PDF
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
fms12345
 
PDF
201707 CSE110 Lecture 13
Javier Gonzalez-Sanchez
 
PDF
create a Tic Tac Toe game using JSP Scripting elements and a JSP pag.pdf
duttakajal70
 
package com.tictactoe; public class Main {public void play() {.pdf
info430661
 
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
anjandavid
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
anithareadymade
 
import tio.;class TicTacToe {static final int EMPTY = 0;stati.pdf
preetajain
 
Can someone help me setup this in JAVA Im new to java. Thanks.pdf
jeeteshmalani1
 
NO PAPER ANSWERS. ALL ANSWER SUBMISSIONS SHOULD BE ABLE TO RUN WIT.pdf
fms12345
 
201707 CSE110 Lecture 13
Javier Gonzalez-Sanchez
 
create a Tic Tac Toe game using JSP Scripting elements and a JSP pag.pdf
duttakajal70
 

Similar to The main class of the tictoe game looks like.public class Main {.pdf (20)

PDF
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
infomalad
 
PDF
Please follow the data 1) For Line 23 In the IF - Condition yo.pdf
info382133
 
PDF
Please help with this. program must be written in C# .. All of the g.pdf
manjan6
 
PDF
import java.util.Scanner;public category Main public Boolean c.pdf
ARYAN20071
 
PDF
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
eyewaregallery
 
PDF
import java.util.Scanner; import java.util.Random; public clas.pdf
annaipowerelectronic
 
PDF
MineSweeper.java public class MS { public static void main(Strin.pdf
aniyathikitchen
 
TXT
Tic tac toe
jo pakson
 
PDF
Need help writing the code for a basic java tic tac toe game Tic.pdf
hainesburchett26321
 
PDF
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
aoneonlinestore1
 
DOCX
This is an individual project, to be completed on your own. It i.docx
abhi353063
 
PDF
import javautilLinkedList import javautilQueue import .pdf
ADITIEYEWEAR
 
PDF
java code please Add event handlers to the buttons in your TicTacToe.pdf
ezzi97
 
PDF
question.(player, entity ,field and base.java codes are given)Stop.pdf
shahidqamar17
 
PDF
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
fms12345
 
DOCX
3 1-1
nima_91
 
PDF
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
formaxekochi
 
DOCX
TilePUzzle class Anderson, Franceschi public class TilePu.docx
Komlin1
 
DOCX
Tic tac toe
KrishanKantGupta5
 
Tic Tac Toe game with GUI written in java.SolutionAnswerimp.pdf
infomalad
 
Please follow the data 1) For Line 23 In the IF - Condition yo.pdf
info382133
 
Please help with this. program must be written in C# .. All of the g.pdf
manjan6
 
import java.util.Scanner;public category Main public Boolean c.pdf
ARYAN20071
 
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
eyewaregallery
 
import java.util.Scanner; import java.util.Random; public clas.pdf
annaipowerelectronic
 
MineSweeper.java public class MS { public static void main(Strin.pdf
aniyathikitchen
 
Tic tac toe
jo pakson
 
Need help writing the code for a basic java tic tac toe game Tic.pdf
hainesburchett26321
 
import java.awt.;import java.awt.event.;import javax.swing.;.pdf
aoneonlinestore1
 
This is an individual project, to be completed on your own. It i.docx
abhi353063
 
import javautilLinkedList import javautilQueue import .pdf
ADITIEYEWEAR
 
java code please Add event handlers to the buttons in your TicTacToe.pdf
ezzi97
 
question.(player, entity ,field and base.java codes are given)Stop.pdf
shahidqamar17
 
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
fms12345
 
3 1-1
nima_91
 
Tic Tac Toe game with GUI please dont copy and paste from google. .pdf
formaxekochi
 
TilePUzzle class Anderson, Franceschi public class TilePu.docx
Komlin1
 
Tic tac toe
KrishanKantGupta5
 
Ad

More from asif1401 (20)

PDF
the reaction of A to B since its Ea is the highes.pdf
asif1401
 
PDF
the one thing that comes to mind for me is about .pdf
asif1401
 
PDF
#includeiostream#includestdlib.husing namespace std;class .pdf
asif1401
 
PDF
(1) Acid rain occurs when the gases SO2 ,NOx react with water,oxygen.pdf
asif1401
 
PDF
Iodine will replace both Cl and Br It will be SN2.pdf
asif1401
 
PDF
The number of outcomes in the event A is 4 Yes event A is a s.pdf
asif1401
 
PDF
There were very few planetary leftovers in this r.pdf
asif1401
 
PDF
i have no idea. im just seeing if i get karma p.pdf
asif1401
 
PDF
Fe+3 solution is more acidic because it produces .pdf
asif1401
 
PDF
Copper chloride. Copper ions will form precipitat.pdf
asif1401
 
PDF
   CCl4 molecule can give IR and Raman spectroscopy.   Selection r.pdf
asif1401
 
PDF
User interface design processNavigation DesignInput DesignOu.pdf
asif1401
 
PDF
True.it  is an example of an independent-measures designSolution.pdf
asif1401
 
PDF
the inner electronsSolutionthe inner electrons.pdf
asif1401
 
PDF
SolutionThe investees net income should be recorded as an increa.pdf
asif1401
 
PDF
QuestionAnswer1TrueThe corpus callosum , otherwise called th.pdf
asif1401
 
PDF
No. of Moles = Given MassMolecular Mass=3.0 x 101398= 3.06101.pdf
asif1401
 
PDF
Let the sample size be n ,Mean of the sample = 27 (same as pop.pdf
asif1401
 
PDF
JeffSolutionJeff.pdf
asif1401
 
PDF
import java.util.Scanner;public class Assignment4 {    public st.pdf
asif1401
 
the reaction of A to B since its Ea is the highes.pdf
asif1401
 
the one thing that comes to mind for me is about .pdf
asif1401
 
#includeiostream#includestdlib.husing namespace std;class .pdf
asif1401
 
(1) Acid rain occurs when the gases SO2 ,NOx react with water,oxygen.pdf
asif1401
 
Iodine will replace both Cl and Br It will be SN2.pdf
asif1401
 
The number of outcomes in the event A is 4 Yes event A is a s.pdf
asif1401
 
There were very few planetary leftovers in this r.pdf
asif1401
 
i have no idea. im just seeing if i get karma p.pdf
asif1401
 
Fe+3 solution is more acidic because it produces .pdf
asif1401
 
Copper chloride. Copper ions will form precipitat.pdf
asif1401
 
   CCl4 molecule can give IR and Raman spectroscopy.   Selection r.pdf
asif1401
 
User interface design processNavigation DesignInput DesignOu.pdf
asif1401
 
True.it  is an example of an independent-measures designSolution.pdf
asif1401
 
the inner electronsSolutionthe inner electrons.pdf
asif1401
 
SolutionThe investees net income should be recorded as an increa.pdf
asif1401
 
QuestionAnswer1TrueThe corpus callosum , otherwise called th.pdf
asif1401
 
No. of Moles = Given MassMolecular Mass=3.0 x 101398= 3.06101.pdf
asif1401
 
Let the sample size be n ,Mean of the sample = 27 (same as pop.pdf
asif1401
 
JeffSolutionJeff.pdf
asif1401
 
import java.util.Scanner;public class Assignment4 {    public st.pdf
asif1401
 
Ad

Recently uploaded (20)

PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PROTIEN ENERGY MALNUTRITION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 

The main class of the tictoe game looks like.public class Main {.pdf

  • 1. The main class of the tictoe game looks like. public class Main { public void play() { TicTacToe game = new TicTacToe(); System.out.println("Welcome! Tic Tac Toe is a two player game."); System.out.print("Enter player one's name: "); game.setPlayer1(game.getPrompt()); System.out.print("Enter player two's name: "); game.setPlayer2(game.getPrompt()); boolean markerOk = false; while (!markerOk) { System.out.print("Select any letter as " + game.getPlayer1() + "'s marker: "); String marker = game.getPrompt(); if (marker.length() == 1 && Character.isLetter(marker.toCharArray()[0])) { markerOk = true; game.setMarker1(marker.toCharArray()[0]); } else { System.out.println("Invalid marker, try again"); } } markerOk = false; while (!markerOk) { System.out.print("Select any letter as " + game.getPlayer2() + "'s marker: "); String marker = game.getPrompt(); if (marker.length() == 1 && Character.isLetter(marker.toCharArray()[0])) { markerOk = true; game.setMarker2(marker.toCharArray()[0]); } else { System.out.println("Invalid marker, try again"); }
  • 2. } boolean continuePlaying = true; while (continuePlaying) { game.init(); System.out.println(); System.out.println(game.getRules()); System.out.println(); System.out.println(game.drawBoard()); System.out.println(); String player = null; while (!game.winner() && game.getPlays() < 9) { player = game.getCurrentPlayer() == 1 ? game.getPlayer1() : game.getPlayer2(); boolean validPick = false; while (!validPick) { System.out.print("It is " + player + "'s turn. Pick a square: "); String square = game.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 = game.placeMarker(pick); } if (!validPick) { System.out.println("Square can not be selected. Retry"); } } game.switchPlayers(); System.out.println(); System.out.println(game.drawBoard());
  • 3. System.out.println(); } if (game.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 = game.getPrompt(); if (!choice.equalsIgnoreCase("Y")) { continuePlaying = false; } } } public static void main(String[] args) { Main main = new Main(); main.play(); } } The TicTacToe class code will be like import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * author Iamavinashkotina */ public class TicTacToe { private char[][] board = new char[3][3]; private String player1; private String player2; private int currentPlayer; private char marker1;
  • 4. private char marker2; private int plays; private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); protected void init() { int counter = 0; for (int i = 0; i < 3; i++) { for (int i1 = 0; i1 < 3; i1++) { board[i][i1] = Character.forDigit(++counter, 10); } } currentPlayer = 1; plays = 0; } protected void switchPlayers() { if (getCurrentPlayer() == 1) { setCurrentPlayer(2); } else { setCurrentPlayer(1); } setPlays(getPlays() + 1); } protected boolean placeMarker(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] = (getCurrentPlayer() == 1) ? getMarker1() : getMarker2(); return true; } } } return false; }
  • 5. 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
  • 6. 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 "); builder.append("not already marked can be picked. Once a player has "); builder.append("marked three squares in a row, the player wins! If all squares "); builder.append("are marked and no three squares are the same, a tie game is declared. "); builder.append("Have Fun! "); return builder.toString(); } protected String getPrompt() { String prompt = ""; try { prompt = reader.readLine(); } catch (IOException ex) { ex.printStackTrace(); } return prompt; }
  • 7. protected String drawBoard() { StringBuilder builder = new StringBuilder("Game board: "); for (int i = 0; i < 3; i++) { for (int i1 = 0; i1 < 3; i1++) { builder.append("[" + board[i][i1] + "]"); } builder.append(" "); } return builder.toString(); } public int getCurrentPlayer() { return currentPlayer; } public void setCurrentPlayer(int currentPlayer) { this.currentPlayer = currentPlayer; } public char getMarker1() { return marker1; } public void setMarker1(char marker1) { this.marker1 = marker1; } public char getMarker2() { return marker2; } public void setMarker2(char marker2) { this.marker2 = marker2; } public int getPlays() {
  • 8. return plays; } public void setPlays(int plays) { this.plays = plays; } public String getPlayer1() { return player1; } public void setPlayer1(String player1) { this.player1 = player1; } public String getPlayer2() { return player2; } public void setPlayer2(String player2) { this.player2 = player2; } } Solution The main class of the tictoe game looks like. public class Main { public void play() { TicTacToe game = new TicTacToe(); System.out.println("Welcome! Tic Tac Toe is a two player game."); System.out.print("Enter player one's name: "); game.setPlayer1(game.getPrompt());
  • 9. System.out.print("Enter player two's name: "); game.setPlayer2(game.getPrompt()); boolean markerOk = false; while (!markerOk) { System.out.print("Select any letter as " + game.getPlayer1() + "'s marker: "); String marker = game.getPrompt(); if (marker.length() == 1 && Character.isLetter(marker.toCharArray()[0])) { markerOk = true; game.setMarker1(marker.toCharArray()[0]); } else { System.out.println("Invalid marker, try again"); } } markerOk = false; while (!markerOk) { System.out.print("Select any letter as " + game.getPlayer2() + "'s marker: "); String marker = game.getPrompt(); if (marker.length() == 1 && Character.isLetter(marker.toCharArray()[0])) { markerOk = true; game.setMarker2(marker.toCharArray()[0]); } else { System.out.println("Invalid marker, try again"); } } boolean continuePlaying = true; while (continuePlaying) { game.init(); System.out.println(); System.out.println(game.getRules()); System.out.println(); System.out.println(game.drawBoard());
  • 10. System.out.println(); String player = null; while (!game.winner() && game.getPlays() < 9) { player = game.getCurrentPlayer() == 1 ? game.getPlayer1() : game.getPlayer2(); boolean validPick = false; while (!validPick) { System.out.print("It is " + player + "'s turn. Pick a square: "); String square = game.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 = game.placeMarker(pick); } if (!validPick) { System.out.println("Square can not be selected. Retry"); } } game.switchPlayers(); System.out.println(); System.out.println(game.drawBoard()); System.out.println(); } if (game.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 = game.getPrompt(); if (!choice.equalsIgnoreCase("Y")) {
  • 11. continuePlaying = false; } } } public static void main(String[] args) { Main main = new Main(); main.play(); } } The TicTacToe class code will be like import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * author Iamavinashkotina */ public class TicTacToe { private char[][] board = new char[3][3]; private String player1; private String player2; private int currentPlayer; private char marker1; private char marker2; private int plays; private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); protected void init() { int counter = 0; for (int i = 0; i < 3; i++) { for (int i1 = 0; i1 < 3; i1++) { board[i][i1] = Character.forDigit(++counter, 10); }
  • 12. } currentPlayer = 1; plays = 0; } protected void switchPlayers() { if (getCurrentPlayer() == 1) { setCurrentPlayer(2); } else { setCurrentPlayer(1); } setPlays(getPlays() + 1); } protected boolean placeMarker(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] = (getCurrentPlayer() == 1) ? getMarker1() : getMarker2(); 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) {
  • 13. 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) {
  • 14. return true; } return false; } protected String getRules() { StringBuilder builder = new StringBuilder(); builder.append("Players take turns marking a square. Only squares "); builder.append("not already marked can be picked. Once a player has "); builder.append("marked three squares in a row, the player wins! If all squares "); builder.append("are marked and no three squares are the same, a tie game is declared. "); builder.append("Have Fun! "); return builder.toString(); } protected String getPrompt() { String prompt = ""; try { prompt = reader.readLine(); } catch (IOException ex) { ex.printStackTrace(); } return prompt; } protected String drawBoard() { StringBuilder builder = new StringBuilder("Game board: "); for (int i = 0; i < 3; i++) { for (int i1 = 0; i1 < 3; i1++) { builder.append("[" + board[i][i1] + "]"); } builder.append(" "); } return builder.toString(); }
  • 15. public int getCurrentPlayer() { return currentPlayer; } public void setCurrentPlayer(int currentPlayer) { this.currentPlayer = currentPlayer; } public char getMarker1() { return marker1; } public void setMarker1(char marker1) { this.marker1 = marker1; } public char getMarker2() { return marker2; } public void setMarker2(char marker2) { this.marker2 = marker2; } public int getPlays() { return plays; } public void setPlays(int plays) { this.plays = plays; } public String getPlayer1() { return player1; }
  • 16. public void setPlayer1(String player1) { this.player1 = player1; } public String getPlayer2() { return player2; } public void setPlayer2(String player2) { this.player2 = player2; } }