April 14, 2020

How to make the Tic Tac Toe Game a two player | Java source code

We have already developed a code for Tic Tac Toe Game. For making the code to a two player game, we need to make one simple modification in TicTacToe.Java file

Create a new method

private void getUserMove(int rowMoved, int colMoved, char currentMove) throws IllegalAccessException {
Scanner scanner = null;
scanner = new Scanner(System.in);
System.out.println(" *** THE USER :  " + currentMove + " MOVE *** ");
System.out.println(" Enter the row (values from 0 to 2): ");
int row = scanner.nextInt();
validate(row);
System.out.println(" Enter the col (values from 0 to 2): ");
int col = scanner.nextInt();
validate(col);
matrix.add(row, col, currentMove);
rowMoved = row;
colMoved = col;
}


Change the following method


@SuppressWarnings("resource")
public void startGame() throws IllegalAccessException {

int rowMoved = 0;
int colMoved = 0;

while (moveCount < MAX_MOVE) {

if (moveCount % 2 == 0) {

if (isTwoPlayer) {
getUserMove(rowMoved, colMoved, COMP_MOVE);
} else {
matrix = computerMove.computerMove(rowMoved, colMoved);
System.out.println("** COMPUTER MOVE **");
try {
Thread.sleep(3121);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

} else {
getUserMove(rowMoved, colMoved, USER_MOVE);
}
matrix.print();
boolean isWon = checkWinner();
if (isWon) {
String name = winner.equals(TikTocToe.USER_MOVE) ? " USER " : " COMPUTER ";
System.out.println("*** Congratulation *** ");
System.out.println(name + " is the winner ");
break;
}
moveCount++;
}

}


Create a member variable - isTwoPlayer (boolean)


public static boolean isTwoPlayer = false;


In MainClass, the user has to choose whether you prefer a two player game or  you like to play with computer...

To see the full source code, check our previous posts.






No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments